def misc(request): base = base_ctx('Submit', 'Misc', request) if not base['adm']: return redirect('/login/') login_message(base) mergeform = ( MergePlayersForm(request=request) if request.method == 'POST' and 'merge' in request.POST else MergePlayersForm() ) moveform = ( MoveEventForm(request=request) if request.method == 'POST' and 'move' in request.POST else MoveEventForm() ) if mergeform.is_bound: base['messages'] += mergeform.merge() if moveform.is_bound: base['messages'] += moveform.move() base.update({ 'mergeform': mergeform, 'moveform': moveform, }) return render_to_response('manage.djhtml', base)
def misc(request): base = base_ctx('Submit', 'Misc', request) if not base['adm']: return redirect('/login/') login_message(base) mergeform = ( MergePlayersForm(request=request) if request.method == 'POST' and 'merge' in request.POST else MergePlayersForm() ) moveform = ( MoveEventForm(request=request) if request.method == 'POST' and 'move' in request.POST else MoveEventForm() ) if mergeform.is_bound: base['messages'] += mergeform.merge() if moveform.is_bound: base['messages'] += moveform.move() base.update({ 'mergeform': mergeform, 'moveform': moveform, }) return render_to_response('manage.html', base)
def sebracket(request): base = base_ctx('Inference', 'Predict', request=request) # {{{ Get data, set up and simulate form = SetupForm(request.GET) if not form.is_valid(): return redirect('/inference/') result = SingleEliminationPredictionResult( dbpl=form.cleaned_data['ps'], bos=form.cleaned_data['bo'], args=request.GET, ) # }}} # {{{ Post-processing base.update({ 'table': result.table, 'matches': result.matches, 'meanres': result.meanres, 'nrounds': result.nrounds, 'form': form, }) # }}} postable_sebracket(base, request, group_by(base['meanres'], key=lambda a: a['eventtext'])) return render_to_response('pred_sebracket.djhtml', base)
def api(request): base = base_ctx('About', 'API', request) if request.LANGUAGE_CODE != 'en': base['messages'].append( Message( _('The API documentation is only in English, sorry.'), type=Message.INFO, )) if request.method == 'POST': form = APIKeyForm(request) base['messages'] += form.add_key() else: form = APIKeyForm() base.update({'form': form}) # To enable pretty rendering of these players in the documentation base.update({ 'parting': Player.objects.get(id=5), 'maru': Player.objects.get(id=49) }) return render_to_response('api.djhtml', base)
def race(request): race = get_param(request, 'race', 'all') if race not in 'PTZ': race = 'all' sub = ['All','Protoss','Terran','Zerg'][['all','P','T','Z'].index(race)] base = base_ctx('Records', sub, request) def sift(lst, num=5): ret, pls = [], set() for r in lst: if not r.player_id in pls: pls.add(r.player_id) ret.append(r) if len(ret) == num: return ret return ret high = ( filter_active(total_ratings(Rating.objects.all())) .filter(period__id__gt=16).select_related('player', 'period') ) if race != 'all': high = high.filter(player__race=race) base.update({ 'hightot': sift(high.order_by('-rating')[:200]), 'highp': sift(high.order_by('-tot_vp')[:200]), 'hight': sift(high.order_by('-tot_vt')[:200]), 'highz': sift(high.order_by('-tot_vz')[:200]), 'race': race if race != 'all' else '', }) return render_to_response('records.djhtml', base)
def teams(request): base = base_ctx('Teams', 'Ranking', request) all_teams = Group.objects.filter( is_team=True).prefetch_related('groupmembership_set') active = all_teams.filter(active=True) sort = get_param_choice(request, 'sort', ['ak', 'pl', 'rt', 'np'], 'ak') if sort == 'pl': active = active.order_by('-scorepl', 'name') elif sort == 'ak': active = active.order_by('-scoreak', 'name') elif sort == 'rt': active = active.order_by('-meanrating', 'name') else: active = active.order_by('name') for t in active: t.nplayers = sum([ 1 if m.current and m.playing else 0 for m in t.groupmembership_set.all() ]) if sort == 'np': active = sorted(list(active), key=lambda a: -a.nplayers) inactive = all_teams.filter(active=False).order_by('name') base.update({ 'active': active, 'inactive': inactive, }) return render_to_response('teams.djhtml', base)
def changepwd(request): if not request.user.is_authenticated(): return redirect('/login/') base = base_ctx(request=request) login_message(base) if not ('old' in request.POST and 'new' in request.POST and 'newre' in request.POST): return render_to_response('changepwd.html', base) if not request.user.check_password(request.POST['old']): base['messages'].append( Message("The old password didn't match. Your password was not changed.", type=Message.ERROR) ) return render_to_response('changepwd.html', base) if request.POST['new'] != request.POST['newre']: base['messages'].append( Message("The new passwords didn't match. Your password was not changed.", type=Message.ERROR) ) return render_to_response('changepwd.html', base) request.user.set_password(request.POST['new']) request.user.save() base['messages'].append( Message('The password for %s was successfully changed.' % request.user.username, type=Message.SUCCESS) ) base.update({"title": "Change password"}) return render_to_response('changepwd.html', base)
def compare_search(request): base = base_ctx('Misc', 'Compare', request) if "op" in request.GET: op = request.GET["op"].lower() if "players" not in request.GET: form = CompareForm() validate = False else: form = CompareForm(request=request) if "op" not in request.GET: validate = False elif op == "compare": validate = True else: validate = False base["form"] = form if not validate: return render_to_response('compare.search.djhtml', base) if not form.is_valid(): base["messages"] += form.get_messages() return render_to_response('compare.search.djhtml', base) return redirect(form.generate_url())
def changepwd(request): if not request.user.is_authenticated(): return redirect('/login/') base = base_ctx(request=request) login_message(base) if not ('old' in request.POST and 'new' in request.POST and 'newre' in request.POST): return render_to_response('changepwd.djhtml', base) if not request.user.check_password(request.POST['old']): base['messages'].append( Message(_( "The old password didn't match. Your password was not changed." ), type=Message.ERROR)) return render_to_response('changepwd.djhtml', base) if request.POST['new'] != request.POST['newre']: base['messages'].append( Message(_( "The new passwords didn't match. Your password was not changed." ), type=Message.ERROR)) return render_to_response('changepwd.djhtml', base) request.user.set_password(request.POST['new']) request.user.save() base['messages'].append( Message(_('The password for %s was successfully changed.') % request.user.username, type=Message.SUCCESS)) return render_to_response('changepwd.djhtml', base)
def teams(request): base = base_ctx('Teams', 'Ranking', request) all_teams = Group.objects.filter(is_team=True).prefetch_related('groupmembership_set') active = all_teams.filter(active=True) sort = get_param_choice(request, 'sort', ['ak','pl','rt','np'], 'ak') if sort == 'pl': active = active.order_by('-scorepl', 'name') elif sort == 'ak': active = active.order_by('-scoreak', 'name') elif sort == 'rt': active = active.order_by('-meanrating', 'name') else: active = active.order_by('name') for t in active: t.nplayers = sum([1 if m.current and m.playing else 0 for m in t.groupmembership_set.all()]) if sort == 'np': active = sorted(list(active), key=lambda a: -a.nplayers) inactive = all_teams.filter(active=False).order_by('name') base.update({ 'active': active, 'inactive': inactive, }) base.update({"title": "Teams"}) return render_to_response('teams.html', base)
def add_matches(request): base = base_ctx('Submit', 'Matches', request) login_message(base) if request.method == 'POST' and 'submit' in request.POST: form = AddMatchesForm(base['adm'], request=request) base['matches'] = display_matches(form.parse_matches(request.user), messages=False) base['messages'] += form.messages else: form = AddMatchesForm(base['adm']) try: get_event = Event.objects.get(id=request.GET['eventid']) if get_event.closed: get_event.open() base['messages'].append( Message(_("Reopened '%s'.") % get_event.fullname, type=Message.SUCCESS)) form['eventobj'].field.choices.append( (get_event.id, get_event.fullname)) form['eventobj'].field.choices.sort(key=lambda e: e[1]) base['event_override'] = get_event.id except: pass base['form'] = form return render_to_response('add.djhtml', base)
def changepwd(request): if not request.user.is_authenticated(): return redirect("/login/") base = base_ctx(request=request) login_message(base) if not ("old" in request.POST and "new" in request.POST and "newre" in request.POST): return render_to_response("changepwd.djhtml", base) if not request.user.check_password(request.POST["old"]): base["messages"].append( Message(_("The old password didn't match. Your password was not changed."), type=Message.ERROR) ) return render_to_response("changepwd.djhtml", base) if request.POST["new"] != request.POST["newre"]: base["messages"].append( Message(_("The new passwords didn't match. Your password was not changed."), type=Message.ERROR) ) return render_to_response("changepwd.djhtml", base) request.user.set_password(request.POST["new"]) request.user.save() base["messages"].append( Message(_("The password for %s was successfully changed.") % request.user.username, type=Message.SUCCESS) ) return render_to_response("changepwd.djhtml", base)
def events(request): base = base_ctx('Submit', 'Events', request) if not base['adm']: return redirect('/login/') login_message(base) if request.method == 'POST': form = AddEventsForm(request=request) base['messages'] += form.commit() else: form = AddEventsForm() base['form'] = form # Build event list events = ( Event.objects.filter(closed=False) .annotate(Max('uplink__distance')) .filter(uplink__distance__max=0) .filter(downlink__child__closed=False) .annotate(Max('downlink__distance')) .order_by('idx') ) #for e in events: #e.has_subtree = e.get_immediate_children().filter(closed=False).exists() base['nodes'] = events base.update({"title": _("Manage events")}) return render_to_response('eventmgr.html', base)
def rrgroup(request): base = base_ctx('Inference', 'Predict', request=request) # {{{ Get data, set up and simulate form = SetupForm(request.GET) if not form.is_valid(): return redirect('/inference/') result = RoundRobinPredictionResult( dbpl=form.cleaned_data['ps'], bos=form.cleaned_data['bo'], args=request.GET, ) # }}} #{{{ Post-processing base.update({ 'table': result.table, 'mtable': result.mtable, 'matches': result.matches, 'meanres': result.meanres, 'form': form, }) # }}} postable_rrgroup(base, request) return render_to_response('pred_rrgroup.djhtml', base)
def add_matches(request): base = base_ctx('Submit', 'Matches', request) login_message(base) if request.method == 'POST' and 'submit' in request.POST: form = AddMatchesForm(base['adm'], request=request) base['matches'] = display_matches(form.parse_matches(request.user), messages=False) base['messages'] += form.messages else: form = AddMatchesForm(base['adm']) try: get_event = Event.objects.get(id=request.GET['eventid']) if get_event.closed: get_event.open() base['messages'].append(Message(_("Reopened '%s'.") % get_event.fullname, type=Message.SUCCESS)) form['eventobj'].field.choices.append((get_event.id, get_event.fullname)) form['eventobj'].field.choices.sort(key=lambda e: e[1]) base['event_override'] = get_event.id except: pass base['form'] = form base.update({"title": _("Submit results")}) return render_to_response('add.html', base)
def proleague(request): base = base_ctx('Inference', 'Predict', request=request) # {{{ Get data, set up and simulate form = SetupForm(request.GET) if not form.is_valid(): return redirect('/inference/') result = ProleaguePredictionResult( dbpl=form.cleaned_data['ps'], bos=form.cleaned_data['bo'], args=request.GET, ) # }}} # {{{ Post-processing base.update({ 's1': result.s1, 's2': result.s2, 'outcomes': result.outcomes, 'prob_draw': result.prob_draw, 'proba': result.proba, 'probb': result.probb, 'matches': result.matches, 'meanres': result.meanres, 'form': form, }) # }}} postable_proleague(base, request) return render_to_response('pred_proleague.djhtml', base)
def search(request): base = base_ctx(request=request) query = get_param(request, 'q', '') results = tools_search(query) if results is None: return redirect('/') players, teams, events = results # {{{ Redirect if only one hit if players.count() == 1 and teams.count() == 0 and events.count() == 0: return redirect('/players/%i-%s/' % (players.first().id, urlfilter(players.first().tag))) elif players.count() == 0 and teams.count() == 1 and events.count() == 0: return redirect('/teams/%i-%s/' % (teams.first().id, urlfilter(teams.first().name))) elif players.count() == 0 and teams.count() == 0 and events.count() == 1: return redirect( '/results/events/%i-%s/' % (events.first().id, urlfilter(events.first().fullname))) # }}} base.update({ 'results': zip_longest(players, teams, events, fillvalue=None), 'players': players, 'teams': teams, 'events': events, 'query': query, }) return render_to_response('search.djhtml', base)
def home(request): ctx = base_ctx('Misc', request=request) ctx["title"] = _("Miscellaneous Pages") ctx["miscpages"] = ( { "url": "/misc/balance/", "title": _("Balance Report"), "desc": _("Charts showing balance in StarCraft II over time.") }, { "url": "/misc/days/", "title": _("Number of days since…"), "desc": _("Page showing the most recent time some things happened.") }, { "url": "/misc/compare/", "title": _("Compare"), "desc": _("Tool for comparing players.") } ) # http://docs.python.org/3.2/library/itertools.html def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) ctx["miscpages"] = grouper(2, ctx["miscpages"]) return render_to_response("misc.html", ctx)
def dual(request): base = base_ctx('Inference', 'Predict', request=request) # {{{ Get data, set up and simulate form = SetupForm(request.GET) if not form.is_valid(): return redirect('/inference/') result = DualPredictionResult( dbpl=form.cleaned_data['ps'], bos=form.cleaned_data['bo'], args=request.GET, ) # }}} # {{{ Post-processing base.update({ 'table': result.table, 'matches': result.matches, 'meanres': result.meanres, 'form': form, }) # }}} postable_dual(base, request) base.update({"title": _("Dual tournament")}) return render_to_response('pred_4pswiss.html', base)
def results(request): base = base_ctx('Results', 'By Date', request) try: day = datetime.strptime(get_param(request, 'd', None), '%Y-%m-%d').date() except: day = date.today() bounds = Match.objects.aggregate(Min('date'), Max('date')) day = min(max(bounds['date__min'], day), bounds['date__max']) base.update({ 'mindate': bounds['date__min'], 'maxdate': bounds['date__max'], 'td': day, }) matches = ( Match.objects.filter(date=day).order_by('eventobj__idx', 'eventobj__latest', 'event', 'id') .prefetch_related('message_set', 'rta', 'rtb', 'pla', 'plb', 'eventobj') .annotate(Count('eventobj__match')) ) add_links = request.user.is_authenticated() and request.user.is_staff base['matches'] = display_matches(matches, date=False, ratings=True, messages=True, eventcount=True, add_links=add_links) return render_to_response('results.djhtml', base)
def search(request): base = base_ctx('Results', 'Search', request) # {{{ Filtering and modifying if base['adm']: if request.method == 'POST': modform = ResultsModForm(request=request) base['messages'] += modform.modify([ int(k.split('-')[-1]) for k in request.POST if 'y' in request.POST[k] and k[0:6] == 'match-' ]) else: modform = ResultsModForm() base['modform'] = modform if 'search' in request.GET: searchform = SearchForm(request=request) q = searchform.search(base['adm']) base['messages'] += q['messages'] del q['messages'] base.update(q) else: searchform = SearchForm() base['searchform'] = searchform # }}} return render_to_response('results_search.djhtml', base, context_instance=RequestContext(request))
def race(request): race = get_param(request, 'race', 'all') if race not in 'PTZ': race = 'all' sub = ['All', 'Protoss', 'Terran', 'Zerg'][['all', 'P', 'T', 'Z'].index(race)] base = base_ctx('Records', sub, request) def sift(lst, num=5): ret, pls = [], set() for r in lst: if not r.player_id in pls: pls.add(r.player_id) ret.append(r) if len(ret) == num: return ret return ret high = (filter_active(total_ratings(Rating.objects.all())).filter( period__id__gt=16).select_related('player', 'period')) if race != 'all': high = high.filter(player__race=race) base.update({ 'hightot': sift(high.order_by('-rating')[:200]), 'highp': sift(high.order_by('-tot_vp')[:200]), 'hight': sift(high.order_by('-tot_vt')[:200]), 'highz': sift(high.order_by('-tot_vz')[:200]), 'race': race if race != 'all' else '', }) return render_to_response('records.djhtml', base)
def results(request): base = base_ctx('Results', 'By Date', request) try: day = datetime.strptime(get_param(request, 'd', None), '%Y-%m-%d').date() except: day = date.today() bounds = Match.objects.aggregate(Min('date'), Max('date')) day = min(max(bounds['date__min'], day), bounds['date__max']) base.update({ 'mindate': bounds['date__min'], 'maxdate': bounds['date__max'], 'td': day, }) matches = (Match.objects.filter(date=day).order_by( 'eventobj__idx', 'eventobj__latest', 'event', 'id').prefetch_related('message_set', 'rta', 'rtb', 'pla', 'plb', 'eventobj').annotate(Count('eventobj__match'))) add_links = request.user.is_authenticated() and request.user.is_staff base['matches'] = display_matches(matches, date=False, ratings=True, messages=True, eventcount=True, add_links=add_links) return render_to_response('results.djhtml', base)
def review_matches(request): base = base_ctx('Submit', 'Review', request) if not base['adm']: return redirect('/login/') login_message(base) if request.method == 'POST': form = ReviewMatchesForm(request=request, submitter=request.user) base['messages'] += form.messages else: form = ReviewMatchesForm() base['form'] = form base['groups'] = ( PreMatchGroup.objects.filter(prematch__isnull=False) .prefetch_related('prematch_set') .order_by('id', 'event') .distinct() ) for g in base['groups']: g.prematches = display_matches(g.prematch_set.all(), messages=False, no_events=True) return render_to_response('review.djhtml', base)
def search(request): base = base_ctx(request=request) query = get_param(request, "q", "") results = tools_search(query) if results is None: return redirect("/") players, teams, events = results # {{{ Redirect if only one hit if players.count() == 1 and teams.count() == 0 and events.count() == 0: return redirect("/players/%i-%s/" % (players.first().id, urlfilter(players.first().tag))) elif players.count() == 0 and teams.count() == 1 and events.count() == 0: return redirect("/teams/%i-%s/" % (teams.first().id, urlfilter(teams.first().name))) elif players.count() == 0 and teams.count() == 0 and events.count() == 1: return redirect("/results/events/%i-%s/" % (events.first().id, urlfilter(events.first().fullname))) # }}} base.update( { "results": zip_longest(players, teams, events, fillvalue=None), "players": players, "teams": teams, "events": events, "query": query, } ) return render_to_response("search.djhtml", base)
def search(request): base = base_ctx(request=request) query = get_param(request, 'q', '') results = tools_search(query) if results is None: return redirect('/') players, teams, events = results # {{{ Redirect if only one hit if players.count() == 1 and teams.count() == 0 and events.count() == 0: return redirect('/players/%i-%s/' % (players.first().id, urlfilter(players.first().tag))) elif players.count() == 0 and teams.count() == 1 and events.count() == 0: return redirect('/teams/%i-%s/' % (teams.first().id, urlfilter(teams.first().name))) elif players.count() == 0 and teams.count() == 0 and events.count() == 1: return redirect('/results/events/%i-%s/' % (events.first().id, urlfilter(events.first().fullname))) # }}} base.update({ 'players': players, 'teams': teams, 'events': events, 'query': query, }) base.update({'title': _('Search results')}) return render_to_response('search.html', base)
def review_matches(request): base = base_ctx('Submit', 'Review', request) if not base['adm']: return redirect('/login/') login_message(base) if request.method == 'POST': form = ReviewMatchesForm(request=request, submitter=request.user) base['messages'] += form.messages else: form = ReviewMatchesForm() base['form'] = form base['groups'] = ( PreMatchGroup.objects.filter(prematch__isnull=False) .prefetch_related('prematch_set') .order_by('id', 'event') .distinct() ) for g in base['groups']: g.prematches = display_matches(g.prematch_set.all(), messages=False) base.update({"title": _("Review results")}) return render_to_response('review.html', base)
def earnings(request, player_id): player = get_object_or_404(Player, id=player_id) base = base_ctx('Ranking', 'Earnings', request, context=player) # {{{ Gather data earnings = player.earnings_set.prefetch_related('event__earnings_set').order_by('-event__latest') totalearnings = earnings.aggregate(Sum('earnings'))['earnings__sum'] # Get placement range for each prize for e in earnings: placements = get_placements(e.event) for prize, rng in placements.items(): if rng[0] <= e.placement <= rng[1]: e.rng = rng # }}} # {{{ Sum up earnings by currency currencies = {e.currency for e in earnings} by_currency = {cur: sum([e.origearnings for e in earnings if e.currency == cur]) for cur in currencies} if len(by_currency) == 1 and 'USD' in by_currency: by_currency = None # }}} base.update({ 'player': player, 'earnings': earnings, 'totalearnings': totalearnings, 'by_currency': by_currency, }) base.update({"title": player.tag}) return render_to_response('player_earnings.html', base)
def results(request, player_id): # {{{ Get objects player = get_object_or_404(Player, id=player_id) base = base_ctx('Ranking', 'Match history', request, context=player) base['player'] = player # }}} # {{{ Filtering matches = player.get_matchset(related=['pla','plb','eventobj']) form = ResultsFilterForm(request.GET) base['form'] = form form.is_valid() q = Q() for r in form.cleaned_data['race'].upper(): q |= Q(pla=player, rcb=r) | Q(plb=player, rca=r) matches = matches.filter(q) if form.cleaned_data['country'] == 'foreigners': matches = matches.exclude(Q(pla=player, plb__country='KR') | Q(plb=player, pla__country='KR')) elif form.cleaned_data['country'] != 'all': matches = matches.filter( Q(pla=player, plb__country=form.cleaned_data['country']) | Q(plb=player, pla__country=form.cleaned_data['country']) ) if form.cleaned_data['bestof'] != 'all': sc = int(form.cleaned_data['bestof'])//2 + 1 matches = matches.filter(Q(sca__gte=sc) | Q(scb__gte=sc)) if form.cleaned_data['offline'] != 'both': matches = matches.filter(offline=(form.cleaned_data['offline']=='offline')) if form.cleaned_data['game'] != 'all': matches = matches.filter(game=form.cleaned_data['game']) if form.cleaned_data['after'] is not None: matches = matches.filter(date__gte=form.cleaned_data['after']) if form.cleaned_data['before'] is not None: matches = matches.filter(date__lte=form.cleaned_data['before']) # }}} # {{{ Statistics base['matches'] = display_matches(matches, fix_left=player) base.update({ 'sc_my': sum([m['pla_score'] for m in base['matches']]), 'sc_op': sum([m['plb_score'] for m in base['matches']]), 'msc_my': sum([1 if m['pla_score'] > m['plb_score'] else 0 for m in base['matches']]), 'msc_op': sum([1 if m['plb_score'] > m['pla_score'] else 0 for m in base['matches']]), }) # }}} base.update({"title": player.tag}) return render_to_response('player_results.html', base)
def events(request): base = base_ctx('Submit', 'Events', request) if not base['adm']: return redirect('/login/') login_message(base) base['messages'].append( Message(_( "If you haven't used this tool before, ask before you do anything." ), type=Message.WARNING)) if request.method == 'POST': form = AddEventsForm(request=request) base['messages'] += form.commit() else: form = AddEventsForm() base['form'] = form # Build event list root_events = (Event.objects.filter(downlink__child__closed=False).filter( parent__isnull=True).order_by('idx').distinct()) subtreemap = {e.id: [] for e in root_events} tree = [{ 'event': e, 'subtree': subtreemap[e.id], 'inc': 0, } for e in root_events] events = root_events while events: events = (Event.objects.filter(downlink__child__closed=False).filter( parent__in=events).order_by('idx').distinct()) for e in events: subtreemap[e.id] = [] subtreemap[e.parent_id].append({ 'event': e, 'subtree': subtreemap[e.id], 'inc': 0, }) base['tree'] = [] def do_level(level, indent): for e in level: e['indent'] = indent base['tree'].append(e) if e['subtree']: base['tree'][-1]['inc'] += 1 do_level(e['subtree'], indent + 1) base['tree'][-1]['inc'] -= 1 do_level(tree, 0) return render_to_response('eventmgr.djhtml', base)
def hof(request): base = base_ctx('Records', 'HoF', request) base['high'] = (Player.objects.filter(dom_val__isnull=False, dom_start__isnull=False, dom_end__isnull=False, dom_val__gt=0).order_by('-dom_val')) return render_to_response('hof.djhtml', base)
def open_events(request): base = base_ctx('Submit', 'Open events', request) if not base['adm']: return redirect('/login/') login_message(base) # {{{ Handle modifications if base['adm'] and 'open_games' in request.POST: ids = [int(i) for i in request.POST.getlist('open_games_ids')] for id in ids: Event.objects.get(id=id).close() base['messages'].append(Message('Successfully closed %i events.' % len(ids), type=Message.SUCCESS)) elif base['adm'] and 'pp_events' in request.POST: ids = [int(i) for i in request.POST.getlist('pp_events_ids')] nevents = Event.objects.filter(id__in=ids).update(prizepool=False) base['messages'].append(Message( 'Successfully marked %i events as having no prize pool.' % nevents, type=Message.SUCCESS)) # }}} # {{{ Open events with games base['open_games'] = ( Event.objects.filter(type=TYPE_EVENT, closed=False) .filter(downlink__child__match__isnull=False) .distinct() .prefetch_related('uplink__parent') .order_by('latest', 'idx', 'fullname') ) # }}} # {{{ Open events without games base['open_nogames'] = ( Event.objects.filter(type=TYPE_EVENT, closed=False) .exclude(downlink__child__match__isnull=False) .exclude(id=2) .distinct() .prefetch_related('uplink__parent') .order_by('fullname') ) # }}} # {{{ Closed non-team events with unknown prizepool status. base['pp_events'] = ( Event.objects.filter(type=TYPE_EVENT, prizepool__isnull=True) .filter(match__isnull=False, closed=True) .exclude(uplink__parent__category=CAT_TEAM) .distinct() .prefetch_related('uplink__parent') .order_by('idx', 'fullname') ) # }}} fill_aux_event(base['open_games']) fill_aux_event(base['open_nogames']) fill_aux_event(base['pp_events']) base.update({"title": "Open events"}) return render_to_response('events_open.html', base)
def db(request): base = base_ctx('About', 'Database', request) base.update({ 'nmatches': Match.objects.all().count(), 'nuntreated': Match.objects.filter(treated=False).count(), 'ngames': sum(count_winloss_games(Match.objects.all())), 'nwol': Match.objects.filter(game=WOL).count(), 'nhots': Match.objects.filter(game=HOTS).count(), 'nlotv': Match.objects.filter(game=LOTV).count(), 'nwolgames': sum(count_winloss_games(Match.objects.filter(game=WOL))), 'nhotsgames': sum(count_winloss_games(Match.objects.filter(game=HOTS))), 'nlotvgames': sum(count_winloss_games(Match.objects.filter(game=LOTV))), 'nonline': Match.objects.filter(offline=False).count(), 'nonlinegames': sum(count_winloss_games(Match.objects.filter(offline=False))), 'npartial': Match.objects.exclude(eventobj__isnull=True, event='').count(), 'nfull': Match.objects.filter(eventobj__isnull=False).count(), 'nplayers': Player.objects.all().count(), 'nkoreans': Player.objects.filter(country='KR').count(), 'nteams': Group.objects.filter(is_team=True).count(), 'nactive': Group.objects.filter(active=True, is_team=True).count(), 'submitters': [ u for u in User.objects.all().annotate(nmatches=Count('match')).order_by('-nmatches') if u.nmatches > 0 ], 'dump': os.path.exists(DUMP_PATH), 'updated': datetime.fromtimestamp(os.stat(PROJECT_PATH + 'update').st_mtime), 'dbtables': DBTABLES, }) base.update({ 'noffline': base['nmatches'] - base['nonline'], 'nofflinegames': base['ngames'] - base['nonlinegames'], 'nuncatalogued': base['nmatches'] - base['nfull'], 'ninactive': base['nteams'] - base['nactive'], }) if base['dump']: stat = os.stat(os.path.join(DUMP_PATH, 'aligulac.sql')) base.update({ 'megabytes': stat.st_size / 1048576, 'modified': datetime.fromtimestamp(stat.st_mtime), }) stat = os.stat(os.path.join(DUMP_PATH, 'aligulac.sql.gz')) base.update({ 'gz_megabytes': stat.st_size / 1048576 }) base.update({'title': _('Database status')}) return render_to_response('db.html', base)
def player_info_lp(request): base = base_ctx('Submit', 'Player Info', request) if not base['adm']: return HttpResponse(status=403) if 'title' not in request.GET: return JsonResponse({"message": "Missing title"}) return player_info_lp_helper(request.GET['title'])
def hof(request): base = base_ctx('Records', 'HoF', request) base['high'] = ( Player.objects.filter( dom_val__isnull=False, dom_start__isnull=False, dom_end__isnull=False, dom_val__gt=0 ).order_by('-dom_val') ) return render_to_response('hof.djhtml', base)
def balance(request): base = base_ctx('Misc', 'Balance Report', request) base.update({ 'charts': True, 'patches': PATCHES, 'entries': BalanceEntry.objects.all().order_by('date'), }) return render_to_response('reports_balance.djhtml', base)
def language(request): base = base_ctx(request=request) base['languages'] = LANGUAGES if 'return' in request.POST: base['return'] = request.POST['return'] else: base['return'] = '/' return render_to_response('language.djhtml', base)
def hof(request): base = base_ctx('Records', 'HoF', request) base['high'] = ( Player.objects.filter( dom_val__isnull=False, dom_start__isnull=False, dom_end__isnull=False, dom_val__gt=0 ).order_by('-dom_val') ) base.update({"title": _("Hall of Fame")}) return render_to_response('hof.html', base)
def proleague(request): base = base_ctx('Inference', 'Predict', request=request) # {{{ Get data, set up and simulate form = SetupForm(request.GET) if not form.is_valid(): return redirect('/inference/') num = form.cleaned_data['bo'][0] dbpl = form.cleaned_data['ps'] sipl = [make_player(p) for p in dbpl] nplayers = len(sipl) sim = TeamPL(num) sim.set_players(sipl) matchlist = [str(i) for i in range(0, nplayers//2)] update_matches(sim, matchlist, request) sim.compute() # }}} # {{{ Post-processing results, prob_draw = [], 0 for si in range(0, nplayers//4 + 1): if si == nplayers//4 and nplayers//2 % 2 == 0: prob_draw = sim.get_tally()[0][si] else: results.append({ 'scl': si, 'scw': sim._numw, 'proba': sim.get_tally()[1][si], 'probb': sim.get_tally()[0][si], }) rounds = [('Matches', matchlist)] matches = [sim.get_match(m) for m in matchlist] base.update({ 's1': sum([1 if m._result[0] > m._result[1] and m.is_fixed() else 0 for m in matches]), 's2': sum([1 if m._result[0] < m._result[1] and m.is_fixed() else 0 for m in matches]), 'results': results, 'prob_draw': prob_draw, 'ta': sum([r['proba'] for r in results]), 'tb': sum([r['probb'] for r in results]), 'matches': create_matches(sim, rounds), 'meanres': create_median_matches(sim, rounds), 'form': form, }) # }}} postable_proleague(base, request) base.update({"title": "Proleague team match"}) return render_to_response('pred_proleague.html', base)
def blog(request): base = base_ctx('About', 'Blog', request) if request.LANGUAGE_CODE != 'en': base['messages'].append(Message( _('The blog/news section is only in English, sorry.'), type=Message.INFO, )) base['blogposts'] = Post.objects.all() return render_to_response('blog.djhtml', base)
def blog(request): base = base_ctx('About', 'Blog', request) if request.LANGUAGE_CODE != 'en': base['messages'].append(Message( _('The blog/news section is only in English, sorry.'), type=Message.INFO, )) base['blogposts'] = Post.objects.all()[:10] return render_to_response('blog.html', base)
def faq(request): base = base_ctx('About', 'FAQ', request) if request.LANGUAGE_CODE != 'en': base['messages'].append(Message( _('The FAQ section is only in English, sorry.'), type=Message.INFO, )) base['posts'] = Post.objects.all() return render_to_response('faq.djhtml', base)
def open_events(request): base = base_ctx('Submit', 'Open events', request) if not base['adm']: return redirect('/login/') login_message(base) # Handle modifications if base['adm'] and 'open_games' in request.POST: ids = [int(i) for i in request.POST.getlist('open_games_ids')] for id in ids: Event.objects.get(id=id).close() base['messages'].append( Message( ungettext_lazy('Successfully closed %i event.', 'Successfully closed %i events.', len(ids)) % len(ids), type=Message.SUCCESS)) elif base['adm'] and 'pp_events' in request.POST: ids = [int(i) for i in request.POST.getlist('pp_events_ids')] nevents = Event.objects.filter(id__in=ids).update(prizepool=False) base['messages'].append( Message(ungettext_lazy( 'Successfully marked %i event as having no prize pool.', 'Successfully marked %i events as having no prize pool.', nevents) % nevents, type=Message.SUCCESS)) # Open events with games base['open_games'] = (Event.objects.filter( type=TYPE_EVENT, closed=False).filter( downlink__child__match__isnull=False).distinct().prefetch_related( 'uplink__parent').order_by('latest', 'idx', 'fullname')) # Open events without games base['open_nogames'] = (Event.objects.filter( type=TYPE_EVENT, closed=False).exclude(id__in=Event.objects.filter( downlink__child__match__isnull=False).distinct()).distinct( ).exclude( id=2).prefetch_related('uplink__parent').order_by('fullname')) # Closed non-team events with unknown prizepool status. base['pp_events'] = (Event.objects.filter( type=TYPE_EVENT, prizepool__isnull=True).filter( match__isnull=False, closed=True).exclude( uplink__parent__category=CAT_TEAM).distinct().prefetch_related( 'uplink__parent').order_by('idx', 'fullname')) fill_aux_event(base['open_games']) fill_aux_event(base['open_nogames']) fill_aux_event(base['pp_events']) return render_to_response('events_open.djhtml', base)
def predict(request): base = base_ctx('Inference', 'Predict', request=request) if 'submitted' not in request.GET: base['form'] = PredictForm() return render_to_response('predict.djhtml', base) base['form'] = PredictForm(request=request) base['messages'] += base['form'].get_messages() if not base['form'].is_valid(): return render_to_response('predict.djhtml', base) return redirect(base['form'].generate_url())
def transfers(request): base = base_ctx('Teams', 'Transfers', request) # {{{ Get relevant groupmembership objects trades = (GroupMembership.objects.exclude( start__isnull=True, end__isnull=True).filter(group__is_team=True).select_related( 'player', 'group').extra( select={ 'cdate': ('CASE ' 'WHEN start IS NULL THEN "end" ' 'WHEN "end" IS NULL THEN start ' 'WHEN start > "end" THEN start ' 'ELSE "end" ' 'END') }).order_by('-cdate', 'player__tag')[0:50]) # }}} # {{{ Separate them into joins and leaves pretrades = [] for t in trades: if t.start is not None and t.start <= date.today(): pretrades.append({ 'date': t.start, 'player': t.player, 'joined': t.group }) if t.end is not None and t.end <= date.today(): pretrades.append({ 'date': t.end, 'player': t.player, 'left': t.group }) pretrades.sort(key=lambda t: t['player'].tag.upper()) pretrades.sort(key=lambda t: t['date'], reverse=True) # }}} # {{{ Combine joins and leaves for the same player on the same date ind = 0 while ind < len(pretrades) - 1: if pretrades[ind]['player'] == pretrades[ind+1]['player'] and\ pretrades[ind]['date'] == pretrades[ind+1]['date']: pretrades[ind].update(pretrades[ind + 1]) del pretrades[ind + 1] ind += 1 # }}} base['trades'] = pretrades[0:25] return render_to_response('player_transfers.djhtml', base)
def earnings(request, player_id): player = get_object_or_404(Player, id=player_id) base = base_ctx('Ranking', 'Earnings', request, context=player) year = get_param(request, 'year', 'all') # {{{ Gather data earnings = player.earnings_set if year != 'all': earnings = earnings.filter(event__latest__year=year) earnings = earnings.prefetch_related('event__earnings_set').order_by( '-event__latest') totalearnings = earnings.aggregate(Sum('earnings'))['earnings__sum'] years = range(2010, datetime.now().year + 1) def year_is_valid(y): return player.earnings_set.filter(event__latest__year=y).exists() valid_years = filter(year_is_valid, years) # Get placement range for each prize for e in earnings: placements = get_placements(e.event) for prize, rng in placements.items(): if rng[0] <= e.placement <= rng[1]: e.rng = rng # }}} # {{{ Sum up earnings by currency currencies = {e.currency for e in earnings} by_currency = { cur: sum([e.origearnings for e in earnings if e.currency == cur]) for cur in currencies } if len(by_currency) == 1 and 'USD' in by_currency: by_currency = None # }}} base.update({ 'player': player, 'earnings': earnings, 'totalearnings': totalearnings, 'by_currency': by_currency, 'year': year, 'valid_years': reversed(list(valid_years)) }) return render_to_response('player_earnings.djhtml', base)
def history(request): base = base_ctx('Records', 'History', request) # {{{ Filtering (appears faster with custom SQL) nplayers = int(get_param(request, 'nplayers', '5')) race = get_param_choice(request, 'race', ['ptzrs', 'p', 't', 'z', 'ptrs', 'tzrs', 'pzrs'], 'ptzrs') nats = get_param_choice(request, 'nats', ['all', 'foreigners'] + list(data.ccn_to_cca2.values()), 'all') query = '''SELECT player.id, player.tag, player.race, player.country, MAX(rating.rating) AS high FROM player JOIN rating ON player.id=rating.player_id''' if race != 'ptzrs' or nats != 'all': query += ' WHERE ' ands = [] if race != 'ptzrs': ands.append( '(' + ' OR '.join(["player.race='%s'" % r.upper() for r in race]) + ')') if nats == 'foreigners': ands.append("(player.country!='KR')") elif nats != 'all': ands.append("(player.country='%s')" % nats) query += ' AND '.join(ands) query += ' GROUP BY player.id, player.tag, player.race, player.country ORDER BY high DESC LIMIT %i' % nplayers players = Player.objects.raw(query) # }}} base.update({ 'race': race, 'nats': nats, 'nplayers': nplayers, 'players': [(p, p.rating_set.select_related('period')) for p in players], 'countries': country_list(Player.objects.all()), 'charts': True, 'patches': PATCHES, }) return render_to_response('history.djhtml', base)
def api(request): base = base_ctx('About', 'API', request) if request.LANGUAGE_CODE != 'en': base['messages'].append( Message( _('The API documentation is only in English, sorry.'), type=Message.INFO, )) if request.method == 'POST': form = APIKeyForm(request) base['messages'] += form.add_key() else: form = APIKeyForm() base.update({'form': form}) return render_to_response('api.djhtml', base)
def clocks(request): ctx = base_ctx('Misc', 'Days Since…', request) ctx["clocks"] = list() for desc, alt_desc, q, t in CLOCKS: obj = None extra = None date = None if t == "match": q = q.prefetch_related("pla", "plb", "eventobj", "message_set") matches = q[:10] extra = display_matches(matches) date = extra[0]["date"] elif t == "event_winner": q = q.prefetch_related("earnings_set") events = list(q[:10]) obj = events[0] extra = list() for e in events: pearnings = list( e.earnings_set.exclude(placement=0).order_by( "placement").prefetch_related("player")[:2]) extra.append((e, pearnings)) date = obj.latest elif t == "one_time": date = q() diff = datetime.today().date() - date years = diff.days // 365 days = diff.days % 365 c = Clock(desc, alt_desc, obj, t, date, years, days, extra) ctx["clocks"].append(c) ctx["clocks"].sort(key=lambda c: c.date, reverse=True) return render_to_response("clocks.djhtml", ctx)
def historical(request, player_id): player = get_object_or_404(Player, id=player_id) base = base_ctx('Ranking', 'Rating history', request, context=player) latest = player.rating_set.filter(period__computed=True, decay=0).latest('period') historical = (player.rating_set.filter( period_id__lte=latest.period_id).prefetch_related( 'prev__rta', 'prev__rtb').select_related('period', 'prev').order_by('-period')) historical = add_counts(historical) base.update({ 'player': player, 'historical': historical, }) return render_to_response('historical.djhtml', base)
def home(request): base = base_ctx(request=request) if request.LANGUAGE_CODE != 'en': base['messages'].append( Message( _('The blog/news section is only in English, sorry.'), type=Message.INFO, )) entries = filter_active(Rating.objects.filter(period=base['curp']))\ .order_by('-rating')\ .select_related('player', 'prev')[0:10] entries = populate_teams(entries) blogs = Post.objects.order_by('-date')[0:3] base.update({'entries': entries, 'blogposts': blogs}) return render_to_response('index.djhtml', base)
def home(request): ctx = base_ctx('Misc', request=request) ctx["miscpages"] = ({ "url": "/misc/balance/", "title": _("Balance Report"), "desc": _("Charts showing balance in StarCraft II over time.") }, { "url": "/misc/days/", "title": _("Number of days since..."), "desc": _("Page showing the most recent time some things happened.") }, { "url": "/misc/compare/", "title": _("Compare"), "desc": _("Tool for comparing players.") }) return render_to_response("misc.djhtml", ctx)