use the base_url and auth data from the configuration to list all courses the user is subscribed to
325631
def get_courses(self):
        
        log.info("Listing Courses...")
        courses = json.loads(self._get('/api/courses').text)["courses"]
        courses = [Course.from_response(course) for course in courses]
        log.debug("Courses: %s" % [str(entry) for entry in courses])
        return courses
650692
def get_sections_for_course(id, opts = {})
      data, _status_code, _headers = get_sections_for_course_with_http_info(id, opts)
      return data
    end
1260773
def all(self, data={}, **kwargs):
        "
        return super(Subscription, self).all(data, **kwargs)
958921
def tutor_courses(self):
        '''
            
        '''
        tutoring = self.user.courses_tutoring.all().filter(active__exact=True)
        owning = self.user.courses.all().filter(active__exact=True)
        result = (tutoring | owning).distinct()
        return result
24306
def list_courses(args):
    
    session = get_session()
    login(session, args.username, args.password)
    extractor = CourseraExtractor(session)
    courses = extractor.list_courses()
    logging.info('Found %d courses', len(courses))
    for course in courses:
        logging.info(course)
1048533
def get_sources_by_member(base_url=BASE_URL_API, limit=LIMIT_DEFAULT):
    
    url = '{}sources-by-member/'.format(base_url)
    page = '{}?{}'.format(url, urlencode({'limit': limit}))
    results = []
    while True:
        data = get_page(page)
        results = results + data['results']
        if data['next']:
            page = data['next']
        else:
            break
    return results
495333
def classes(request):
    """"""

    if not request.user.is_authenticated() or not hasattr(request.user, "userprofile"):
        return render_json(request, {
            'error': _('User is not logged in'),
            'error_type': 'user_unauthorized'
        }, template='user_json.html', status=401)
    clss = [c.to_json() for c in Class.objects.filter(owner=request.user.userprofile)]

    return render_json(request, clss, status=200, template='user_json.html', help_text=classes.__doc__)
1009692
function(subscription_id) {
    var params = {
      client_id:     this._credentials.client_id,
      client_secret: this._credentials.client_secret
    };
    if (subscription_id==='users') {
      params.object = 'user';
    } else if (subscription_id==='all') {
      params.object = 'all';
    } else {
      params.id = subscription_id;
    }
    return params;
  }
1373803
def get_courses_metadata(self):
        
        # Implemented from template for osid.learning.ActivityForm.get_assets_metadata_template
        metadata = dict(self._mdata['courses'])
        metadata.update({'existing_courses_values': self._my_map['courseIds']})
        return Metadata(**metadata)
477136
def get_subscriptions(self, publication_id=None, owner_id=None,
                          since_when=None, limit_to=200, max_calls=None,
                          start_record=0, verbose=False):
        
        query = "SELECT Objects() FROM Subscription"

        # collect all where parameters into a list of
        # (key, operator, value) tuples
        where_params = []

        if owner_id:
            where_params.append(('owner', '=', "'%s'" % owner_id))
        if publication_id:
            where_params.append(('publication', '=', "'%s'" % publication_id))
        if since_when:
            d = datetime.date.today() - datetime.timedelta(days=since_when)
            where_params.append(
                ('LastModifiedDate', ">", "'%s 00:00:00'" % d))

        if where_params:
            query += " WHERE "
            query += " AND ".join(
                ["%s %s %s" % (p[0], p[1], p[2]) for p in where_params])

        subscription_list = self.get_long_query(
            query, limit_to=limit_to, max_calls=max_calls,
            start_record=start_record, verbose=verbose)

        return subscription_list
775880
public function course_list($courses, $unused, $contextcourseid) {
        global $CFG;

        $renderedhtml = '';

        if (empty($courses)) {
            if (isset($courses)) {
                $renderedhtml .= get_string('nocourse', 'block_community');
            }
        } else {
            $courseiteration = 0;
            foreach ($courses as $course) {
                $course = (object) $course;
                $courseiteration = $courseiteration + 1;

                //create visit link html
                if (!empty($course->courseurl)) {
                    $courseurl = new moodle_url($course->courseurl);
                    $linktext = get_string('visitsite', 'block_community');
                } else {
                    $courseurl = new moodle_url($course->demourl);
                    $linktext = get_string('visitdemo', 'block_community');
                }

                $visitlinkhtml = html_writer::tag('a', $linktext,
                                array('href' => $courseurl, 'class' => 'hubcoursedownload',
                                    'onclick' => 'this.target="_blank"'));

                //create title html
                $coursename = html_writer::tag('h3', $course->fullname,
                                array('class' => 'hubcoursetitle'));
                $coursenamehtml = html_writer::tag('div', $coursename,
                        array('class' => 'hubcoursetitlepanel'));

                // create screenshots html
                $screenshothtml = '';
                if (!empty($course->screenshotbaseurl)) {
                    $screenshothtml = html_writer::empty_tag('img',
                        array('src' => $course->screenshotbaseurl, 'alt' => $course->fullname));
                }
                $coursescreenshot = html_writer::tag('div', $screenshothtml,
                                array('class' => 'coursescreenshot',
                                    'id' => 'image-' . $course->id));

                //create description html
                $deschtml = html_writer::tag('div', $course->description,
                                array('class' => 'hubcoursedescription'));

                //create users related information html
                $courseuserinfo = get_string('userinfo', 'block_community', $course);
                if ($course->contributornames) {
                    $courseuserinfo .= ' - ' . get_string('contributors', 'block_community',
                                    $course->contributornames);
                }
                $courseuserinfohtml = html_writer::tag('div', $courseuserinfo,
                                array('class' => 'hubcourseuserinfo'));

                //create course content related information html
                $course->subject = (get_string_manager()->string_exists($course->subject, 'edufields')) ?
                        get_string($course->subject, 'edufields') : get_string('none');
                $course->audience = get_string('audience' . $course->audience, 'hub');
                $course->educationallevel = get_string('edulevel' . $course->educationallevel, 'hub');
                $coursecontentinfo = '';
                if (empty($course->coverage)) {
                    $course->coverage = '';
                } else {
                    $coursecontentinfo .= get_string('coverage', 'block_community', $course->coverage);
                    $coursecontentinfo .= ' - ';
                }
                $coursecontentinfo .= get_string('contentinfo', 'block_community', $course);
                $coursecontentinfohtml = html_writer::tag('div', $coursecontentinfo,
                                array('class' => 'hubcoursecontentinfo'));

                ///create course file related information html
                //language
                if (!empty($course->language)) {
                    $languages = get_string_manager()->get_list_of_languages();
                    $course->lang = $languages[$course->language];
                } else {
                    $course->lang = '';
                }
                //licence
                require_once($CFG->libdir . "/licenselib.php");
                $licensemanager = new license_manager();
                $licenses = $licensemanager->get_licenses();
                foreach ($licenses as $license) {
                    if ($license->shortname == $course->licenceshortname) {
                        $course->license = $license->fullname;
                    }
                }
                $course->timeupdated = userdate($course->timemodified);
                $coursefileinfo = get_string('fileinfo', 'block_community', $course);
                $coursefileinfohtml = html_writer::tag('div', $coursefileinfo,
                                array('class' => 'hubcoursefileinfo'));



                //Create course content html
                $blocks = core_component::get_plugin_list('block');
                $activities = core_component::get_plugin_list('mod');
                if (!empty($course->contents)) {
                    $activitieshtml = '';
                    $blockhtml = '';
                    foreach ($course->contents as $content) {
                        $content = (object) $content;
                        if ($content->moduletype == 'block') {
                            if (!empty($blockhtml)) {
                                $blockhtml .= ' - ';
                            }
                            if (array_key_exists($content->modulename, $blocks)) {
                                $blockname = get_string('pluginname', 'block_' . $content->modulename);
                            } else {
                                $blockname = $content->modulename;
                            }
                            $blockhtml .= $blockname . " (" . $content->contentcount . ")";
                        } else {
                            if (!empty($activitieshtml)) {
                                $activitieshtml .= ' - ';
                            }
                            if (array_key_exists($content->modulename, $activities)) {
                                $activityname = get_string('modulename', $content->modulename);
                            } else {
                                $activityname = $content->modulename;
                            }
                            $activitieshtml .= $activityname . " (" . $content->contentcount . ")";
                        }
                    }

                    $blocksandactivities = html_writer::tag('div',
                                    get_string('activities', 'block_community') . " : " . $activitieshtml);

                    //Uncomment following lines to display blocks information
//                    $blocksandactivities .= html_writer::tag('span',
//                                    get_string('blocks', 'block_community') . " : " . $blockhtml);
                }

                //Create outcomes html
                $outcomes= '';
                if (!empty($course->outcomes)) {
                    foreach ($course->outcomes as $outcome) {
                        if (!empty($outcomes)) {
                            $outcomes .= ', ';
                        }
                        $outcomes .= $outcome['fullname'];
                    }
                    $outcomes = get_string('outcomes', 'block_community',
                            $outcomes);
                }
                $outcomeshtml = html_writer::tag('div', $outcomes, array('class' => 'hubcourseoutcomes'));

                //create additional information html
                $additionaldesc = $courseuserinfohtml . $coursecontentinfohtml
                        . $coursefileinfohtml . $blocksandactivities . $outcomeshtml;
                $additionaldeschtml = html_writer::tag('div', $additionaldesc,
                                array('class' => 'additionaldesc'));

                //Create add button html
                $addbuttonhtml = "";
                if ($course->enrollable) {
                    $params = array('sesskey' => sesskey(), 'add' => 1, 'confirmed' => 1,
                        'coursefullname' => $course->fullname, 'courseurl' => $courseurl,
                        'coursedescription' => $course->description,
                        'courseid' => $contextcourseid);
                    $addurl = new moodle_url("/blocks/community/communitycourse.php", $params);
                    $addbuttonhtml = html_writer::tag('a',
                                    get_string('addtocommunityblock', 'block_community'),
                                    array('href' => $addurl, 'class' => 'centeredbutton, hubcoursedownload'));
                }

                //create download button html
                $downloadbuttonhtml = "";
                if (!$course->enrollable) {
                    $params = array('sesskey' => sesskey(), 'download' => 1, 'confirmed' => 1,
                        'remotemoodleurl' => $CFG->wwwroot, 'courseid' => $contextcourseid,
                        'downloadcourseid' => $course->id,
                        'coursefullname' => $course->fullname, 'backupsize' => $course->backupsize);
                    $downloadurl = new moodle_url("/blocks/community/communitycourse.php", $params);
                    $downloadbuttonhtml = html_writer::tag('a', get_string('install', 'block_community'),
                                    array('href' => $downloadurl, 'class' => 'centeredbutton, hubcoursedownload'));
                }

                //Create rating html
                $rating = html_writer::tag('div', get_string('noratings', 'block_community'),
                                array('class' => 'norating'));
                if (!empty($course->rating)) {
                    $course->rating = (object) $course->rating;
                    if ($course->rating->count > 0) {

                        //calculate size of the rating star
                        $starimagesize = 20; //in px
                        $numberofstars = 5;
                        $size = ($course->rating->aggregate / $course->rating->scaleid)
                                * $numberofstars * $starimagesize;
                        $rating = html_writer::tag('li', '',
                                        array('class' => 'current-rating',
                                            'style' => 'width:' . $size . 'px;'));

                        $rating = html_writer::tag('ul', $rating,
                                        array('class' => 'star-rating clearfix'));
                        $rating .= html_writer::tag('div', ' (' . $course->rating->count . ')',
                                        array('class' => 'ratingcount clearfix'));
                    }
                }


                //Create comments html
                $coursecomments = html_writer::tag('div', get_string('nocomments', 'block_community'),
                                array('class' => 'nocomments'));
                $commentcount = 0;
                if (!empty($course->comments)) {
                    //display only if there is some comment if there is some comment
                    $commentcount = count($course->comments);
                    $coursecomments = html_writer::tag('div',
                                    get_string('comments', 'block_community', $commentcount),
                                    array('class' => 'commenttitle'));

                    foreach ($course->comments as $comment) {
                        $commentator = html_writer::tag('div',
                                        $comment['commentator'],
                                        array('class' => 'hubcommentator'));
                        $commentdate = html_writer::tag('div',
                                        ' - ' . userdate($comment['date'], '%e/%m/%y'),
                                        array('class' => 'hubcommentdate clearfix'));

                        $commenttext = html_writer::tag('div',
                                        $comment['comment'],
                                        array('class' => 'hubcommenttext'));

                        $coursecomments .= html_writer::tag('div',
                                        $commentator . $commentdate . $commenttext,
                                        array('class' => 'hubcomment'));
                    }
                    $coursecommenticon = html_writer::tag('div',
                                    get_string('comments', 'block_community', $commentcount),
                                    array('class' => 'hubcoursecomments',
                                        'id' => 'comments-' . $course->id));
                    $coursecomments = $coursecommenticon . html_writer::tag('div',
                                    $coursecomments,
                                    array('class' => 'yui3-overlay-loading',
                                        'id' => 'commentoverlay-' . $course->id));
                }

                //link rate and comment
                $rateandcomment = html_writer::tag('div',
                                html_writer::link($course->commenturl, get_string('rateandcomment', 'block_community'),
                                            ['onclick' => 'this.target="_blank"']),
                                array('class' => 'hubrateandcomment'));

                //the main DIV tags
                $buttonsdiv = html_writer::tag('div',
                                $addbuttonhtml . $downloadbuttonhtml . $visitlinkhtml,
                                array('class' => 'courseoperations'));
                $screenshotbuttonsdiv = html_writer::tag('div',
                                $coursescreenshot . $buttonsdiv,
                                array('class' => 'courselinks'));

                $coursedescdiv = html_writer::tag('div',
                                $deschtml . $additionaldeschtml
                                . $rating . $coursecomments . $rateandcomment,
                                array('class' => 'coursedescription'));
                $coursehtml =
                        $coursenamehtml . html_writer::tag('div',
                                $coursedescdiv . $screenshotbuttonsdiv,
                                array('class' => 'hubcourseinfo clearfix'));

                $renderedhtml .=html_writer::tag('div', $coursehtml,
                                array('class' => 'fullhubcourse clearfix'));
            }

            $renderedhtml = html_writer::tag('div', $renderedhtml,
                            array('class' => 'hubcourseresult'));
        }

        return $renderedhtml;
    }
803669
def get_queryset(self, request):
        ''' '''
        qs = super(AssignmentAdmin, self).get_queryset(request)
        if not request.user.is_superuser:
            qs = qs.filter(course__active=True).filter(Q(course__tutors__pk=request.user.pk) | Q(course__owner=request.user)).distinct()
        return qs.order_by('title')
1293780
def list_users_in_course_users(self, course_id, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, search_term=None, user_id=None, user_ids=None):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # OPTIONAL - search_term
        """The partial name or full ID of the users to match and return in the results list."""
        if search_term is not None:
            params["search_term"] = search_term

        # OPTIONAL - enrollment_type
        """When set, only return users where the user is enrolled as this type.
        "student_view" implies include[]=test_student.
        This argument is ignored if enrollment_role is given."""
        if enrollment_type is not None:
            self._validate_enum(enrollment_type, ["teacher", "student", "student_view", "ta", "observer", "designer"])
            params["enrollment_type"] = enrollment_type

        # OPTIONAL - enrollment_role
        """Deprecated
        When set, only return users enrolled with the specified course-level role.  This can be
        a role created with the {api:RoleOverridesController#add_role Add Role API} or a
        base role type of 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment',
        'ObserverEnrollment', or 'DesignerEnrollment'."""
        if enrollment_role is not None:
            params["enrollment_role"] = enrollment_role

        # OPTIONAL - enrollment_role_id
        """When set, only return courses where the user is enrolled with the specified
        course-level role.  This can be a role created with the
        {api:RoleOverridesController#add_role Add Role API} or a built_in role id with type
        'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment',
        or 'DesignerEnrollment'."""
        if enrollment_role_id is not None:
            params["enrollment_role_id"] = enrollment_role_id

        # OPTIONAL - include
        """- "email": Optional user email.
        - "enrollments":
        Optionally include with each Course the user's current and invited
        enrollments. If the user is enrolled as a student, and the account has
        permission to manage or view all grades, each enrollment will include a
        'grades' key with 'current_score', 'final_score', 'current_grade' and
        'final_grade' values.
        - "locked": Optionally include whether an enrollment is locked.
        - "avatar_url": Optionally include avatar_url.
        - "bio": Optionally include each user's bio.
        - "test_student": Optionally include the course's Test Student,
        if present. Default is to not include Test Student.
        - "custom_links": Optionally include plugin-supplied custom links for each student,
        such as analytics information"""
        if include is not None:
            self._validate_enum(include, ["email", "enrollments", "locked", "avatar_url", "test_student", "bio", "custom_links"])
            params["include"] = include

        # OPTIONAL - user_id
        """If this parameter is given and it corresponds to a user in the course,
        the +page+ parameter will be ignored and the page containing the specified user
        will be returned instead."""
        if user_id is not None:
            params["user_id"] = user_id

        # OPTIONAL - user_ids
        """If included, the course users set will only include users with IDs
        specified by the param. Note: this will not work in conjunction
        with the "user_id" argument but multiple user_ids can be included."""
        if user_ids is not None:
            params["user_ids"] = user_ids

        # OPTIONAL - enrollment_state
        """When set, only return users where the enrollment workflow state is of one of the given types.
        "active" and "invited" enrollments are returned by default."""
        if enrollment_state is not None:
            self._validate_enum(enrollment_state, ["active", "invited", "rejected", "completed", "inactive"])
            params["enrollment_state"] = enrollment_state

        self.logger.debug("GET /api/v1/courses/{course_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/users".format(**path), data=data, params=params, all_pages=True)
407212
def list(cls, params=None, custom_headers=None):
        

        if params is None:
            params = {}

        if custom_headers is None:
            custom_headers = {}

        api_client = client.ApiClient(cls._get_api_context())
        endpoint_url = cls._ENDPOINT_URL_LISTING.format(
            cls._determine_user_id())
        response_raw = api_client.get(endpoint_url, params, custom_headers)

        return BunqResponseOauthClientList.cast_from_bunq_response(
            cls._from_json_list(response_raw, cls._OBJECT_TYPE_GET)
        )
343165
public static function get_enrolled_users($courseid, $options = array()) {
        global $CFG, $USER, $DB;

        require_once($CFG->dirroot . '/course/lib.php');
        require_once($CFG->dirroot . "/user/lib.php");

        $params = self::validate_parameters(
            self::get_enrolled_users_parameters(),
            array(
                'courseid'=>$courseid,
                'options'=>$options
            )
        );
        $withcapability = '';
        $groupid        = 0;
        $onlyactive     = false;
        $userfields     = array();
        $limitfrom = 0;
        $limitnumber = 0;
        $sortby = 'us.id';
        $sortparams = array();
        $sortdirection = 'ASC';
        foreach ($options as $option) {
            switch ($option['name']) {
            case 'withcapability':
                $withcapability = $option['value'];
                break;
            case 'groupid':
                $groupid = (int)$option['value'];
                break;
            case 'onlyactive':
                $onlyactive = !empty($option['value']);
                break;
            case 'userfields':
                $thefields = explode(',', $option['value']);
                foreach ($thefields as $f) {
                    $userfields[] = clean_param($f, PARAM_ALPHANUMEXT);
                }
                break;
            case 'limitfrom' :
                $limitfrom = clean_param($option['value'], PARAM_INT);
                break;
            case 'limitnumber' :
                $limitnumber = clean_param($option['value'], PARAM_INT);
                break;
            case 'sortby':
                $sortallowedvalues = array('id', 'firstname', 'lastname', 'siteorder');
                if (!in_array($option['value'], $sortallowedvalues)) {
                    throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $option['value'] . '),' .
                        'allowed values are: ' . implode(',', $sortallowedvalues));
                }
                if ($option['value'] == 'siteorder') {
                    list($sortby, $sortparams) = users_order_by_sql('us');
                } else {
                    $sortby = 'us.' . $option['value'];
                }
                break;
            case 'sortdirection':
                $sortdirection = strtoupper($option['value']);
                $directionallowedvalues = array('ASC', 'DESC');
                if (!in_array($sortdirection, $directionallowedvalues)) {
                    throw new invalid_parameter_exception('Invalid value for sortdirection parameter
                        (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
                }
                break;
            }
        }

        $course = $DB->get_record('course', array('id'=>$courseid), '*', MUST_EXIST);
        $coursecontext = context_course::instance($courseid, IGNORE_MISSING);
        if ($courseid == SITEID) {
            $context = context_system::instance();
        } else {
            $context = $coursecontext;
        }
        try {
            self::validate_context($context);
        } catch (Exception $e) {
            $exceptionparam = new stdClass();
            $exceptionparam->message = $e->getMessage();
            $exceptionparam->courseid = $params['courseid'];
            throw new moodle_exception('errorcoursecontextnotvalid' , 'webservice', '', $exceptionparam);
        }

        course_require_view_participants($context);

        // to overwrite this parameter, you need role:review capability
        if ($withcapability) {
            require_capability('moodle/role:review', $coursecontext);
        }
        // need accessallgroups capability if you want to overwrite this option
        if (!empty($groupid) && !groups_is_member($groupid)) {
            require_capability('moodle/site:accessallgroups', $coursecontext);
        }
        // to overwrite this option, you need course:enrolereview permission
        if ($onlyactive) {
            require_capability('moodle/course:enrolreview', $coursecontext);
        }

        list($enrolledsql, $enrolledparams) = get_enrolled_sql($coursecontext, $withcapability, $groupid, $onlyactive);
        $ctxselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
        $ctxjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = u.id AND ctx.contextlevel = :contextlevel)";
        $enrolledparams['contextlevel'] = CONTEXT_USER;

        $groupjoin = '';
        if (empty($groupid) && groups_get_course_groupmode($course) == SEPARATEGROUPS &&
                !has_capability('moodle/site:accessallgroups', $coursecontext)) {
            // Filter by groups the user can view.
            $usergroups = groups_get_user_groups($course->id);
            if (!empty($usergroups['0'])) {
                list($groupsql, $groupparams) = $DB->get_in_or_equal($usergroups['0'], SQL_PARAMS_NAMED);
                $groupjoin = "JOIN {groups_members} gm ON (u.id = gm.userid AND gm.groupid $groupsql)";
                $enrolledparams = array_merge($enrolledparams, $groupparams);
            } else {
                // User doesn't belong to any group, so he can't see any user. Return an empty array.
                return array();
            }
        }
        $sql = "SELECT us.*, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
                  FROM {user} us
                  JOIN (
                      SELECT DISTINCT u.id $ctxselect
                        FROM {user} u $ctxjoin $groupjoin
                       WHERE u.id IN ($enrolledsql)
                  ) q ON q.id = us.id
             LEFT JOIN {user_lastaccess} ul ON (ul.userid = us.id AND ul.courseid = :courseid)
                ORDER BY $sortby $sortdirection";
        $enrolledparams = array_merge($enrolledparams, $sortparams);
        $enrolledparams['courseid'] = $courseid;

        $enrolledusers = $DB->get_recordset_sql($sql, $enrolledparams, $limitfrom, $limitnumber);
        $users = array();
        foreach ($enrolledusers as $user) {
            context_helper::preload_from_record($user);
            if ($userdetails = user_get_user_details($user, $course, $userfields)) {
                $users[] = $userdetails;
            }
        }
        $enrolledusers->close();

        return $users;
    }
415886
def POST(self):  # pylint: disable=arguments-differ
        
        if not self.app.welcome_page:
            raise web.seeother("/courselist")
        return self.show_page(self.app.welcome_page)
5916
def list_courses(self):
        
        course = CourseraOnDemand(session=self._session,
                                  course_id=None,
                                  course_name=None)
        return course.list_courses()