r"""Return a list of :class:`EighthScheduledActivity`\s in which the
    given user is sponsoring.

    Returns:
        Dictionary with:
            activities
            no_attendance_today
            num_acts
439356
def gen_sponsor_schedule(user, sponsor=None, num_blocks=6, surrounding_blocks=None, given_date=None):
    
    """

    no_attendance_today = None
    acts = []

    if sponsor is None:
        sponsor = user.get_eighth_sponsor()

    if surrounding_blocks is None:
        surrounding_blocks = EighthBlock.objects.get_upcoming_blocks(num_blocks)

    activities_sponsoring = (EighthScheduledActivity.objects.for_sponsor(sponsor).select_related("block").filter(block__in=surrounding_blocks))
    sponsoring_block_map = {}
    for sa in activities_sponsoring:
        bid = sa.block.id
        if bid in sponsoring_block_map:
            sponsoring_block_map[bid] += [sa]
        else:
            sponsoring_block_map[bid] = [sa]

    num_acts = 0

    for b in surrounding_blocks:
        num_added = 0
        sponsored_for_block = sponsoring_block_map.get(b.id, [])

        for schact in sponsored_for_block:
            acts.append(schact)
            if schact.block.is_today():
                if not schact.attendance_taken and schact.block.locked:
                    no_attendance_today = True

            num_added += 1

        if num_added == 0:
            # fake an entry for a block where there is no sponsorship
            acts.append({"block": b, "id": None, "fake": True})
        else:
            num_acts += 1

    logger.debug(acts)

    cur_date = surrounding_blocks[0].date if acts else given_date if given_date else datetime.now().date()

    last_block = surrounding_blocks[len(surrounding_blocks) - 1] if surrounding_blocks else None
    last_block_date = last_block.date + timedelta(days=1) if last_block else cur_date
    next_blocks = list(last_block.next_blocks(1)) if last_block else None
    next_date = next_blocks[0].date if next_blocks else last_block_date

    first_block = surrounding_blocks[0] if surrounding_blocks else None
    if cur_date and not first_block:
        first_block = EighthBlock.objects.filter(date__lte=cur_date).last()
    first_block_date = first_block.date + timedelta(days=-7) if first_block else cur_date
    prev_blocks = list(first_block.previous_blocks(num_blocks - 1)) if first_block else None
    prev_date = prev_blocks[0].date if prev_blocks else first_block_date
    return {
        "sponsor_schedule": acts,
        "no_attendance_today": no_attendance_today,
        "num_attendance_acts": num_acts,
        "sponsor_schedule_cur_date": cur_date,
        "sponsor_schedule_next_date": next_date,
        "sponsor_schedule_prev_date": prev_date
    }
1182240
def minicalendar(context):
    
    today = dt.date.today()
    request = context['request']
    home = request.site.root_page
    cal = CalendarPage.objects.live().descendant_of(home).first()
    calUrl = cal.get_url(request) if cal else None
    if cal:
        events = cal._getEventsByWeek(request, today.year, today.month)
    else:
        events = getAllEventsByWeek(request, today.year, today.month)
    return {'request':     request,
            'today':       today,
            'year':        today.year,
            'month':       today.month,
            'calendarUrl': calUrl,
            'monthName':   calendar.month_name[today.month],
            'weekdayInfo': zip(weekday_abbr, weekday_name),
            'events':      events}
432702
def activities_list(self, since=None, **kwargs):
        ""
        api_path = "/api/v2/activities.json"
        api_query = {}
        if "query" in kwargs.keys():
            api_query.update(kwargs["query"])
            del kwargs["query"]
        if since:
            api_query.update({
                "since": since,
            })
        return self.call(api_path, query=api_query, **kwargs)
426213
async def listCronJobs(self):
        '''
        
        '''
        crons = []
        for iden, cron in self.cell.agenda.list():
            useriden = cron['useriden']
            if not (self.user.admin or useriden == self.user.iden):
                continue
            user = self.cell.auth.user(useriden)
            cron['username'] = '<unknown>' if user is None else user.name
            crons.append((iden, cron))

        return crons
977580
def user_activities(username, tournament=1):
    """"""
    click.echo(prettify(napi.get_user_activities(username, tournament)))
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
1330447
def get_activity(self, id_num):
        
        url = self._build_url('my', 'activities', id_num)
        return self._json(url)
370738
def subscriptions(self):
        """"""
        if not hasattr(self, '_subscriptions'):
            subscriptions_resource = self.resource.subscriptions
            self._subscriptions = Subscriptions(
                subscriptions_resource, self.client)
        return self._subscriptions
506127
def cancel(self):
        
        # super(EighthScheduledActivity, self).save(*args, **kwargs)

        logger.debug("Running cancel hooks: {}".format(self))

        if not self.cancelled:
            logger.debug("Cancelling {}".format(self))
            self.cancelled = True
        self.save()
        # NOT USED. Was broken anyway.
        """
        cancelled_room = EighthRoom.objects.get_or_create(name="CANCELLED", capacity=0)[0]
        cancelled_sponsor = EighthSponsor.objects.get_or_create(first_name="", last_name="CANCELLED")[0]
        if cancelled_room not in list(self.rooms.all()):
            self.rooms.all().delete()
            self.rooms.add(cancelled_room)

        if cancelled_sponsor not in list(self.sponsors.all()):
            self.sponsors.all().delete()
            self.sponsors.add(cancelled_sponsor)

        self.save()
        """
266783
def active_inactive(self):
        """"""
        active_indices = []
        inactive_indices = []
        for index, active in enumerate(self.active):
            if active:
                active_indices.append(index)
            else:
                inactive_indices.append(index)
        return active_indices, inactive_indices
483610
def get_current_tournaments():
    """"""

    schedule_page = requests.get(TOURNAMENTS_XML_URL)
    root = etree.XML(schedule_page.content)

    for tour in root.iter('{*}tournament'):
        yield _Tournament(
            start_date=tour.findtext('{*}start_date'),
            name=tour.findtext('{*}name'),
            game=tour.findtext('{*}game'),
            buyin=tour.findtext('{*}buy_in_fee'),
            players=tour.get('players')
        )
617803
def __parse_enrollments(self, user):
        """"""

        enrollments = []

        for company in user['companies']:
            name = company['company_name']

            org = self._organizations.get(name, None)

            if not org:
                org = Organization(name=name)
                self._organizations[name] = org

            start_date = MIN_PERIOD_DATE
            end_date = MAX_PERIOD_DATE

            if company['end_date']:
                end_date = str_to_datetime(company['end_date'])

            rol = Enrollment(start=start_date, end=end_date,
                             organization=org)
            enrollments.append(rol)

        return enrollments
1050871
def get_scheduling_block(sub_array_id, block_id):
    """"""
    block_ids = DB.get_sub_array_sbi_ids(sub_array_id)
    if block_id in block_ids:
        block = DB.get_block_details([block_id]).__next__()
        return block, HTTPStatus.OK

    return dict(error="unknown id"), HTTPStatus.NOT_FOUND
768441
def get_current_activities(self, login=None, **kwargs):
        

        _login = kwargs.get(
            'login',
            login or self._login
        )
        _activity_url = ACTIVITY_URL.format(login=_login)
        return self._request_api(url=_activity_url).json()
513513
def get_notifications(user):
    ''''''
    notifications = []

    for name, func in _providers.items():
        notifications.extend([{
            'type': name,
            'created_on': dt,
            'details': details
        } for dt, details in func(user)])

    return notifications
628213
def get_days_off(transactions):
    
    days_off = []
    for trans in transactions:
        date, action, _ = _parse_transaction_entry(trans)
        if action == 'off':
            days_off.append(date)
    return days_off
529001
def __get_activities(self, search):
        """"""

        query = """
                   SELECT a.name AS name, b.name AS category
                     FROM activities a
                LEFT JOIN categories b ON coalesce(b.id, -1) = a.category_id
                LEFT JOIN facts f ON a.id = f.activity_id
                    WHERE deleted IS NULL
                      AND a.search_name LIKE ? ESCAPE '\\'
                 GROUP BY a.id
                 ORDER BY max(f.start_time) DESC, lower(a.name)
                    LIMIT 50
        """
        search = search.lower()
        search = search.replace('\\', '\\\\').replace('%', '\\%').replace('_', '\\_')
        activities = self.fetchall(query, ('%s%%' % search, ))

        return activities