List calendar events.

        Retrieve the list of calendar events or assignments for the current user
166419
def list_calendar_events(self, all_events=None, context_codes=None, end_date=None, excludes=None, start_date=None, type=None, undated=None):
        
        path = {}
        data = {}
        params = {}

        # OPTIONAL - type
        """Defaults to "event""""
        if type is not None:
            self._validate_enum(type, ["event", "assignment"])
            params["type"] = type

        # OPTIONAL - start_date
        """Only return events since the start_date (inclusive).
        Defaults to today. The value should be formatted as: yyyy-mm-dd or ISO 8601 YYYY-MM-DDTHH:MM:SSZ."""
        if start_date is not None:
            params["start_date"] = start_date

        # OPTIONAL - end_date
        """Only return events before the end_date (inclusive).
        Defaults to start_date. The value should be formatted as: yyyy-mm-dd or ISO 8601 YYYY-MM-DDTHH:MM:SSZ.
        If end_date is the same as start_date, then only events on that day are
        returned."""
        if end_date is not None:
            params["end_date"] = end_date

        # OPTIONAL - undated
        """Defaults to false (dated events only).
        If true, only return undated events and ignore start_date and end_date."""
        if undated is not None:
            params["undated"] = undated

        # OPTIONAL - all_events
        """Defaults to false (uses start_date, end_date, and undated criteria).
        If true, all events are returned, ignoring start_date, end_date, and undated criteria."""
        if all_events is not None:
            params["all_events"] = all_events

        # OPTIONAL - context_codes
        """List of context codes of courses/groups/users whose events you want to see.
        If not specified, defaults to the current user (i.e personal calendar,
        no course/group events). Limited to 10 context codes, additional ones are
        ignored. The format of this field is the context type, followed by an
        underscore, followed by the context id. For example: course_42"""
        if context_codes is not None:
            params["context_codes"] = context_codes

        # OPTIONAL - excludes
        """Array of attributes to exclude. Possible values are "description", "child_events" and "assignment""""
        if excludes is not None:
            params["excludes"] = excludes

        self.logger.debug("GET /api/v1/calendar_events with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/calendar_events".format(**path), data=data, params=params, all_pages=True)
661837
def toList(self):
        
        date = self.date()
        sign = '+' if date[0] >= 0 else '-'
        date[0] = abs(date[0])
        return list(sign) + date
1293305
def _getEventsByWeek(self, request, year, month):
        """"""
        return getAllEventsByWeek(request, year, month, home=self)
79639
def activity_list(date, sort, limit)
      date_param = format_date(date)
      if sort == "asc"
        date_param = "afterDate=#{date_param}"
      elsif sort == "desc"
        date_param = "beforeDate=#{date_param}"
      else
        raise FitgemOauth2::InvalidArgumentError, "sort can either be asc or desc"
      end
      get_call("user/#{user_id}/activities/list.json?offset=0&limit=#{limit}&sort=#{sort}&#{date_param}")
    end
143591
def _getEventsByDay(self, request, firstDay, lastDay):
        
        return getAllEventsByDay(request, firstDay, lastDay, home=self)
776061
def get_active_schedulings(self):
        """"""
        blocks = EighthBlock.objects.get_blocks_this_year()
        scheduled_activities = EighthScheduledActivity.objects.filter(activity=self)
        scheduled_activities = scheduled_activities.filter(block__in=blocks)

        return scheduled_activities
548362
def lists_submissions(self, date, course_id, grader_id, assignment_id):
        
        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """The id of the contextual course for this API call"""
        path["course_id"] = course_id

        # REQUIRED - PATH - date
        """The date for which you would like to see submissions"""
        path["date"] = date

        # REQUIRED - PATH - grader_id
        """The ID of the grader for which you want to see submissions"""
        path["grader_id"] = grader_id

        # REQUIRED - PATH - assignment_id
        """The ID of the assignment for which you want to see submissions"""
        path["assignment_id"] = assignment_id

        self.logger.debug("GET /api/v1/courses/{course_id}/gradebook_history/{date}/graders/{grader_id}/assignments/{assignment_id}/submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/gradebook_history/{date}/graders/{grader_id}/assignments/{assignment_id}/submissions".format(**path), data=data, params=params, all_pages=True)
1128703
def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=12):
        
        params = {
            'year': str(starting_year),
            'listing_id': str(listing_id),
            '_format': 'with_conditions',
            'count': str(calendar_months),
            'month': str(starting_month)
        }

        r = self._session.get(API_URL + "/calendar_months", params=params)
        r.raise_for_status()

        return r.json()
953383
def getListForEvent(self, event=None):
        '''  '''
        names = list(self.guestlistname_set.annotate(
            guestType=Case(
                When(notes__isnull=False, then=F('notes')),
                default=Value(ugettext('Manually Added')),
                output_field=models.CharField()
            )
        ).values('firstName','lastName','guestType'))

        # Component-by-component, OR append filters to an initial filter that always
        # evaluates to False.
        components = self.guestlistcomponent_set.all()
        filters = Q(pk__isnull=True)

        # Add prior staff based on the component rule.
        for component in components:
            if event and self.appliesToEvent(event):
                filters = filters | self.getComponentFilters(component,event=event)
            else:
                filters = filters | self.getComponentFilters(component,dateTime=timezone.now())

        # Add all event staff if that box is checked (no need for separate components)
        if self.includeStaff and event and self.appliesToEvent(event):
            filters = filters | Q(eventstaffmember__event=event)

        # Execute the constructed query and add the names of staff
        names += list(StaffMember.objects.filter(filters).annotate(
            guestType=Case(
                When(eventstaffmember__event=event, then=Concat(Value('Event Staff: '), 'eventstaffmember__category__name')),
                default=Value(ugettext('Other Staff')),
                output_field=models.CharField()
            )
        ).distinct().values('firstName','lastName','guestType'))

        if self.includeRegistrants and event and self.appliesToEvent(event):
            names += list(Registration.objects.filter(eventregistration__event=event).annotate(
                guestType=Value(_('Registered'),output_field=models.CharField())
            ).values('firstName','lastName','guestType'))
        return names
637460
def get_event_list(config):
    """"""
    eventinstances = session_request(
        config.session.post, device_event_url.format(
            proto=config.web_proto, host=config.host, port=config.port),
        auth=config.session.auth, headers=headers, data=request_xml)

    raw_event_list = _prepare_event(eventinstances)

    event_list = {}
    for entry in MAP + METAMAP:
        instance = raw_event_list
        try:
            for item in sum(entry[MAP_BASE].values(), []):
                instance = instance[item]
        except KeyError:
            continue
        event_list[entry[MAP_TYPE]] = instance

    return event_list
1129781
def getAllUpcomingEvents(request, *, home=None):
    
    qrys = [SimpleEventPage.events(request).upcoming().this(),
            MultidayEventPage.events(request).upcoming().this(),
            RecurringEventPage.events(request).upcoming().this(),
            PostponementPage.events(request).upcoming().this(),
            ExtraInfoPage.events(request).exclude(extra_title="").upcoming()
                                         .this()]
    if home is not None:
        qrys = [qry.descendant_of(home) for qry in qrys]
    events = sorted(chain.from_iterable(qrys),
                    key=attrgetter('page._upcoming_datetime_from'))
    return events
1064304
def get_upcoming_events_within_the_current_week(self):
        ''''''
        now = datetime.now(tz=self.timezone) # timezone?
        start_time = datetime(year=now.year, month=now.month, day=now.day, hour=now.hour, minute=now.minute, second=now.second, tzinfo=self.timezone)
        end_time = start_time + timedelta(days = 6 - now.weekday())
        end_time = datetime(year = end_time.year, month = end_time.month, day = end_time.day, hour=23, minute=59, second=59, tzinfo=self.timezone)
        assert(end_time.weekday() == 6)
        start_time = start_time.isoformat()
        end_time = end_time.isoformat()
        return self.get_events(start_time, end_time)
1298767
public static function get_calendar_events($events = array(), $options = array()) {
        global $SITE, $DB, $USER;

        // Parameter validation.
        $params = self::validate_parameters(self::get_calendar_events_parameters(), array('events' => $events, 'options' => $options));
        $funcparam = array('courses' => array(), 'groups' => array(), 'categories' => array());
        $hassystemcap = has_capability('moodle/calendar:manageentries', context_system::instance());
        $warnings = array();
        $coursecategories = array();

        // Let us find out courses and their categories that we can return events from.
        if (!$hassystemcap) {
            $courseobjs = enrol_get_my_courses();
            $courses = array_keys($courseobjs);

            $coursecategories = array_flip(array_map(function($course) {
                return $course->category;
            }, $courseobjs));

            foreach ($params['events']['courseids'] as $id) {
               try {
                    $context = context_course::instance($id);
                    self::validate_context($context);
                    $funcparam['courses'][] = $id;
                } catch (Exception $e) {
                    $warnings[] = array(
                        'item' => 'course',
                        'itemid' => $id,
                        'warningcode' => 'nopermissions',
                        'message' => 'No access rights in course context '.$e->getMessage().$e->getTraceAsString()
                    );
                }
            }
        } else {
            $courses = $params['events']['courseids'];
            $funcparam['courses'] = $courses;

            if (!empty($courses)) {
                list($wheresql, $sqlparams) = $DB->get_in_or_equal($courses);
                $wheresql = "id $wheresql";
                $coursecategories = array_flip(array_map(function($course) {
                    return $course->category;
                }, $DB->get_records_select('course', $wheresql, $sqlparams, '', 'category')));
            }
        }

        // Let us findout groups that we can return events from.
        if (!$hassystemcap) {
            $groups = groups_get_my_groups();
            $groups = array_keys($groups);
            foreach ($params['events']['groupids'] as $id) {
                if (in_array($id, $groups)) {
                    $funcparam['groups'][] = $id;
                } else {
                    $warnings[] = array('item' => $id, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to access this group');
                }
            }
        } else {
            $groups = $params['events']['groupids'];
            $funcparam['groups'] = $groups;
        }

        $categories = array();
        if ($hassystemcap || !empty($courses)) {
            // Use the category id as the key in the following array. That way we do not have to remove duplicates and
            // have a faster lookup later.
            $categories = [];

            if (!empty($params['events']['categoryids'])) {
                $catobjs = \core_course_category::get_many(
                    array_merge($params['events']['categoryids'], array_keys($coursecategories)));
                foreach ($catobjs as $catobj) {
                    if (isset($coursecategories[$catobj->id]) ||
                            has_capability('moodle/category:manage', $catobj->get_context())) {
                        // If the user has access to a course in this category or can manage the category,
                        // then they can see all parent categories too.
                        $categories[$catobj->id] = true;
                        foreach ($catobj->get_parents() as $catid) {
                            $categories[$catid] = true;
                        }
                    }
                }
                $funcparam['categories'] = array_keys($categories);
            } else {
                // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
                $calcatcache = cache::make('core', 'calendar_categories');
                // Do not use cache if the user has the system capability as $coursecategories might not represent the
                // courses the user is enrolled in.
                $categories = (!$hassystemcap) ? $calcatcache->get('site') : false;
                if ($categories !== false) {
                    // The ids are stored in a list in the cache.
                    $funcparam['categories'] = $categories;
                    $categories = array_flip($categories);
                } else {
                    $categories = [];
                    foreach (\core_course_category::get_all() as $category) {
                        if (isset($coursecategories[$category->id]) ||
                                has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
                            // If the user has access to a course in this category or can manage the category,
                            // then they can see all parent categories too.
                            $categories[$category->id] = true;
                            foreach ($category->get_parents() as $catid) {
                                $categories[$catid] = true;
                            }
                        }
                    }
                    $funcparam['categories'] = array_keys($categories);
                    if (!$hassystemcap) {
                        $calcatcache->set('site', $funcparam['categories']);
                    }
                }
            }
        }

        // Do we need user events?
        if (!empty($params['options']['userevents'])) {
            $funcparam['users'] = array($USER->id);
        } else {
            $funcparam['users'] = false;
        }

        // Do we need site events?
        if (!empty($params['options']['siteevents'])) {
            $funcparam['courses'][] = $SITE->id;
        }

        // We treat 0 and null as no end.
        if (empty($params['options']['timeend'])) {
            $params['options']['timeend'] = PHP_INT_MAX;
        }

        // Event list does not check visibility and permissions, we'll check that later.
        $eventlist = calendar_get_legacy_events($params['options']['timestart'], $params['options']['timeend'],
                $funcparam['users'], $funcparam['groups'], $funcparam['courses'], true,
                $params['options']['ignorehidden'], $funcparam['categories']);

        // WS expects arrays.
        $events = array();

        // We need to get events asked for eventids.
        if ($eventsbyid = calendar_get_events_by_id($params['events']['eventids'])) {
            $eventlist += $eventsbyid;
        }
        foreach ($eventlist as $eventid => $eventobj) {
            $event = (array) $eventobj;
            // Description formatting.
            $calendareventobj = new calendar_event($event);
            list($event['description'], $event['format']) = $calendareventobj->format_external_text();

            if ($hassystemcap) {
                // User can see everything, no further check is needed.
                $events[$eventid] = $event;
            } else if (!empty($eventobj->modulename)) {
                $courseid = $eventobj->courseid;
                if (!$courseid) {
                    if (!$calendareventobj->context || !($context = $calendareventobj->context->get_course_context(false))) {
                        continue;
                    }
                    $courseid = $context->instanceid;
                }
                $instances = get_fast_modinfo($courseid)->get_instances_of($eventobj->modulename);
                if (!empty($instances[$eventobj->instance]->uservisible)) {
                    $events[$eventid] = $event;
                }
            } else {
                // Can the user actually see this event?
                $eventobj = calendar_event::load($eventobj);
                if ((($eventobj->courseid == $SITE->id) && (empty($eventobj->categoryid))) ||
                            (!empty($eventobj->categoryid) && isset($categories[$eventobj->categoryid])) ||
                            (!empty($eventobj->groupid) && in_array($eventobj->groupid, $groups)) ||
                            (!empty($eventobj->courseid) && in_array($eventobj->courseid, $courses)) ||
                            ($USER->id == $eventobj->userid) ||
                            (calendar_edit_event_allowed($eventobj))) {
                    $events[$eventid] = $event;
                } else {
                    $warnings[] = array('item' => $eventid, 'warningcode' => 'nopermissions', 'message' => 'you do not have permissions to view this event');
                }
            }
        }
        return array('events' => $events, 'warnings' => $warnings);
    }
1108739
def calendars(self):
        
        today = datetime.today()
        first_day, last_day = monthrange(today.year, today.month)
        from_dt = datetime(today.year, today.month, first_day)
        to_dt = datetime(today.year, today.month, last_day)
        params = dict(self.params)
        params.update({
            'lang': 'en-us',
            'usertz': get_localzone().zone,
            'startDate': from_dt.strftime('%Y-%m-%d'),
            'endDate': to_dt.strftime('%Y-%m-%d')
        })
        req = self.session.get(self._calendars, params=params)
        self.response = req.json()
        return self.response['Collection']
1096403
def search(self, user, since, until, target_type, action_name):
        
        if not self.user:
            self.user = self.get_user(user)
        if not self.events:
            self.events = self.user_events(self.user['id'], since, until)
        result = []
        for event in self.events:
            created_at = dateutil.parser.parse(event['created_at']).date()
            if (event['target_type'] == target_type and
                    event['action_name'] == action_name and
                    since.date <= created_at and until.date >= created_at):
                result.append(event)
        log.debug("Result: {0} fetched".format(listed(len(result), "item")))
        return result
1238045
def events(cls, filters):
        """"""
        current = filters.pop('current', False)
        current_params = []
        if current:
            current_params = [('current', 'true')]

        filter_url = uparse.urlencode(sorted(list(filters.items())) + current_params)  # noqa
        events = cls.json_get('%s/events?%s' % (cls.api_url, filter_url),
                              empty_key=True, send_key=False)
        return events
1278582
def write_items(self, calendar):
        
        for item in self.items:
            event = Event()
            for ifield, efield in ITEM_EVENT_FIELD_MAP:
                val = item.get(ifield)
                if val is not None:
                    event.add(efield, val)
            calendar.add_component(event)