Ejemplo n.º 1
0
def player_historical(request, player_id):
    player = get_object_or_404(Player, id=player_id)
    base = base_ctx('Ranking', 'Rating history', request, context=player)

    hist = list(Rating.objects.filter(player=player, period__computed=True).order_by('period__end'))
    historical = []

    init = 0
    search = 1
    while True:
        while init < len(hist) and hist[init].decay > 0:
            init += 1
        if init >= len(hist):
            break
        search = init + 1

        while search < len(hist) and hist[search].decay < 4:
            search += 1
        fin = search
        if search < len(hist):
            fin = search - 3
        
        if len(historical) > 0:
            historical.append(None)
        historical += hist[init:fin]

        init = search + 1

    historical = historical[::-1]

    base.update({'player': player, 'historical': historical})
    return render_to_response('historical.html', base)
Ejemplo n.º 2
0
def list(request):
    """Print all redirects"""
    base = base_ctx(request=request)

    base['minis'] = MiniURL.objects.order_by('-nb_access')

    return render(request, 'miniURL/list.html', base)
Ejemplo n.º 3
0
def periods(request):
    periods = Period.objects.filter(computed=True).order_by('-start')

    base = base_ctx('Ranking', 'History', request)
    base.update({'periods': periods})

    return render_to_response('periods.html', base)
Ejemplo n.º 4
0
def blog(request):
    posts = Post.objects.order_by('-date')[:10]

    base = base_ctx('About', 'Blog', request)
    base.update({'blogposts': posts})

    return render_to_response('blog.html', base)
Ejemplo n.º 5
0
def player_results(request, player_id):
    player = get_object_or_404(Player, id=int(player_id))
    matches = Match.objects.filter(Q(pla=player) | Q(plb=player))

    base = base_ctx('Ranking', 'Match history', request, context=player)

    if 'race' in request.GET:
        q = None
        for r in request.GET['race']:
            try:
                q |= Q(pla=player, rcb=r)
                q |= Q(plb=player, rca=r)
            except:
                q = Q(pla=player, rcb=r)
                q |= Q(plb=player, rca=r)
        matches = matches.filter(q)
        base['race'] = request.GET['race']
    else:
        base['race'] = 'ptzr'

    if 'nats' in request.GET:
        if request.GET['nats'] == 'foreigners':
            matches = matches.exclude(Q(pla=player, plb__country='KR') | Q(plb=player, pla__country='KR'))
        elif request.GET['nats'] == 'kr':
            matches = matches.filter(Q(pla=player, plb__country='KR') | Q(plb=player, pla__country='KR'))
        base['nats'] = request.GET['nats']
    else:
        base['nats'] = 'all'

    if 'bo' in request.GET:
        if request.GET['bo'] == '3':
            matches = matches.filter(Q(sca__gte=2) | Q(scb__gte=2))
        elif request.GET['bo'] == '5':
            matches = matches.filter(Q(sca__gte=3) | Q(scb__gte=3))
        base['bo'] = request.GET['bo']
    else:
        base['bo'] = 'all'
    
    if 'offline' in request.GET:
        if request.GET['offline'] == 'online':
            matches = matches.filter(offline=0)
        elif request.GET['offline'] == 'offline':
            matches = matches.filter(offline=1)
        base['offline'] = request.GET['offline']
    else:
        base['offline'] = 'both'
    
    matches = matches.order_by('-date', '-eventobj__lft', 'event', '-id')
    matches = matches.select_related('pla__rating').select_related('plb__rating').select_related('period')

    base['matches'] = display_matches(matches, fix_left=player, ratings=True)
    
    base['sc_my'] = sum([m.pla_score for m in base['matches']])
    base['sc_op'] = sum([m.plb_score for m in base['matches']])
    base['msc_my'] = sum([1 if m.pla_score > m.plb_score else 0 for m in base['matches']])
    base['msc_op'] = sum([1 if m.plb_score > m.pla_score else 0 for m in base['matches']])
    
    base['player'] = player
    
    return render_to_response('player_results.html', base)
Ejemplo n.º 6
0
def faq(request):
    posts = Post.objects.order_by('index')

    base = base_ctx('About', 'FAQ', request)
    base.update({'posts': posts})

    return render_to_response('faq.html', base)
Ejemplo n.º 7
0
def earnings(request):
    base = base_ctx('Ranking', 'Earnings', request)

    try:
        page = int(request.GET['page'])
    except:
        page = 1

    ranking = Earnings.objects.values('player').annotate(totalearnings=Sum('earnings')).order_by('-totalearnings')
    players = Player.objects.all()
    
    totalprizepool = Earnings.objects.aggregate(Sum('earnings'))['earnings__sum']
    
    for player in ranking:
        player["playerobj"] = players.get(id=player["player"])
        try:
            player["teamobj"] = player["playerobj"].teammembership_set.get(current=True)
        except:
            pass
    
    # Pages
    psize = 40
    nitems = ranking.count()
    npages = nitems/psize + (1 if nitems % psize > 0 else 0)
    page = min(max(page, 1), npages)
    startcount = (page-1)*psize

    ranking = ranking[(page-1)*psize:page*psize]

    base.update({'ranking': ranking, 'totalprizepool': totalprizepool, 'page': page, 'npages': npages, 'startcount': startcount})
    
    return render_to_response('earnings.html', base)
Ejemplo n.º 8
0
def player_earnings(request, player_id):
    player = get_object_or_404(Player, id=int(player_id))

    base = base_ctx('Ranking', 'Earnings', request, context=player)

    earnings = Earnings.objects.filter(player=player)
    totalearnings = earnings.aggregate(Sum('earnings'))['earnings__sum']
        
    for event in earnings:
        dict = get_placements(event.event)
        for earning, placement in dict.items():
            if event.placement in placement:
                event.min = min(placement)
                event.max = max(placement)
        
        event.earliest = event.event.get_earliest()
        event.latest = event.event.get_latest()
    
    #sort by latest date        
    def getLatest( object ):
        return object.latest
    earnings= list(earnings)
    earnings.sort( key=getLatest, reverse=True )

    base.update({'player': player, 'earnings': earnings, 'totalearnings': totalearnings})
    
    return render_to_response('player_earnings.html', base)
Ejemplo n.º 9
0
def pred_4pswiss(request):
    base = base_ctx('Predict', 'Predict', request=request)

    dbpl = [get_object_or_404(Player, id=int(i)) for i in request.GET['ps'].split(',')]
    sipl = [make_player(pl) for pl in dbpl]
    num = (int(request.GET['bo'])+1)/2
    obj = mslgroup.MSLGroup(num)
    obj.set_players(sipl)

    def update(request, obj, match, r1, r2):
        if r1 in request.GET and r2 in request.GET:
            try:
                if obj.get_match(match).can_modify():
                    obj.get_match(match).modify(int(request.GET[r1]), int(request.GET[r2]))
            except:
                pass

    update(request, obj, 'first',   '11', '12')
    update(request, obj, 'second',  '21', '22')
    update(request, obj, 'winners', '31', '32')
    update(request, obj, 'losers',  '41', '42')
    update(request, obj, 'final',   '51', '52')

    obj.compute()
    tally = obj.get_tally()

    players = list(sipl)
    for p in players:
        p.tally = tally[p]

    for i in range(0, 4):
        players.sort(key=lambda p: p.tally[i], reverse=True)

    base['players'] = players

    MatchObj = namedtuple('MatchObj', 'obj pla plb modded canmod fixed sca scb')
    matches = []
    for mname in ['first', 'second', 'winners', 'losers', 'final']:
        match = obj.get_match(mname)
        matches.append(MatchObj(match, match.get_player(0).dbpl, match.get_player(1).dbpl,\
                match.is_modified(), match.can_modify(), match.is_fixed(), match._result[0], match._result[1]))
    base['matches'] = matches

    MeanRes = namedtuple('MeanRes', 'pla plb sca scb')
    meanres = []
    for mname in ['first', 'second', 'winners', 'losers', 'final']:
        match = obj.get_match(mname)
        match.compute()
        lsup = match.find_lsup()
        meanres.append(MeanRes(match.get_player(0).dbpl, match.get_player(1).dbpl, lsup[1], lsup[2]))
        match.broadcast_instance((0, [lsup[4], lsup[3]], match))
    base['meanres'] = meanres

    base['ps'] = request.GET['ps']
    base['bo'] = request.GET['bo']

    fpswiss_postable(base, obj, players,
                     url='http://aligulac.com/predict/4pswiss/?bo=%s&ps=%s' % (base['bo'], base['ps']))
    return render_to_response('pred_4pswiss.html', base)
Ejemplo n.º 10
0
def integrity(request):
    base = base_ctx('Submit', 'Integrity', request)

    if not base['adm']:
        base.update(csrf(request))
        return render_to_response('login.html', base)

    add_login_message(base)
    base.update(csrf(request))

    with open(M_WARNINGS, 'r') as f:
        warnings = pickle.load(f)
    with open(M_APPROVED, 'r') as f:
        approved = pickle.load(f)

    if 'del' in request.POST or 'del_ok' in request.POST:
        ndel = 0
        for key in request.POST:
            if request.POST[key] != 'y':
                continue
            if key[0:6] == 'match-':
                try:
                    Match.objects.get(id=int(key.split('-')[-1])).delete()
                    ndel += 1
                except:
                    pass
        base['messages'].append(Message('Deleted %i match(es).' % ndel, type=Message.SUCCESS))

    if 'del_ok' in request.POST or 'false' in request.POST:
        warning = tuple([int(f) for f in request.POST['warning'].split(',')])
        warnings.remove(warning)
        approved.add(warning)

        with open(M_WARNINGS, 'w') as f:
            pickle.dump(warnings, f)
        with open(M_APPROVED, 'w') as f:
            pickle.dump(approved, f)
        base['messages'].append(Message('Resolved one integrity warning.', type=Message.SUCCESS))

    matches = []
    for w in warnings:
        block = []
        for id in w:
            try:
                block.append(Match.objects.get(id=id))
            except:
                pass
        matches.append((','.join(str(k) for k in list(w)), display_matches(block, messages=False)))

        if len(matches) == 50:
            break

    base['matches'] = matches
    if len(matches) == 0:
        base['messages'].append(Message('There are currently no warnings pending resolution.', 
                                        type=Message.INFO))
    base['num'] = len(warnings)

    return render_to_response('integrity.html', base)
Ejemplo n.º 11
0
def pred_proleague(request):
    base = base_ctx('Predict', 'Predict', request=request)

    dbpl = [get_object_or_404(Player, id=int(i)) for i in request.GET['ps'].split(',')]
    sipl = [make_player(pl) for pl in dbpl]
    num = (int(request.GET['bo'])+1)/2
    nplayers = len(sipl)
    obj = teampl.TeamPL(num)
    obj.set_players(sipl)

    def update(request, obj, match, r1, r2):
        if r1 in request.GET and r2 in request.GET:
            try:
                if obj.get_match(match).can_modify():
                    obj.get_match(match).modify(int(request.GET[r1]), int(request.GET[r2]))
            except:
                pass
        else:
            obj.get_match(match).modify(0, 0)

    for i in range(0, obj._nplayers):
        update(request, obj, i, 'm%i-1' % i, 'm%i-2' % i)

    obj.compute()

    ResObj = namedtuple('ResObj', 'scl scw proba probb')
    base['results'] = []
    base['prob_draw'] = 0.0
    for score in range(0,obj._nplayers+1):
        if 2*score < obj._nplayers:
            base['results'].append(ResObj(score, obj._nplayers-score,
                        obj.get_tally()[1][score], obj.get_tally()[0][score]))
        elif 2*score == obj._nplayers:
            base['prob_draw'] = obj.get_tally()[0][score]
        if 2*score >= obj._nplayers:
            break
    base['t1'] = sum([r.proba for r in base['results']])
    base['t2'] = sum([r.probb for r in base['results']])

    MatchObj = namedtuple('MatchObj', 'obj pla plb modded canmod fixed sca scb')
    matches = []
    base['s1'], base['s2'] = 0, 0
    for i in range(0, obj._nplayers):
        match = obj.get_match(i)
        matches.append(MatchObj(match, match.get_player(0).dbpl, match.get_player(1).dbpl,\
                    match.is_modified(), match.can_modify(), match.is_fixed(),\
                    match._result[0], match._result[1]))
        if match.is_fixed():
            base['s1'] += 1 if match._result[0] > match._result[1] else 0
            base['s2'] += 1 if match._result[1] > match._result[0] else 0
    base['matches'] = matches

    base['ps'] = request.GET['ps']
    base['bo'] = request.GET['bo']

    proleague_postable(base, obj, base['results'], base['prob_draw'], 
                     url='http://aligulac.com/predict/proleague/?bo=%s&ps=%s' % (base['bo'], base['ps']))
    return render_to_response('pred_proleague.html', base)
Ejemplo n.º 12
0
def manage(request):
    base = base_ctx('Submit', 'Misc', request)

    if not base['adm']:
        base.update(csrf(request))
        return render_to_response('login.html', base)

    add_login_message(base)
    base.update(csrf(request))

    if 'op' in request.POST and request.POST['op'] == 'merge':
        try:
            base['player_source'] = request.POST['player_source']
            base['player_target'] = request.POST['player_target']
            source = Player.objects.get(id=int(request.POST['player_source']))
            target = Player.objects.get(id=int(request.POST['player_target']))
        except:
            base['messages'].append(Message('Failed to find players. One or more incorrect IDs.',
                                            title='Merge error', type=Message.ERROR))
            return render_to_response('manage.html', base)

        if 'conf' in request.POST and request.POST['conf'] == 'yes':
            Match.objects.filter(pla=source).update(pla=target, treated=False)
            Match.objects.filter(plb=source).update(plb=target, treated=False)
            Earnings.objects.filter(player=source).update(player=target)
            Rating.objects.filter(player=source).delete()
            GroupMembership.objects.filter(player=source).delete()
            sourcename = source.tag
            source.delete()

            base['messages'].append(Message('%s was successfully merged into %s.' % (sourcename, target.tag),
                                            title='Merging complete', type=Message.SUCCESS))
            base['player_source'] = ''
            base['player_target'] = ''
        else:
            base['merge_conf'] = True
            base['source'] = source
            base['target'] = target
        return render_to_response('manage.html', base)

    if 'op' in request.POST and request.POST['op'] == 'treerestore':
        roots = list(Event.objects.filter(parent__isnull=True).order_by('lft'))
        nextleft = 0
        for r in roots:
            nextleft = r.reorganize(nextleft) + 1 
        base['messages'].append(Message('The NSM has been successfully restored.', 
                                        title='NSM restoration', type=Message.SUCCESS))
        return render_to_response('manage.html', base)

    if 'op' in request.POST and request.POST['op'] == 'namerestore':
        for event in Event.objects.all():
            event.update_name()
        base['messages'].append(Message('The event names have been successfully updated.', 
                                        title='Event name update', type=Message.SUCCESS))
        return render_to_response('manage.html', base)

    return render_to_response('manage.html', base)
Ejemplo n.º 13
0
def records(request):
    try:
        race = request.GET['race']
        sub = ['HoF','All','Protoss','Terran','Zerg'][['hof','all','P','T','Z'].index(race)]
    except:
        race = 'hof'
        sub = 'HoF'

    base = base_ctx('Records', sub, request)

    if race in ['all', 'T', 'P', 'Z']:
        high = Rating.objects.extra(select={'rat': 'rating'})\
                .filter(period__id__gt=24, decay__lt=4, dev__lte=0.2)
        highp = Rating.objects.extra(select={'rat': 'rating+rating_vp'})\
                .filter(period__id__gt=24, decay__lt=4, dev__lte=0.2)
        hight = Rating.objects.extra(select={'rat': 'rating+rating_vt'}).\
                filter(period__id__gt=24, decay__lt=4, dev__lte=0.2)
        highz = Rating.objects.extra(select={'rat': 'rating+rating_vz'}).\
                filter(period__id__gt=24, decay__lt=4, dev__lte=0.2)
        dom = Rating.objects.extra(select={'rat': 'domination'}).\
                filter(domination__gt=0.0, period__id__gt=24, decay__lt=4, dev__lte=0.2)

        if race in ['P','T','Z']:
            high = high.filter(player__race=request.GET['race'])
            highp = highp.filter(player__race=request.GET['race'])
            hight = hight.filter(player__race=request.GET['race'])
            highz = highz.filter(player__race=request.GET['race'])
            dom = dom.filter(player__race=request.GET['race'])
            base.update({'race': request.GET['race']})
        else:
            base.update({'race': ''})

        def sift(lst, num=5):
            ret = []
            pls = []
            for r in lst:
                if not r.player.id in pls:
                    pls.append(r.player.id)
                    ret.append(r)
                if len(ret) == num:
                    return ret
            return ret

        high = sift(high.order_by('-rat')[0:200])
        highp = sift(highp.order_by('-rat')[0:200])
        hight = sift(hight.order_by('-rat')[0:200])
        highz = sift(highz.order_by('-rat')[0:200])
        dom = sift(dom.order_by('-rat')[0:200])

        base.update({'hightot': high, 'highp': highp, 'hight': hight, 'highz': highz, 'dom': dom})
        return render_to_response('records.html', base)

    elif race in ['hof'] or True:
        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.html', base)
Ejemplo n.º 14
0
def pred_match(request):
    base = base_ctx("Predict", request=request)

    dbpl = [get_object_or_404(Player, id=int(i)) for i in request.GET["ps"].split(",")]
    sipl = [make_player(pl) for pl in dbpl]
    num = (int(request.GET["bo"]) + 1) / 2
    obj = match.Match(num)
    obj.set_players(sipl)

    s1, s2 = 0, 0
    if "s1" in request.GET:
        try:
            s1 = max(min(int(request.GET["s1"]), num), 0)
        except:
            pass
    if "s2" in request.GET:
        try:
            s2 = max(min(int(request.GET["s2"]), num), 0)
        except:
            pass

    obj.modify(s1, s2)
    obj.compute()

    base.update(
        {
            "p1": dbpl[0],
            "p2": dbpl[1],
            "r1": sipl[0].elo + sipl[0].elo_race[sipl[1].race],
            "r2": sipl[1].elo + sipl[1].elo_race[sipl[0].race],
        }
    )
    tally = obj.get_tally()
    base.update({"t1": tally[sipl[0]][1], "t2": tally[sipl[1]][1]})
    base["max"] = max(base["t1"], base["t2"])
    base["fav"] = dbpl[0] if base["t1"] > base["t2"] else dbpl[1]
    r1, r2 = [], []
    for oc in obj._outcomes:
        if oc[1] > oc[2]:
            r1.append((oc[1], oc[2], oc[0]))
        else:
            r2.append((oc[1], oc[2], oc[0]))

    while len(r1) < len(r2):
        r1 = [None] + r1
    while len(r2) < len(r1):
        r2 = [None] + r2
    base["res"] = zip(r1, r2)

    base["ps"] = request.GET["ps"]
    base["bo"] = request.GET["bo"]
    base["s1"] = s1
    base["s2"] = s2

    match_postable(base, obj, r1, r2, url="http://aligulac.com/predict/match/?bo=%s&ps=%s" % (base["bo"], base["ps"]))
    return render_to_response("pred_match.html", base)
Ejemplo n.º 15
0
def open_events(request):
    base = base_ctx('Submit', 'Open events', request)

    if not base['adm']:
        base.update(csrf(request))
        return render_to_response('login.html', base)

    add_login_message(base)
    base.update(csrf(request))

    if base['adm'] == True:
        if 'openevents' in request.POST:
            nclose = 0
            for event in request.POST.getlist('openevent'):
                Event.objects.get(id=event).close()
                nclose += 1
            base['messages'].append(Message('Closed %i events and their children.' % nclose,
                                            type=Message.SUCCESS))
        if 'prizepools' in request.POST:
            nmarked = 0
            for event in request.POST.getlist('prizepool'):
                Event.objects.get(id=event).set_prizepool(False)
                nmarked += 1
            base['messages'].append(Message('Marked %i events as having no prize pool.' % nmarked,
                                            type=Message.SUCCESS))

    openevents = []
    emptyopenevents = []
    noprizepoolevents = []
    events = Event.objects.filter(type="event", closed=False)
    ppevents = Event.objects.filter(prizepool__isnull=True, type="event", closed=True)
    
    for event in events:
        # If any of the subevents is not empty, add it to openevents.
        # Else it has no matches and so is added to emptyopenevents
        if Event.objects.filter(lft__gte=event.lft, rgt__lte=event.rgt, 
                                match__eventobj__isnull=False).exists():
            openevents.append(event)
        else:
            emptyopenevents.append(event)
            
    #exclude team events and empty events from no prize pool list 
    for event in ppevents:
        if event.get_root().category != "team" and Event.objects.filter(lft__gte=event.lft, 
                                               rgt__lte=event.rgt, match__eventobj__isnull=False).exists():
            noprizepoolevents.append(event)

    #remove "unknown events"
    emptyopenevents = emptyopenevents[1:]
    noprizepoolevents = noprizepoolevents[1:]

    base['openevents'] = openevents
    base['emptyopenevents'] = emptyopenevents
    base['noprizepoolevents'] = noprizepoolevents

    return render_to_response('events_open.html', base)
Ejemplo n.º 16
0
def balance(request):
    base = base_ctx('Reports', 'Balance', request)

    first = (2010,7)
    last = (datetime.date.today().year, datetime.date.today().month-1)
    if last[1] == 0:
        last[0] -= 1
        last[1] = 12

    N = (last[0]-first[0])*12 + last[1]-first[1] + 1

    def nti(x):
        return 0 if x is None else x

    def add_to_array(qset, rc1, rc2, ar, col):
        temp = qset.filter(rca=rc1, rcb=rc2).aggregate(Sum('sca'), Sum('scb'))
        ar[0, col] += nti(temp['sca__sum'])
        ar[1, col] += nti(temp['scb__sum'])
        temp = qset.filter(rca=rc2, rcb=rc1).aggregate(Sum('sca'), Sum('scb'))
        ar[0, col] += nti(temp['scb__sum'])
        ar[1, col] += nti(temp['sca__sum'])

    pvt_scores = zeros((2,N))
    pvz_scores = zeros((2,N))
    tvz_scores = zeros((2,N))
    time = []

    ind = 0
    delta = datetime.timedelta(days=15)
    while first[0] < last[0] or (first[0] == last[0] and first[1] <= last[1]):
        matches = Match.objects.filter(date__gte='%i-%i-01' % first)
        if first[1] < 12:
            matches = matches.filter(date__lt='%i-%i-01' % (first[0], first[1]+1))
        else:
            matches = matches.filter(date__lt='%i-%i-01' % (first[0]+1, 1))

        add_to_array(matches, 'P', 'T', pvt_scores, ind)
        add_to_array(matches, 'P', 'Z', pvz_scores, ind)
        add_to_array(matches, 'T', 'Z', tvz_scores, ind)
        time.append(datetime.date(month=first[1], year=first[0], day=15))

        first = (first[0], first[1]+1)
        if first[1] == 13:
            first = (first[0]+1, 1)
        ind += 1

    base['pvt'] = zip(100*pvt_scores[0,:]/(pvt_scores[0,:] + pvt_scores[1,:]), time)
    base['pvz'] = zip(100*pvz_scores[0,:]/(pvz_scores[0,:] + pvz_scores[1,:]), time)
    base['tvz'] = zip(100*tvz_scores[0,:]/(tvz_scores[0,:] + tvz_scores[1,:]), time)

    base['charts'] = True
    base['patches'] = PATCHES
    return render_to_response('reports_balance.html', base)
Ejemplo n.º 17
0
def teams(request):
    base = base_ctx('Teams', 'Ranking', request)

    base['teams'] = Group.objects.filter(active=True, is_team=True)
    if 'sort' in request.GET and request.GET['sort'] == 'pl':
        base['teams'] = base['teams'].order_by('-scorepl', '-scoreak')
    else:
        base['teams'] = base['teams'].order_by('-scoreak', '-scorepl')

    base['inactive'] = Group.objects.filter(active=False, is_team=True).order_by('name')

    return render_to_response('teams.html', base)
Ejemplo n.º 18
0
def manage(request):
    base = base_ctx('Submit', 'Misc', request)

    if not base['adm']:
        base.update(csrf(request))
        return render_to_response('login.html', base)

    base['user'] = request.user.username
    base.update(csrf(request))

    if 'op' in request.POST and request.POST['op'] == 'merge':
        try:
            base['player_source'] = request.POST['player_source']
            base['player_target'] = request.POST['player_target']
            source = Player.objects.get(id=int(request.POST['player_source']))
            target = Player.objects.get(id=int(request.POST['player_target']))
        except:
            base['merge_err'] = 'Failed to find players. One or more incorrect IDs.'
            return render_to_response('manage.html', base)

        if 'conf' in request.POST and request.POST['conf'] == 'yes':
            Match.objects.filter(pla=source).update(pla=target, treated=False)
            Match.objects.filter(plb=source).update(plb=target, treated=False)
            Earnings.objects.filter(player=source).update(player=target)
            Rating.objects.filter(player=source).delete()
            TeamMembership.objects.filter(player=source).delete()
            source.delete()

            base['merge_succ'] = 'Merging complete.'
            base['player_source'] = ''
            base['player_target'] = ''
        else:
            base['merge_conf'] = True
            base['source'] = source
            base['target'] = target
        return render_to_response('manage.html', base)

    if 'op' in request.POST and request.POST['op'] == 'treerestore':
        roots = list(Event.objects.filter(parent__isnull=True).order_by('lft'))
        nextleft = 0
        for r in roots:
            nextleft = r.reorganize(nextleft) + 1 
        base['treerestore_succ'] = 'The NSM has been restored.'
        return render_to_response('manage.html', base)

    if 'op' in request.POST and request.POST['op'] == 'namerestore':
        for event in Event.objects.all():
            event.update_name()
        base['namerestore_succ'] = 'The names have been updated.'
        return render_to_response('manage.html', base)

    return render_to_response('manage.html', base)
Ejemplo n.º 19
0
def integrity(request):
    base = base_ctx('Submit', 'Integrity', request)

    if not base['adm']:
        base.update(csrf(request))
        return render_to_response('login.html', base)

    base['user'] = request.user.username
    base.update(csrf(request))

    with open(M_WARNINGS, 'r') as f:
        warnings = pickle.load(f)
    with open(M_APPROVED, 'r') as f:
        approved = pickle.load(f)

    if 'del' in request.POST or 'del_ok' in request.POST:
        for key in request.POST:
            if request.POST[key] != 'y':
                continue
            if key[0:6] == 'match-':
                try:
                    Match.objects.get(id=int(key.split('-')[-1])).delete()
                except:
                    pass

    if 'del_ok' in request.POST or 'false' in request.POST:
        warning = tuple([int(f) for f in request.POST['warning'].split(',')])
        warnings.remove(warning)
        approved.add(warning)

        with open(M_WARNINGS, 'w') as f:
            pickle.dump(warnings, f)
        with open(M_APPROVED, 'w') as f:
            pickle.dump(approved, f)

    matches = []
    for w in warnings:
        block = []
        for id in w:
            try:
                block.append(Match.objects.get(id=id))
            except:
                pass
        matches.append((','.join(str(k) for k in list(w)), display_matches(block)))

        if len(matches) == 50:
            break
    base['matches'] = matches
    base['num'] = len(warnings)

    return render_to_response('integrity.html', base)
Ejemplo n.º 20
0
def pred_match(request):
    base = base_ctx('Predict', request=request)

    dbpl = [get_object_or_404(Player, id=int(i)) for i in request.GET['ps'].split(',')]
    sipl = [make_player(pl) for pl in dbpl]
    num = (int(request.GET['bo'])+1)/2
    obj = match.Match(num)
    obj.set_players(sipl)

    s1, s2 = 0, 0
    if 's1' in request.GET:
        try:
            s1 = max(min(int(request.GET['s1']), num), 0)
        except:
            pass
    if 's2' in request.GET:
        try:
            s2 = max(min(int(request.GET['s2']), num), 0)
        except:
            pass

    obj.modify(s1, s2)
    obj.compute()

    base.update({'p1': dbpl[0], 'p2': dbpl[1], 'r1': sipl[0].elo + sipl[0].elo_race[sipl[1].race],\
                 'r2': sipl[1].elo + sipl[1].elo_race[sipl[0].race]})
    tally = obj.get_tally()
    base.update({'t1': tally[sipl[0]][1], 't2': tally[sipl[1]][1]})
    base['max'] = max(base['t1'], base['t2'])
    base['fav'] = dbpl[0] if base['t1'] > base['t2'] else dbpl[1]
    r1, r2 = [], []
    for oc in obj._outcomes:
        if oc[1] > oc[2]:
            r1.append((oc[1], oc[2], oc[0]))
        else:
            r2.append((oc[1], oc[2], oc[0]))

    while len(r1) < len(r2):
        r1 = [None] + r1
    while len(r2) < len(r1):
        r2 = [None] + r2
    base['res'] = zip(r1, r2)
    
    base['ps'] = request.GET['ps']
    base['bo'] = request.GET['bo']
    base['s1'] = s1
    base['s2'] = s2

    match_postable(base, obj, r1, r2)
    return render_to_response('pred_match.html', base)
Ejemplo n.º 21
0
def results(request):
    base = base_ctx('Results', 'By Date', request)

    try:
        ints = [int(x) for x in request.GET['d'].split('-')]
        td = datetime.date(ints[0], ints[1], ints[2])
    except:
        td = datetime.date.today()

    matches = Match.objects.filter(date=td).order_by('eventobj__lft', 'event', 'id')

    base['matches'] = display_matches(matches, date=False, ratings=True)
    base['td'] = td

    return render_to_response('results.html', base)
Ejemplo n.º 22
0
def player_transfers(request):
    base = base_ctx('Teams', 'Transfers', request)
    
    trades = TeamMembership.objects.filter(Q(start__isnull=False) | Q(end__isnull=False))
    trades = trades.extra(select={'cdate':'CASE\
                                            WHEN start IS NULL THEN end\
                                            WHEN end IS NULL THEN start\
                                            WHEN start > end THEN start\
                                            ELSE end\
                                            END'})
    trades = trades.order_by('-cdate')[0:25]

    base["trades"] = trades
    
    return render_to_response('player_transfers.html', base)
Ejemplo n.º 23
0
def compare(request):
    base = base_ctx('Predict', 'Compare', request=request)

    if 'pla' not in request.GET and 'plb' not in request.GET:
        return render_to_response('compare.html', base)
    
    pla = find_player(request.GET['pla'].strip().split(' '), make=False)
    plb = find_player(request.GET['plb'].strip().split(' '), make=False)
    base['plas'] = request.GET['pla']
    base['plbs'] = request.GET['plb']

    for p, ps, id in [(pla, request.GET['pla'], 'pla'), (plb, request.GET['plb'], 'plb')]:
        if p.count() > 1:
            base['messages'].append(NotUniquePlayerMessage(ps, p, update=id))
        elif not p.exists():
            base['messages'].append(Message('No such player found.', ps, Message.ERROR))

    if len(base['messages']) > 0:
        return render_to_response('compare.html', base)

    pla, plb = pla[0], plb[0]
    base['pla'] = pla
    base['plb'] = plb

    rata = pla.rating_set.order_by('-period__id')[0]
    ratb = plb.rating_set.order_by('-period__id')[0]

    def analyze(pla, rata, plb, ratb, race):
        diff = rata.get_totalrating(race) - ratb.get_totalrating(race)
        dev = sqrt(rata.get_totaldev(race)**2 + ratb.get_totaldev(race)**2)
        if diff > 0:
            return pla, plb, cdf(-diff, scale=dev)
        else:
            return plb, pla, cdf(diff, scale=dev)

    base['winner'],    base['loser'],    base['sig'] =    analyze(pla, rata, plb, ratb, None)
    base['winner_vp'], base['loser_vp'], base['sig_vp'] = analyze(pla, rata, plb, ratb, 'P')
    base['winner_vt'], base['loser_vt'], base['sig_vt'] = analyze(pla, rata, plb, ratb, 'T')
    base['winner_vz'], base['loser_vz'], base['sig_vz'] = analyze(pla, rata, plb, ratb, 'Z')


    return render_to_response('compare.html', base)
Ejemplo n.º 24
0
def open_events(request):
    base = base_ctx('Submit', 'Open events', request)

    if not base['adm']:
        base.update(csrf(request))
        return render_to_response('login.html', base)

    base['user'] = request.user.username
    base.update(csrf(request))

    if base['adm'] == True:
        if 'openevents' in request.POST:
            for event in request.POST.getlist('openevent'):
                Event.objects.get(id=event).close()
        if 'prizepools' in request.POST:
            for event in request.POST.getlist('prizepool'):
                print "setting thingy false:"
                print event
                Event.objects.get(id=event).set_prizepool(False)

    openevents = []
    emptyopenevents = []
    events = Event.objects.filter(type="event", closed=False)
    noprizepoolevents = Event.objects.filter(prizepool__isnull=True, type="event", closed=True)
    
    for event in events:
        #If any of the subevents is not empty, add it to openevents. Else it has no matches and so is added to emptyopenevents
        if len(Event.objects.filter(lft__gte=event.lft, rgt__lte=event.rgt, match__eventobj__isnull=False)) > 0:
            openevents.append(event)
        else:
            emptyopenevents.append(event)
    
    #remove "unknown events"
    emptyopenevents = emptyopenevents[1:]
    noprizepoolevents = noprizepoolevents[1:]
                
    base['openevents'] = openevents
    base['emptyopenevents'] = emptyopenevents
    base['noprizepoolevents'] = noprizepoolevents

    
    return render_to_response('events_open.html', base)
Ejemplo n.º 25
0
def pred_rrgroup(request):
    base = base_ctx('Predict', request=request)

    dbpl = [get_object_or_404(Player, id=int(i)) for i in request.GET['ps'].split(',')]
    sipl = [make_player(pl) for pl in dbpl]
    num = (int(request.GET['bo'])+1)/2
    nplayers = len(sipl)
    obj = rrgroup.RRGroup(len(sipl), num, ['mscore', 'sscore', 'imscore', 'isscore', 'ireplay'], 1)
    obj.set_players(sipl)

    MeanRes = namedtuple('MeanRes', 'pla plb sca scb')
    meanres = []
    for i in range(0, (nplayers-1)*nplayers/2):
        match = obj.get_match(i)
        match.compute()
        lsup = match.find_lsup()
        meanres.append(MeanRes(match.get_player(0).dbpl, match.get_player(1).dbpl, lsup[1], lsup[2]))
        match.modify(lsup[1], lsup[2])
    base['meanres'] = meanres
    obj.compute()

    mtally = obj.get_tally()
    for p in sipl:
        p.mtally = mtally[p]

    base['mplayers'] = obj.table

    def update(request, obj, match, r1, r2):
        if r1 in request.GET and r2 in request.GET:
            try:
                if obj.get_match(match).can_modify():
                    obj.get_match(match).modify(int(request.GET[r1]), int(request.GET[r2]))
            except:
                pass
        else:
            obj.get_match(match).modify(0, 0)

    for i in range(0, (nplayers-1)*nplayers/2):
        update(request, obj, i, 'm%i-1' % i, 'm%i-2' % i)

    obj.compute()
    tally = obj.get_tally()

    players = list(sipl)
    for p in players:
        p.tally = tally[p][::-1]

    for i in range(len(players[0].tally)-1, -1, -1):
        players.sort(key=lambda p: p.tally[i], reverse=True)

    base['players'] = players

    MatchObj = namedtuple('MatchObj', 'obj pla plb modded canmod fixed sca scb')
    matches = []
    for i in range(0, (nplayers-1)*nplayers/2):
        match = obj.get_match(i)
        matches.append(MatchObj(match, match.get_player(0).dbpl, match.get_player(1).dbpl,\
                    match.is_modified(), match.can_modify(), match.is_fixed(),\
                    match._result[0], match._result[1]))
    base['matches'] = matches


    base['ps'] = request.GET['ps']
    base['bo'] = request.GET['bo']

    rrgroup_postable(base, obj, players)
    return render_to_response('pred_rrgroup.html', base)
Ejemplo n.º 26
0
def predict(request):
    base = base_ctx()
    base['curpage'] = 'Predict'

    formats = ['Best-of-N match', 'Four-player Swiss group', 'Single elimination bracket',\
               'Round robin group']
    base['formats'] = formats

    if 'format' not in request.GET:
        return render_to_response('predict.html', base)

    base['errs'] = []

    try:
        fmt = int(request.GET['format'])
        formats[fmt]
    except:
        base['errs'].append('Unrecognized format ID: %s' % request.GET['format'])
    base['fmt'] = fmt

    try:
        bo = [int(k.strip()) for k in request.GET['bo'].split(',') if k.strip() != '']
        assert(len(bo) != 0)
        for i in bo:
            assert(i % 2 == 1)
            assert(i > 0)
    except:
        base['errs'].append('\'Best of\' must be a comma-separated list of positive odd integers (1,3,5,...)')
    base['bo'] = request.GET['bo']

    failures, players = [], []
    for line in request.GET['players'].splitlines():
        if line.strip() == '':
            continue
        dbplayer = find_player(line.strip().split(' '), make=False)
        if dbplayer.count() > 1:
            base['errs'].append('Player \'%s\' not unique, add more information.' % line)
        elif not dbplayer.exists():
            base['errs'].append('No such player \'%s\' found.' % line)
        else:
            players.append(dbplayer[0])
    base['pls'] = request.GET['players']

    if len(base['errs']) != 0:
        return render_to_response('predict.html', base)

    if fmt == 0: 
        if len(players) != 2:
            base['errs'].append('Expected exactly two players')
        if len(bo) != 1:
            base['errs'].append('Expected exactly one \'best of\'')
    elif fmt == 1:
        if len(players) != 4:
            base['errs'].append('Expected exactly four player')
        if len(bo) != 1:
            base['errs'].append('Expected exactly one \'best of\'')
    elif fmt == 2:
        if len(players) not in [2,4,8,16,32,64,128,256,512,1024]:
            base['errs'].append('Expected number of players to be a power of two (2,4,8,...), got %i' % len(players))
        else:
            nrounds = int(log(len(players),2))
            if len(bo) != nrounds and len(bo) != 1:
                base['errs'].append('Expected exactly 1 or %i \'best of\'' % nrounds)
    elif fmt == 3:
        if len(players) < 3:
            base['errs'].append('Expected at least three players')
        if len(bo) != 1:
            base['errs'].append('Expected exactly one \'best of \'')

    if len(base['errs']) != 0:
        return render_to_response('predict.html', base)

    bo = '%2C'.join([str(b) for b in bo])
    ps = '%2C'.join([str(p.id) for p in players])
    if fmt == 0:
        return redirect('/predict/match/?bo=%s&ps=%s' % (bo, ps))
    elif fmt == 1:
        return redirect('/predict/4pswiss/?bo=%s&ps=%s' % (bo, ps))
    elif fmt == 2:
        return redirect('/predict/sebracket/?bo=%s&ps=%s' % (bo, ps))
    elif fmt == 3:
        return redirect('/predict/rrgroup/?bo=%s&ps=%s' % (bo, ps))

    return render_to_response('predict.html', base)
Ejemplo n.º 27
0
def pred_sebracket(request):
    base = base_ctx('Predict', request=request)

    dbpl = [get_object_or_404(Player, id=int(i)) for i in request.GET['ps'].split(',')]
    sipl = [make_player(pl) for pl in dbpl]
    nrounds = int(log(len(sipl),2))
    num = [(int(bo)+1)/2 for bo in request.GET['bo'].split(',')]
    if len(num) == 1:
        num = num * nrounds
    obj = sebracket.SEBracket(num)
    obj.set_players(sipl)

    def update(request, obj, match, r1, r2):
        if r1 in request.GET and r2 in request.GET:
            try:
                if obj.get_match(match).can_modify():
                    obj.get_match(match).modify(int(request.GET[r1]), int(request.GET[r2]))
            except:
                pass

    for rnd in range(1, nrounds+1):
        for j in range(1, 2**(nrounds-rnd)+1):
            s = '%i-%i' % (rnd, j)
            update(request, obj, s, 'm' + s + '-1', 'm' + s + '-2')

    obj.compute()
    tally = obj.get_tally()

    players = list(sipl)
    for p in players:
        p.tally = tally[p][::-1]

    for i in range(len(players[0].tally)-1, -1, -1):
        players.sort(key=lambda p: p.tally[i], reverse=True)

    base['players'] = players
    base['nrounds'] = nrounds

    MatchObj = namedtuple('MatchObj', 'obj pla plb modded canmod fixed sca scb id')
    matches = []
    for rnd in range(1, nrounds+1):
        matches.append('Round %i' % rnd)
        for j in range(1, 2**(nrounds-rnd)+1):
            match = obj.get_match('%i-%i' % (rnd, j))
            matches.append(MatchObj(match, match.get_player(0).dbpl, match.get_player(1).dbpl,\
                    match.is_modified(), match.can_modify(), match.is_fixed(),\
                    match._result[0], match._result[1], '%i-%i' % (rnd, j)))
    base['matches'] = matches

    MeanRes = namedtuple('MeanRes', 'pla plb sca scb')
    meanres = []
    for rnd in range(1, nrounds+1):
        meanres.append('Round %i' % rnd)
        for j in range(1, 2**(nrounds-rnd)+1):
            match = obj.get_match('%i-%i' % (rnd, j))
            match.compute()
            lsup = match.find_lsup()
            meanres.append(MeanRes(match.get_player(0).dbpl, match.get_player(1).dbpl, lsup[1], lsup[2]))
            match.broadcast_instance((0, [lsup[4], lsup[3]], match))
    base['meanres'] = meanres

    base['ps'] = request.GET['ps']
    base['bo'] = request.GET['bo']

    sebracket_postable(base, obj, players)
    return render_to_response('pred_sebracket.html', base)
Ejemplo n.º 28
0
def pred_rrgroup(request):
    base = base_ctx("Predict", request=request)

    dbpl = [get_object_or_404(Player, id=int(i)) for i in request.GET["ps"].split(",")]
    sipl = [make_player(pl) for pl in dbpl]
    num = (int(request.GET["bo"]) + 1) / 2
    nplayers = len(sipl)
    obj = rrgroup.RRGroup(len(sipl), num, ["mscore", "sscore", "imscore", "isscore", "ireplay"], 1)
    obj.set_players(sipl)

    MeanRes = namedtuple("MeanRes", "pla plb sca scb")
    meanres = []
    for i in range(0, (nplayers - 1) * nplayers / 2):
        match = obj.get_match(i)
        match.compute()
        lsup = match.find_lsup()
        meanres.append(MeanRes(match.get_player(0).dbpl, match.get_player(1).dbpl, lsup[1], lsup[2]))
        match.modify(lsup[1], lsup[2])
    base["meanres"] = meanres
    obj.compute()

    mtally = obj.get_tally()
    for p in sipl:
        p.mtally = mtally[p]

    base["mplayers"] = obj.table

    def update(request, obj, match, r1, r2):
        if r1 in request.GET and r2 in request.GET:
            try:
                if obj.get_match(match).can_modify():
                    obj.get_match(match).modify(int(request.GET[r1]), int(request.GET[r2]))
            except:
                pass
        else:
            obj.get_match(match).modify(0, 0)

    for i in range(0, (nplayers - 1) * nplayers / 2):
        update(request, obj, i, "m%i-1" % i, "m%i-2" % i)

    obj.compute()
    tally = obj.get_tally()

    players = list(sipl)
    for p in players:
        p.tally = tally[p][::-1]

    for i in range(len(players[0].tally) - 1, -1, -1):
        players.sort(key=lambda p: p.tally[i], reverse=True)

    base["players"] = players

    MatchObj = namedtuple("MatchObj", "obj pla plb modded canmod fixed sca scb")
    matches = []
    for i in range(0, (nplayers - 1) * nplayers / 2):
        match = obj.get_match(i)
        matches.append(
            MatchObj(
                match,
                match.get_player(0).dbpl,
                match.get_player(1).dbpl,
                match.is_modified(),
                match.can_modify(),
                match.is_fixed(),
                match._result[0],
                match._result[1],
            )
        )
    base["matches"] = matches

    base["ps"] = request.GET["ps"]
    base["bo"] = request.GET["bo"]

    rrgroup_postable(
        base, obj, players, url="http://aligulac.com/predict/rrgroup/?bo=%s&ps=%s" % (base["bo"], base["ps"])
    )
    return render_to_response("pred_rrgroup.html", base)
Ejemplo n.º 29
0
def predict(request):
    base = base_ctx()
    base["curpage"] = "Predict"

    formats = ["Best-of-N match", "Four-player Swiss group", "Single elimination bracket", "Round robin group"]
    base["formats"] = formats

    if "format" not in request.GET:
        return render_to_response("predict.html", base)

    base["errs"] = []

    try:
        fmt = int(request.GET["format"])
        formats[fmt]
    except:
        base["errs"].append("Unrecognized format ID: %s" % request.GET["format"])
    base["fmt"] = fmt

    try:
        bo = [int(k.strip()) for k in request.GET["bo"].split(",") if k.strip() != ""]
        assert len(bo) != 0
        for i in bo:
            assert i % 2 == 1
            assert i > 0
    except:
        base["errs"].append("'Best of' must be a comma-separated list of positive odd integers (1,3,5,...)")
    base["bo"] = request.GET["bo"]

    failures, players = [], []
    for line in request.GET["players"].splitlines():
        if line.strip() == "":
            continue
        elif line.strip() == "-" or line.strip().upper() == "BYE":
            players.append(None)
            continue

        dbplayer = find_player(line.strip().split(" "), make=False)
        if dbplayer.count() > 1:
            base["errs"].append("Player '%s' not unique, add more information." % line)
        elif not dbplayer.exists():
            base["errs"].append("No such player '%s' found." % line)
        else:
            players.append(dbplayer[0])
    base["pls"] = request.GET["players"]

    if len(base["errs"]) != 0:
        return render_to_response("predict.html", base)

    if fmt == 0:
        if len(players) != 2:
            base["errs"].append("Expected exactly two players")
        if len(bo) != 1:
            base["errs"].append("Expected exactly one 'best of'")
    elif fmt == 1:
        if len(players) != 4:
            base["errs"].append("Expected exactly four player")
        if len(bo) != 1:
            base["errs"].append("Expected exactly one 'best of'")
    elif fmt == 2:
        if len(players) not in [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024]:
            base["errs"].append("Expected number of players to be a power of two (2,4,8,...), got %i" % len(players))
        else:
            nrounds = int(log(len(players), 2))
            if len(bo) != nrounds and len(bo) != 1:
                base["errs"].append("Expected exactly 1 or %i 'best of'" % nrounds)
    elif fmt == 3:
        if len(players) < 3:
            base["errs"].append("Expected at least three players")
        if len(bo) != 1:
            base["errs"].append("Expected exactly one 'best of '")

    if len(base["errs"]) != 0:
        return render_to_response("predict.html", base)

    bo = "%2C".join([str(b) for b in bo])
    ps = "%2C".join([(str(p.id) if p is not None else "0") for p in players])
    if fmt == 0:
        return redirect("/predict/match/?bo=%s&ps=%s" % (bo, ps))
    elif fmt == 1:
        return redirect("/predict/4pswiss/?bo=%s&ps=%s" % (bo, ps))
    elif fmt == 2:
        return redirect("/predict/sebracket/?bo=%s&ps=%s" % (bo, ps))
    elif fmt == 3:
        return redirect("/predict/rrgroup/?bo=%s&ps=%s" % (bo, ps))

    return render_to_response("predict.html", base)
Ejemplo n.º 30
0
def pred_sebracket(request):
    base = base_ctx("Predict", request=request)

    dbpl = []
    for i in request.GET["ps"].split(","):
        id = int(i)
        if id > 0:
            dbpl.append(get_object_or_404(Player, id=id))
        else:
            dbpl.append(None)
    sipl = [make_player(pl) for pl in dbpl]
    nrounds = int(log(len(sipl), 2))
    num = [(int(bo) + 1) / 2 for bo in request.GET["bo"].split(",")]
    if len(num) == 1:
        num = num * nrounds
    obj = sebracket.SEBracket(num)
    obj.set_players(sipl)

    def update(request, obj, match, r1, r2):
        if r1 in request.GET and r2 in request.GET:
            try:
                if obj.get_match(match).can_modify():
                    obj.get_match(match).modify(int(request.GET[r1]), int(request.GET[r2]))
            except:
                pass

    for rnd in range(1, nrounds + 1):
        for j in range(1, 2 ** (nrounds - rnd) + 1):
            s = "%i-%i" % (rnd, j)
            update(request, obj, s, "m" + s + "-1", "m" + s + "-2")

    obj.compute()
    tally = obj.get_tally()

    players = list(sipl)
    for p in players:
        p.tally = tally[p][::-1]

    for i in range(len(players[0].tally) - 1, -1, -1):
        players.sort(key=lambda p: p.tally[i], reverse=True)

    base["players"] = [p for p in players if p.dbpl is not None]
    base["nrounds"] = nrounds

    MatchObj = namedtuple("MatchObj", "obj pla plb modded canmod fixed sca scb id")
    matches = []
    for rnd in range(1, nrounds + 1):
        matches.append("Round %i" % rnd)
        for j in range(1, 2 ** (nrounds - rnd) + 1):
            match = obj.get_match("%i-%i" % (rnd, j))
            if match.get_player(0).dbpl is not None and match.get_player(1).dbpl is not None:
                matches.append(
                    MatchObj(
                        match,
                        match.get_player(0).dbpl,
                        match.get_player(1).dbpl,
                        match.is_modified(),
                        match.can_modify(),
                        match.is_fixed(),
                        match._result[0],
                        match._result[1],
                        "%i-%i" % (rnd, j),
                    )
                )
    base["matches"] = matches

    MeanRes = namedtuple("MeanRes", "pla plb sca scb")
    meanres = []
    for rnd in range(1, nrounds + 1):
        meanres.append("Round %i" % rnd)
        for j in range(1, 2 ** (nrounds - rnd) + 1):
            match = obj.get_match("%i-%i" % (rnd, j))
            match.compute()
            lsup = match.find_lsup()
            meanres.append(MeanRes(match.get_player(0).dbpl, match.get_player(1).dbpl, lsup[1], lsup[2]))
            match.broadcast_instance((0, [lsup[4], lsup[3]], match))
    base["meanres"] = meanres

    base["ps"] = request.GET["ps"]
    base["bo"] = request.GET["bo"]

    sebracket_postable(
        base, obj, players, url="http://aligulac.com/predict/sebracket/?bo=%s&ps=%s" % (base["bo"], base["ps"])
    )
    return render_to_response("pred_sebracket.html", base)