Exemplo n.º 1
0
def period(request, period_id=None):
    base = base_ctx('Ranking', 'Current', request)

    # {{{ Get period object
    if not period_id:
        period = base['curp']
    else:
        period = get_object_or_404(Period, id=period_id, computed=True)

    if period.is_preview():
        base['messages'].append(Message(msg_preview % cdate(period.end, _('F jS')), type=Message.INFO))

    base['period'] = period
    if period.id != base['curp'].id:
        base['curpage'] = ''
    # }}}

    # {{{ Best and most specialised players
    qset = total_ratings(filter_active(Rating.objects.filter(period=period))).select_related('player')
    qsetp = qset.filter(player__race=P)
    qsett = qset.filter(player__race=T)
    qsetz = qset.filter(player__race=Z)
    base.update({
        'best':     qset.latest('rating'),
        'bestvp':   qset.latest('tot_vp'),
        'bestvt':   qset.latest('tot_vt'),
        'bestvz':   qset.latest('tot_vz'),
        'bestp':    qsetp.latest('rating'),
        'bestpvp':  qsetp.latest('tot_vp'),
        'bestpvt':  qsetp.latest('tot_vt'),
        'bestpvz':  qsetp.latest('tot_vz'),
        'bestt':    qsett.latest('rating'),
        'besttvp':  qsett.latest('tot_vp'),
        'besttvt':  qsett.latest('tot_vt'),
        'besttvz':  qsett.latest('tot_vz'),
        'bestz':    qsetz.latest('rating'),
        'bestzvp':  qsetz.latest('tot_vp'),
        'bestzvt':  qsetz.latest('tot_vt'),
        'bestzvz':  qsetz.latest('tot_vz'),
        'specvp':   qset.extra(select={'d':   'rating_vp/dev_vp*(rating+1.5)'}).latest('d'),
        'specvt':   qset.extra(select={'d':   'rating_vt/dev_vt*(rating+1.5)'}).latest('d'),
        'specvz':   qset.extra(select={'d':   'rating_vz/dev_vz*(rating+1.5)'}).latest('d'),
        'specpvp':  qsetp.extra(select={'d':  'rating_vp/dev_vp*(rating+1.5)'}).latest('d'),
        'specpvt':  qsetp.extra(select={'d':  'rating_vt/dev_vt*(rating+1.5)'}).latest('d'),
        'specpvz':  qsetp.extra(select={'d':  'rating_vz/dev_vz*(rating+1.5)'}).latest('d'),
        'spectvp':  qsett.extra(select={'d':  'rating_vp/dev_vp*(rating+1.5)'}).latest('d'),
        'spectvt':  qsett.extra(select={'d':  'rating_vt/dev_vt*(rating+1.5)'}).latest('d'),
        'spectvz':  qsett.extra(select={'d':  'rating_vz/dev_vz*(rating+1.5)'}).latest('d'),
        'speczvp':  qsetz.extra(select={'d':  'rating_vp/dev_vp*(rating+1.5)'}).latest('d'),
        'speczvt':  qsetz.extra(select={'d':  'rating_vt/dev_vt*(rating+1.5)'}).latest('d'),
        'speczvz':  qsetz.extra(select={'d':  'rating_vz/dev_vz*(rating+1.5)'}).latest('d'),
    })
    # }}}

    # {{{ Highest gainer and biggest losers

    # TODO: Fix these queries, highly dependent on the way django does things.
    gainers = filter_active(Rating.objects.filter(period=period))\
        .filter(prev__isnull=False)\
        .select_related('prev', 'player')\
        .extra(select={'diff': 'rating.rating - T3.rating'})\
        .order_by('-diff')
    losers = filter_active(Rating.objects.filter(period=period))\
        .filter(prev__isnull=False)\
        .select_related('prev', 'player')\
        .extra(select={'diff': 'rating.rating - T3.rating'})\
        .order_by('diff')

    base.update({
        'gainers': gainers[:5],
        'losers': losers[:5]
    })
    # }}}

    # {{{ Matchup statistics
    qset = period.match_set
    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(qset, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(qset, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(qset, 'T', 'Z')
    base.update({
        'pvp_games': count_mirror_games(qset, 'P'),
        'tvt_games': count_mirror_games(qset, 'T'),
        'zvz_games': count_mirror_games(qset, 'Z'),
    })

    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base['zvz_games']
    # }}}

    # {{{ Build country list
    all_players = Player.objects.filter(rating__period_id=period.id, rating__decay__lt=INACTIVE_THRESHOLD)
    base['countries'] = country_list(all_players)
    # }}}

    # {{{ Initial filtering of ratings
    entries = filter_active(period.rating_set).select_related('player')

    # Race filter
    race = get_param(request, 'race', 'ptzrs')
    q = Q()
    for r in race:
        q |= Q(player__race=r.upper())
    entries = entries.filter(q)

    # Country filter
    nats = get_param(request, 'nats', 'all')
    if nats == 'foreigners':
        entries = entries.exclude(player__country='KR')
    elif nats != 'all':
        entries = entries.filter(player__country=nats)

    # Sorting
    sort = get_param(request, 'sort', '')
    if sort not in ['vp', 'vt', 'vz']: 
        entries = entries.order_by('-rating', 'player__tag')
    else:
        entries = entries.extra(select={'d':'rating+rating_'+sort}).order_by('-d', 'player__tag')

    entries = entries.prefetch_related('prev')

    base.update({
        'race': race,
        'nats': nats,
        'sort': sort,
    })
    # }}}

    # {{{ Pages etc.
    pagesize = SHOW_PER_LIST_PAGE
    page = int(get_param(request, 'page', 1))
    nitems = entries.count()
    npages = nitems//pagesize + (1 if nitems % pagesize > 0 else 0)
    page = min(max(page, 1), npages)
    entries = entries[(page-1)*pagesize : page*pagesize] if page > 0 else []

    base.update({
        'page':       page,
        'npages':     npages,
        'startcount': (page-1)*pagesize,
        'entries':    populate_teams(entries),
        'nperiods':   Period.objects.filter(computed=True).count(),
    })
    # }}}

    base.update({
        'sortable':   True,
        'localcount': True,
    })
        
    fmt_date = django_date_filter(period.end, "F jS, Y")
    # Translators: List (number): (date)
    base.update({"title": _("List {num}: {date}").format(num=period.id, date=fmt_date)})

    return render_to_response('period.html', base)
Exemplo n.º 2
0
def events(request, event_id=None):
    # {{{ Get base context, redirect if necessary
    if 'goto' in request.GET:
        return redirect('/results/events/' + request.GET['goto'])

    base = base_ctx('Results', 'By Event', request)
    # }}}

    # {{{ Display the main table if event ID is not given
    if event_id is None:
        root_events = (
            Event.objects
                  .annotate(num_uplinks=Count("uplink"))
                  .filter(num_uplinks=1)
                  .order_by('name')
                  .only('id', 'name', 'big', 'category', 'fullname')
        )
        base.update({
            'bigs': (
                list(root_events.filter(big=True, category=CAT_INDIVIDUAL)) +
                list(root_events.filter(big=True, category=CAT_TEAM)) +
                list(root_events.filter(big=True, category=CAT_FREQUENT))
            ),
            'smalls': (
                list(root_events.filter(big=False, category=CAT_INDIVIDUAL).order_by('name')) +
                list(root_events.filter(big=False, category=CAT_TEAM).order_by('name')) +
                list(root_events.filter(big=False, category=CAT_FREQUENT).order_by('name'))
            )
        })

        base['messages'].append(Message(
            _('The events are organized in a hierarchical fashion. Thus, all GSL tournaments '
              'are filed under GSL, all Code S under their respective seasons, all groups under '
              'their respective Code S event, and so on.'),
            type=Message.INFO
        ))

        return render_to_response('events.djhtml', base)
    # }}}

    # {{{ Get object, generate messages, and ensure big is set. Find familial relationships.
    event = get_object_or_404(Event, id=event_id)
    base['messages'] += generate_messages(event)

    matches = event.get_matchset()
    if matches.count() > 200 and not event.big:
        event.set_big(True)

    base.update({
        'event':            event,
        'siblings':         event.get_parent().get_immediate_children().exclude(id=event.id)
                                if event.get_parent() else None,
        'path':             event.get_ancestors(id=True),
        'children':         event.get_immediate_children(),
    })
    # }}}

    # {{{ Make forms
    if base['adm']:
        def check_form(formname, cl, check):
            if request.method == 'POST' and check in request.POST:
                f = cl(request=request, event=event)
                base['messages'] += f.update_event(event)
            else:
                f = cl(event=event)
            base[formname] = f

        check_form('form', EventModForm, 'modevent')
        check_form('addform', AddForm, 'addevent')
        if event.has_children():
            check_form('reorderform', ReorderForm, 'reorder')
        if event.type == TYPE_EVENT:
            check_form('ppform', PrizepoolModForm, 'modpp')
            check_form('wcsform', WCSModForm, 'modwcs')
        if not event.has_children() and event.get_immediate_matchset().exists():
            check_form('stform', StoriesForm, 'modstory')

        if 'close' in request.GET and request.GET['close'] == '1':
            event.close()
            base['messages'].append(Message(_('Sucessfully closed event.'), type=Message.SUCCESS))
    # }}}

    # {{{ Prizepool information for the public
    total_earnings = Earnings.objects.filter(event__uplink__parent=event)

    local_earnings = Earnings.objects.filter(event=event)

    ranked_prize = local_earnings.exclude(placement=0)\
                                 .order_by('-earnings', 'placement')
    unranked_prize = list(
        local_earnings.filter(placement=0).order_by('-earnings')
    )

    placements = get_placements(event)
    prize_pool_table = list()
    for k, g in groupby(ranked_prize, key=lambda x: x.earnings):
        gl = list(g)
        prize_pool_table.append((k, placements[k], gl, len(gl)))

    if len(prize_pool_table) > 0:
        base['ranked_prize'] = prize_pool_table
    if len(unranked_prize) > 0:
        base['unranked_prize'] = unranked_prize

    currencies = list({r['currency'] for r in total_earnings.values('currency').distinct()})
    base.update({
        'prizepool':     total_earnings.aggregate(Sum('earnings'))['earnings__sum'],
        'nousdpp':       len(currencies) > 1 or len(currencies) == 1 and currencies[0] != 'USD',
        'prizepoolorig': [{
            'pp':  total_earnings.filter(currency=k).aggregate(Sum('origearnings'))['origearnings__sum'],
            'cur': k,
        } for k in currencies],
    })
    # }}}

    # {{{ Other easy statistics

    add_links = request.user.is_authenticated() and request.user.is_staff

    base.update({
        'game':      etn(lambda: dict(GAMES)[matches.values('game').distinct()[0]['game']]),
        'nmatches':  matches.count(),
        'ngames':    sum(count_winloss_games(matches)),
        'pvp_games': count_mirror_games(matches, 'P'),
        'tvt_games': count_mirror_games(matches, 'T'),
        'zvz_games': count_mirror_games(matches, 'Z'),
        'matches':   display_matches(
            matches.prefetch_related('message_set')
                .prefetch_related('pla', 'plb', 'eventobj')
                .annotate(Count('eventobj__match'))
                .order_by('-eventobj__latest', '-eventobj__idx', '-date', '-id')[0:200],
            eventcount=True,
            add_links=add_links
        ),
        'nplayers':  Player.objects.filter(
            Q(id__in=matches.values('pla')) | Q(id__in=matches.values('plb'))
        ).count(),
    })

    offlines = list(matches.values('offline').distinct())
    if len(offlines) > 1:
        base['offline'] = _('Both')
    elif len(offlines) == 1:
        base['offline'] = _('Offline') if offlines[0]['offline'] else _('Online')

    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(matches, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(matches, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(matches, 'T', 'Z')
    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base['zvz_games']
    # }}}

    return render_to_response('eventres.djhtml', base)
Exemplo n.º 3
0
def events(request, event_id=None):
    # {{{ Get base context, redirect if necessary
    if 'goto' in request.GET:
        return redirect('/results/events/' + request.GET['goto'])

    base = base_ctx('Results', 'By Event', request)
    # }}}

    # {{{ Display the main table if event ID is not given
    if event_id is None:
        root_events = (
            Event.objects
                .annotate(num_uplinks=Count("uplink"))
                .filter(num_uplinks=1)
                .order_by('name')
                .only('id', 'name', 'big', 'category', 'fullname')
        )
        base.update({
            'ind_bigs':    collect(root_events.filter(big=True, category=CAT_INDIVIDUAL), 2),
            'ind_smalls':  root_events.filter(big=False, category=CAT_INDIVIDUAL).order_by('name'),
            'team_bigs':   collect(root_events.filter(big=True, category=CAT_TEAM), 2),
            'team_smalls': root_events.filter(big=False, category=CAT_TEAM).order_by('name'),
            'freq_bigs':   collect(root_events.filter(big=True, category=CAT_FREQUENT), 2),
            'freq_smalls': root_events.filter(big=False, category=CAT_FREQUENT).order_by('name'),
        })

        return render_to_response('events.html', base)
    # }}}

    # {{{ Get object, generate messages, and ensure big is set. Find familial relationships.
    event = get_object_or_404(Event, id=event_id)
    base['messages'] += generate_messages(event)

    matches = event.get_matchset()
    if matches.count() > 200 and not event.big:
        event.set_big(True)

    base.update({
        'event':            event,
        'siblings':         event.get_parent().get_immediate_children().exclude(id=event.id)
                                if event.get_parent() else None,
        'path':             event.get_ancestors(id=True),
        'children':         event.get_immediate_children(),
    })
    # }}}

    # {{{ Make forms
    if base['adm']:
        def check_form(formname, cl, check):
            if request.method == 'POST' and check in request.POST:
                f = cl(request=request, event=event)
                base['messages'] += f.update_event(event)
            else:
                f = cl(event=event)
            base[formname] = f

        check_form('form', EventModForm, 'modevent')
        check_form('addform', AddForm, 'addevent')
        if event.has_children():
            check_form('reorderform', ReorderForm, 'reorder')
        if event.type == TYPE_EVENT:
            check_form('ppform', PrizepoolModForm, 'modpp')
        if not event.has_children() and event.get_immediate_matchset().exists():
            check_form('stform', StoryModForm, 'modstories')
    # }}}

    # {{{ Prizepool information for the public
    total_earnings = Earnings.objects.filter(event__uplink__parent=event)
    currencies = list({r['currency'] for r in total_earnings.values('currency').distinct()})
    base.update({
        'prizepool':     total_earnings.aggregate(Sum('earnings'))['earnings__sum'],
        'nousdpp':       len(currencies) > 1 or len(currencies) == 1 and currencies[0] != 'USD',
        'prizepoolorig': [{
            'pp':  total_earnings.filter(currency=k).aggregate(Sum('origearnings'))['origearnings__sum'],
            'cur': k,
        } for k in currencies],
    })
    # }}}

    # {{{ Other easy statistics
    base.update({
        'game':      etn(lambda: dict(Match.GAMES)[matches.values('game').distinct()[0]['game']]),
        'offline':   etn(lambda: matches.values('offline').distinct()[0]['offline']),
        'nmatches':  matches.count(),
        'ngames':    sum(count_winloss_games(matches)),
        'pvp_games': count_mirror_games(matches, 'P'),
        'tvt_games': count_mirror_games(matches, 'T'),
        'zvz_games': count_mirror_games(matches, 'Z'),
        'matches':   display_matches(
            matches.prefetch_related('message_set')
                .prefetch_related('pla', 'plb', 'eventobj')
                .annotate(Count('eventobj__match'))
                .order_by('-eventobj__latest', '-eventobj__idx', '-date', '-id')[0:200],
            eventcount=True,
        ),
        'nplayers':  Player.objects.filter(
            Q(id__in=matches.values('pla')) | Q(id__in=matches.values('plb'))
        ).count(),
    })

    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(matches, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(matches, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(matches, 'T', 'Z')
    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base['zvz_games']
    # }}}

    base.update({"title": event})

    return render_to_response('eventres.html', base)
Exemplo n.º 4
0
def events(request, event_id=None):
    # {{{ Get base context, redirect if necessary
    if 'goto' in request.GET:
        return redirect('/results/events/' + request.GET['goto'])

    base = base_ctx('Results', 'By Event', request)
    # }}}

    # {{{ Display the main table if event ID is not given
    if event_id is None:
        root_events = (Event.objects.annotate(
            num_uplinks=Count("uplink")).filter(
                num_uplinks=1).order_by('name').only('id', 'name', 'big',
                                                     'category', 'fullname'))
        base.update({
            'bigs':
            (list(root_events.filter(big=True, category=CAT_INDIVIDUAL)) +
             list(root_events.filter(big=True, category=CAT_TEAM)) +
             list(root_events.filter(big=True, category=CAT_FREQUENT))),
            'smalls':
            (list(
                root_events.filter(big=False,
                                   category=CAT_INDIVIDUAL).order_by('name')) +
             list(
                 root_events.filter(big=False,
                                    category=CAT_TEAM).order_by('name')) +
             list(
                 root_events.filter(big=False,
                                    category=CAT_FREQUENT).order_by('name')))
        })

        base['messages'].append(
            Message(_(
                'The events are organized in a hierarchical fashion. Thus, all GSL tournaments '
                'are filed under GSL, all Code S under their respective seasons, all groups under '
                'their respective Code S event, and so on.'),
                    type=Message.INFO))

        return render_to_response('events.djhtml', base)
    # }}}

    # {{{ Get object, generate messages, and ensure big is set. Find familial relationships.
    event = get_object_or_404(Event, id=event_id)
    base['messages'] += generate_messages(event)

    matches = event.get_matchset()
    if matches.count() > 200 and not event.big:
        event.set_big(True)

    base.update({
        'event':
        event,
        'siblings':
        event.get_parent().get_immediate_children().exclude(
            id=event.id) if event.get_parent() else None,
        'path':
        event.get_ancestors(id=True),
        'children':
        event.get_immediate_children(),
    })
    # }}}

    # {{{ Make forms
    if base['adm']:

        def check_form(formname, cl, check):
            if request.method == 'POST' and check in request.POST:
                f = cl(request=request, event=event)
                base['messages'] += f.update_event(event)
            else:
                f = cl(event=event)
            base[formname] = f

        check_form('form', EventModForm, 'modevent')
        check_form('addform', AddForm, 'addevent')
        if event.has_children():
            check_form('reorderform', ReorderForm, 'reorder')
        if event.type == TYPE_EVENT:
            check_form('ppform', PrizepoolModForm, 'modpp')
        if not event.has_children() and event.get_immediate_matchset().exists(
        ):
            check_form('stform', StoriesForm, 'modstory')
    # }}}

    # {{{ Prizepool information for the public
    total_earnings = Earnings.objects.filter(event__uplink__parent=event)

    local_earnings = Earnings.objects.filter(event=event)

    ranked_prize = local_earnings.exclude(placement=0)\
                                 .order_by('-earnings', 'placement')
    unranked_prize = list(
        local_earnings.filter(placement=0).order_by('-earnings'))

    placements = get_placements(event)
    prize_pool_table = list()
    for k, g in groupby(ranked_prize, key=lambda x: x.earnings):
        gl = list(g)
        prize_pool_table.append((k, placements[k], gl, len(gl)))

    if len(prize_pool_table) > 0:
        base['ranked_prize'] = prize_pool_table
    if len(unranked_prize) > 0:
        base['unranked_prize'] = unranked_prize

    currencies = list(
        {r['currency']
         for r in total_earnings.values('currency').distinct()})
    base.update({
        'prizepool':
        total_earnings.aggregate(Sum('earnings'))['earnings__sum'],
        'nousdpp':
        len(currencies) > 1 or len(currencies) == 1 and currencies[0] != 'USD',
        'prizepoolorig': [{
            'pp':
            total_earnings.filter(currency=k).aggregate(
                Sum('origearnings'))['origearnings__sum'],
            'cur':
            k,
        } for k in currencies],
    })
    # }}}

    # {{{ Other easy statistics

    add_links = request.user.is_authenticated() and request.user.is_staff

    base.update({
        'game':
        etn(lambda: dict(GAMES)[matches.values('game').distinct()[0]['game']]),
        'nmatches':
        matches.count(),
        'ngames':
        sum(count_winloss_games(matches)),
        'pvp_games':
        count_mirror_games(matches, 'P'),
        'tvt_games':
        count_mirror_games(matches, 'T'),
        'zvz_games':
        count_mirror_games(matches, 'Z'),
        'matches':
        display_matches(
            matches.prefetch_related('message_set').prefetch_related(
                'pla', 'plb',
                'eventobj').annotate(Count('eventobj__match')).order_by(
                    '-eventobj__latest', '-eventobj__idx', '-date',
                    '-id')[0:200],
            eventcount=True,
            add_links=add_links),
        'nplayers':
        Player.objects.filter(
            Q(id__in=matches.values('pla'))
            | Q(id__in=matches.values('plb'))).count(),
    })

    offlines = list(matches.values('offline').distinct())
    if len(offlines) > 1:
        base['offline'] = _('Both')
    elif len(offlines) == 1:
        base['offline'] = _('Offline') if offlines[0]['offline'] else _(
            'Online')

    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(matches, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(matches, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(matches, 'T', 'Z')
    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base[
        'zvz_games']
    # }}}

    return render_to_response('eventres.djhtml', base)
Exemplo n.º 5
0
def period(request, period_id=None):
    base = base_ctx('Ranking', 'Current', request)

    # {{{ Get period object
    if not period_id:
        period = base['curp']
    else:
        period = get_object_or_404(Period, id=period_id, computed=True)

    if period.is_preview():
        base['messages'].append(
            Message(msg_preview % django_date_filter(period.end, 'F jS'),
                    type=Message.INFO))

    base['period'] = period
    if period.id != base['curp'].id:
        base['curpage'] = ''
    # }}}

    # {{{ Best and most specialised players
    qset = total_ratings(filter_active(
        Rating.objects.filter(period=period))).select_related('player')
    qsetp = qset.filter(player__race=P)
    qsett = qset.filter(player__race=T)
    qsetz = qset.filter(player__race=Z)
    base.update({
        'best':
        qset.latest('rating'),
        'bestvp':
        qset.latest('tot_vp'),
        'bestvt':
        qset.latest('tot_vt'),
        'bestvz':
        qset.latest('tot_vz'),
        'bestp':
        qsetp.latest('rating'),
        'bestpvp':
        qsetp.latest('tot_vp'),
        'bestpvt':
        qsetp.latest('tot_vt'),
        'bestpvz':
        qsetp.latest('tot_vz'),
        'bestt':
        qsett.latest('rating'),
        'besttvp':
        qsett.latest('tot_vp'),
        'besttvt':
        qsett.latest('tot_vt'),
        'besttvz':
        qsett.latest('tot_vz'),
        'bestz':
        qsetz.latest('rating'),
        'bestzvp':
        qsetz.latest('tot_vp'),
        'bestzvt':
        qsetz.latest('tot_vt'),
        'bestzvz':
        qsetz.latest('tot_vz'),
        'specvp':
        qset.extra(select={
            'd': 'rating_vp/dev_vp*(rating+1.5)'
        }).latest('d'),
        'specvt':
        qset.extra(select={
            'd': 'rating_vt/dev_vt*(rating+1.5)'
        }).latest('d'),
        'specvz':
        qset.extra(select={
            'd': 'rating_vz/dev_vz*(rating+1.5)'
        }).latest('d'),
        'specpvp':
        qsetp.extra(select={
            'd': 'rating_vp/dev_vp*(rating+1.5)'
        }).latest('d'),
        'specpvt':
        qsetp.extra(select={
            'd': 'rating_vt/dev_vt*(rating+1.5)'
        }).latest('d'),
        'specpvz':
        qsetp.extra(select={
            'd': 'rating_vz/dev_vz*(rating+1.5)'
        }).latest('d'),
        'spectvp':
        qsett.extra(select={
            'd': 'rating_vp/dev_vp*(rating+1.5)'
        }).latest('d'),
        'spectvt':
        qsett.extra(select={
            'd': 'rating_vt/dev_vt*(rating+1.5)'
        }).latest('d'),
        'spectvz':
        qsett.extra(select={
            'd': 'rating_vz/dev_vz*(rating+1.5)'
        }).latest('d'),
        'speczvp':
        qsetz.extra(select={
            'd': 'rating_vp/dev_vp*(rating+1.5)'
        }).latest('d'),
        'speczvt':
        qsetz.extra(select={
            'd': 'rating_vt/dev_vt*(rating+1.5)'
        }).latest('d'),
        'speczvz':
        qsetz.extra(select={
            'd': 'rating_vz/dev_vz*(rating+1.5)'
        }).latest('d'),
    })
    # }}}

    # {{{ Highest gainer and biggest losers

    # TODO: Fix these queries, highly dependent on the way django does things.
    gainers = filter_active(Rating.objects.filter(period=period))\
        .filter(prev__isnull=False)\
        .select_related('prev', 'player')\
        .extra(select={'diff': 'rating.rating - T3.rating'})\
        .order_by('-diff')
    losers = filter_active(Rating.objects.filter(period=period))\
        .filter(prev__isnull=False)\
        .select_related('prev', 'player')\
        .extra(select={'diff': 'rating.rating - T3.rating'})\
        .order_by('diff')

    base.update({'updown': zip(gainers[:5], losers[:5])})
    # }}}

    # {{{ Matchup statistics
    qset = period.match_set
    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(qset, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(qset, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(qset, 'T', 'Z')
    base.update({
        'pvp_games': count_mirror_games(qset, 'P'),
        'tvt_games': count_mirror_games(qset, 'T'),
        'zvz_games': count_mirror_games(qset, 'Z'),
    })

    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base[
        'zvz_games']
    # }}}

    # {{{ Build country list
    all_players = Player.objects.filter(rating__period_id=period.id,
                                        rating__decay__lt=INACTIVE_THRESHOLD)
    base['countries'] = country_list(all_players)
    # }}}

    # {{{ Initial filtering of ratings
    entries = filter_active(period.rating_set).select_related('player')

    # Race filter
    race = get_param(request, 'race', 'ptzrs')
    q = Q()
    for r in race:
        q |= Q(player__race=r.upper())
    entries = entries.filter(q)

    # Country filter
    nats = get_param(request, 'nats', 'all')
    if nats == 'foreigners':
        entries = entries.exclude(player__country='KR')
    elif nats != 'all':
        entries = entries.filter(player__country=nats)

    # Sorting
    sort = get_param(request, 'sort', '')
    if sort not in ['vp', 'vt', 'vz']:
        entries = entries.order_by('-rating', 'player__tag')
    else:
        entries = entries.extra(select={
            'd': 'rating+rating_' + sort
        }).order_by('-d', 'player__tag')

    entries = entries.prefetch_related('prev')

    base.update({
        'race': race,
        'nats': nats,
        'sort': sort,
    })
    # }}}

    # {{{ Pages etc.
    pagesize = SHOW_PER_LIST_PAGE
    page = int(get_param(request, 'page', 1))
    nitems = entries.count()
    npages = nitems // pagesize + (1 if nitems % pagesize > 0 else 0)
    page = min(max(page, 1), npages)
    entries = entries[(page - 1) * pagesize:page *
                      pagesize] if page > 0 else []

    pn_start, pn_end = page - 2, page + 2
    if pn_start < 1:
        pn_end += 1 - pn_start
        pn_start = 1
    if pn_end > npages:
        pn_start -= pn_end - npages
        pn_end = npages
    if pn_start < 1:
        pn_start = 1

    base.update({
        'page': page,
        'npages': npages,
        'startcount': (page - 1) * pagesize,
        'entries': populate_teams(entries),
        'nperiods': Period.objects.filter(computed=True).count(),
        'pn_range': range(pn_start, pn_end + 1),
    })
    # }}}

    base.update({
        'sortable': True,
        'localcount': True,
    })

    fmt_date = django_date_filter(period.end, "F jS, Y")

    return render_to_response('period.djhtml', base)
Exemplo n.º 6
0
def period(request, period_id):
    base = base_ctx('Ranking', 'Current', request)

    # {{{ Get period object
    period = get_object_or_404(Period, id=period_id, computed=True)
    if period.is_preview():
        base['messages'].append(Message(msg_preview % period.end.strftime('%B %d'), type=Message.INFO))

    base['period'] = period
    if period.id != base['curp'].id:
        base['curpage'] = ''
    # }}}

    # {{{ Best and most specialised players
    qset = total_ratings(filter_active(Rating.objects.filter(period=period))).select_related('player')
    qsetp = qset.filter(player__race=P)
    qsett = qset.filter(player__race=T)
    qsetz = qset.filter(player__race=Z)
    base.update({
        'best':     qset.latest('rating'),
        'bestvp':   qset.latest('tot_vp'),
        'bestvt':   qset.latest('tot_vt'),
        'bestvz':   qset.latest('tot_vz'),
        'bestp':    qsetp.latest('rating'),
        'bestpvp':  qsetp.latest('tot_vp'),
        'bestpvt':  qsetp.latest('tot_vt'),
        'bestpvz':  qsetp.latest('tot_vz'),
        'bestt':    qsett.latest('rating'),
        'besttvp':  qsett.latest('tot_vp'),
        'besttvt':  qsett.latest('tot_vt'),
        'besttvz':  qsett.latest('tot_vz'),
        'bestz':    qsetz.latest('rating'),
        'bestzvp':  qsetz.latest('tot_vp'),
        'bestzvt':  qsetz.latest('tot_vt'),
        'bestzvz':  qsetz.latest('tot_vz'),
        'specvp':   qset.extra(select={'d':   'rating_vp/dev_vp*rating'}).latest('d'),
        'specvt':   qset.extra(select={'d':   'rating_vt/dev_vt*rating'}).latest('d'),
        'specvz':   qset.extra(select={'d':   'rating_vz/dev_vz*rating'}).latest('d'),
        'specpvp':  qsetp.extra(select={'d':  'rating_vp/dev_vp*rating'}).latest('d'),
        'specpvt':  qsetp.extra(select={'d':  'rating_vt/dev_vt*rating'}).latest('d'),
        'specpvz':  qsetp.extra(select={'d':  'rating_vz/dev_vz*rating'}).latest('d'),
        'spectvp':  qsett.extra(select={'d':  'rating_vp/dev_vp*rating'}).latest('d'),
        'spectvt':  qsett.extra(select={'d':  'rating_vt/dev_vt*rating'}).latest('d'),
        'spectvz':  qsett.extra(select={'d':  'rating_vz/dev_vz*rating'}).latest('d'),
        'speczvp':  qsetz.extra(select={'d':  'rating_vp/dev_vp*rating'}).latest('d'),
        'speczvt':  qsetz.extra(select={'d':  'rating_vt/dev_vt*rating'}).latest('d'),
        'speczvz':  qsetz.extra(select={'d':  'rating_vz/dev_vz*rating'}).latest('d'),
    })
    # }}}

    # {{{ Matchup statistics
    qset = period.match_set
    base['pvt_wins'], base['pvt_loss'] = count_matchup_games(qset, 'P', 'T')
    base['pvz_wins'], base['pvz_loss'] = count_matchup_games(qset, 'P', 'Z')
    base['tvz_wins'], base['tvz_loss'] = count_matchup_games(qset, 'T', 'Z')
    base.update({
        'pvp_games': count_mirror_games(qset, 'P'),
        'tvt_games': count_mirror_games(qset, 'T'),
        'zvz_games': count_mirror_games(qset, 'Z'),
    })

    base['tot_mirror'] = base['pvp_games'] + base['tvt_games'] + base['zvz_games']
    # }}}

    # {{{ Build country list
    all_players = Player.objects.filter(rating__period_id=period.id, rating__decay__lt=INACTIVE_THRESHOLD)
    base['countries'] = country_list(all_players)
    # }}}

    # {{{ Initial filtering of ratings
    entries = filter_active(period.rating_set).select_related('player')

    # Race filter
    race = get_param(request, 'race', 'ptzrs')
    q = Q()
    for r in race:
        q |= Q(player__race=r.upper())
    entries = entries.filter(q)

    # Country filter
    nats = get_param(request, 'nats', 'all')
    if nats == 'foreigners':
        entries = entries.exclude(player__country='KR')
    elif nats != 'all':
        entries = entries.filter(player__country=nats)

    # Sorting
    sort = get_param(request, 'sort', '')
    if sort not in ['vp', 'vt', 'vz']: 
        entries = entries.order_by('-rating', 'player__tag')
    else:
        entries = entries.extra(select={'d':'rating+rating_'+sort}).order_by('-d', 'player__tag')

    base.update({
        'race': race,
        'nats': nats,
        'sort': sort,
    })
    # }}}

    # {{{ Pages etc.
    pagesize = 40
    page = int(get_param(request, 'page', 1))
    nitems = entries.count()
    npages = nitems//pagesize + (1 if nitems % pagesize > 0 else 0)
    page = min(max(page, 1), npages)
    entries = entries[(page-1)*pagesize : page*pagesize]

    base.update({
        'page':       page,
        'npages':     npages,
        'startcount': (page-1)*pagesize,
        'entries':    populate_teams(entries),
        'nperiods':   Period.objects.filter(computed=True).count(),
    })
    # }}}

    base.update({
        'sortable':   True,
        'localcount': True,
    })
        
    fmt_date = django_date_filter(period.end, "F jS, Y")
    base.update({"title": "List {}: {}".format(period.id, fmt_date)})

    return render_to_response('period.html', base)