コード例 #1
0
ファイル: submitviews.py プロジェクト: Arzar/aligulac
def review_treat_players(pm, base):
    def get_make_switch(lst):
        make_switch = False
        while lst[-1][0] == '!':
            if lst[-1] == '!MAKE':
                make_switch = True
                lst = lst[:-1]
        return lst, make_switch

    def get_race_info(lst):
        race = None
        while lst[-1][0:2].upper() == 'R:':
            race = lst[-1][2:].upper()
            lst = lst[:-1]
        return lst, race

    rca, rcb = None, None

    if not pm.pla:
        lst = list(pm.pla_string.split(' '))
        lst, make_switch_a = get_make_switch(lst)
        lst, rca = get_race_info(lst)
        pla = find_player(lst, make=make_switch_a)
        if pla.count() > 1:
            base['messages'].append(NotUniquePlayerMessage(' '.join(lst), pla))
        elif pla.count() == 0:
            base['messages'].append(Message('Player does not exist. Add !MAKE switch to create.',
                                            ' '.join(lst), type=Message.ERROR))
        else:
            pm.pla = pla[0]

    if rca:
        pm.rca = rca
    elif not pm.rca and pm.pla and pm.pla.race != 'S':
        pm.rca = pm.pla.race
    elif pm.pla and not pm.rca:
        base['messages'].append(Message('No race information for %s.' % str(pm.pla),
                                        'Race information missing', type=Message.ERROR))

    if not pm.plb:
        lst = list(pm.plb_string.split(' '))
        lst, make_switch_b = get_make_switch(lst)
        lst, rcb = get_race_info(lst)
        plb = find_player(lst, make=make_switch_b)
        if plb.count() > 1:
            base['messages'].append(NotUniquePlayerMessage(' '.join(lst), plb))
        elif plb.count() == 0:
            base['messages'].append(Message('Player does not exist. Add !MAKE switch to create.',
                                            ' '.join(lst), type=Message.ERROR))
        else:
            pm.plb = plb[0]

    if rcb:
        pm.rcb = rcb
    elif not pm.rcb and pm.plb and pm.plb.race != 'S':
        pm.rcb = pm.plb.race
    elif pm.plb and not pm.rcb:
        base['messages'].append(Message('No race information for %s.' % str(pm.plb),
                                        'Race information missing', type=Message.ERROR))
コード例 #2
0
ファイル: submitviews.py プロジェクト: orangeups/aligulac
def review_treat_players(pm, messages):
    def get_make_switch(lst):
        make_switch = False
        while lst[-1][0] == '!':
            if lst[-1] == '!MAKE':
                make_switch = True
                lst = lst[:-1]
        return lst, make_switch

    def get_race_info(lst):
        race = None
        while lst[-1][0:2].upper() == 'R:':
            race = lst[-1][2:].upper()
            lst = lst[:-1]
        return lst, race

    rca, rcb = None, None

    if not pm.pla:
        lst = list(pm.pla_string.split(' '))
        lst, make_switch_a = get_make_switch(lst)
        lst, rca = get_race_info(lst)
        pla = find_player(lst, make=make_switch_a)
        if pla.count() > 1:
            messages.append('Player not unique: \'%s\'. Add more information.' % ' '.join(lst))
        elif pla.count() == 0:
            messages.append('Player does not exist: \'%s\'. Add !MAKE switch to create.' % ' '.join(lst))
        else:
            pm.pla = pla[0]

    if rca:
        pm.rca = rca
    elif not pm.rca and pm.pla and pm.pla.race != 'S':
        pm.rca = pm.pla.race
    elif pm.pla and not pm.rca:
        messages.append('No race information for %s.' % str(pm.pla))

    if not pm.plb:
        lst = list(pm.plb_string.split(' '))
        lst, make_switch_b = get_make_switch(lst)
        lst, rcb = get_race_info(lst)
        plb = find_player(lst, make=make_switch_b)
        if plb.count() > 1:
            messages.append('Player not unique: \'%s\'. Add more information.' % ' '.join(lst))
        elif plb.count() == 0:
            messages.append('Player does not exist: \'%s\'. Add !MAKE switch to create.' % ' '.join(lst))
        else:
            pm.plb = plb[0]

    if rcb:
        pm.rcb = rcb
    elif not pm.rcb and pm.plb and pm.plb.race != 'S':
        pm.rcb = pm.plb.race
    elif pm.plb and not pm.rcb:
        messages.append('No race information for %s.' % str(pm.plb))
コード例 #3
0
ファイル: staff_views.py プロジェクト: kevinklaes/aligulac
def review_find_player(query):
    lst = shlex.split(query)
    override = find_race_override(lst)
    make_flag = '!MAKE' in lst
    lst = [l for l in lst if l != '!MAKE']

    return find_player(lst=lst, make=make_flag, soft=False), override
コード例 #4
0
ファイル: inference_views.py プロジェクト: Grovbolle/aligulac
    def clean_players(self):
        lines = self.cleaned_data['players'].splitlines()
        lineno, ok, players = -1, True, []
        self.messages = []

        for line in lines:
            lineno += 1
            if line.strip() == '':
                continue

            if line.strip() == '-' or line.strip().lower() == 'bye':
                players.append(None)
                continue

            pls = find_player(query=line, make=False)
            if not pls.exists():
                # Translators: Matches as in search matches
                self.messages.append(Message(_("No matches found: '%s'.") % line.strip(), type=Message.ERROR))
                ok = False
            elif pls.count() > 1:
                self.messages.append(NotUniquePlayerMessage(
                    line.strip(), pls, update=self['players'].auto_id,
                    updateline=lineno, type=Message.ERROR
                ))
                ok = False
            else:
                players.append(pls.first())

        if not ok:
            raise ValidationError(_('One or more errors found in player list.'))

        return players
コード例 #5
0
ファイル: views.py プロジェクト: peteryao/aligulac
def search(request, q=''):
    base = base_ctx(request=request)

    if q == '':
        q = request.GET['q']

    players = find_player(q.split(' '), make=False, soft=True)

    teams = Team.objects.all()
    for qpart in q.split(' '):
        if qpart.strip() == '':
            continue
        query = Q(name__icontains=qpart) | Q(alias__name__icontains=q)
        teams = teams.filter(query)
    teams = teams.distinct()

    events = Event.objects.filter(type__in=['category','event'])
    for qpart in q.split(' '):
        if qpart.strip() == '':
            continue
        events = events.filter(Q(fullname__icontains=qpart))
    events = events.order_by('lft')

    if players.count() == 1 and teams.count() == 0 and events.count() == 0:
        return redirect('/players/%i-%s/' % (players[0].id, urlfilter(players[0].tag)))
    elif players.count() == 0 and teams.count() == 1 and events.count() == 0:
        return redirect('/teams/%i-%s/' % (teams[0].id, urlfilter(teams[0].name)))
    elif players.count() == 0 and teams.count() == 0 and events.count() == 1:
        return redirect('/results/events/%i-%s/' % (events[0].id, urlfilter(events[0].fullname)))

    base.update({'players': players, 'query': q, 'teams': teams, 'events': events})

    return render_to_response('search.html', base)
コード例 #6
0
def review_find_player(query):
    lst = shlex.split(query)
    override = find_race_override(lst)
    make_flag = '!MAKE' in lst
    lst = [l for l in lst if l != '!MAKE']

    return find_player(lst=lst, make=make_flag, soft=False), override
コード例 #7
0
ファイル: predictviews.py プロジェクト: Arzar/aligulac
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)
コード例 #8
0
    def line_to_data(self, line):
        ind = line.find(' ')
        prize = Decimal(line[:ind])

        queryset = find_player(query=line[ind + 1:])
        if not queryset.exists():
            raise Exception(_("No such player: '%s'.") % line[ind + 1:])
        elif queryset.count() > 1:
            raise Exception(_("Ambiguous player: '%s'.") % line[ind + 1:])
        else:
            return prize, queryset.first()
コード例 #9
0
ファイル: results_views.py プロジェクト: KenanY/aligulac
    def line_to_data(self, line):
        ind = line.find(' ')
        prize = Decimal(line[:ind])

        queryset = find_player(query=line[ind+1:])
        if not queryset.exists():
            raise Exception(_("No such player: '%s'.") % line[ind+1:])
        elif queryset.count() > 1:
            raise Exception(_("Ambiguous player: '%s'.") % line[ind+1:])
        else:
            return prize, queryset.first()
コード例 #10
0
ファイル: staff_views.py プロジェクト: kevinklaes/aligulac
    def get_player(self, query, make_flag):
        players = find_player(lst=query, make=make_flag, soft=False)

        if players.count() != 1:
            if self.is_adm:
                if players.count() == 0:
                    self.messages.append(
                        Message(_("Could not find player: '%s'.") % ' '.join(query), type=Message.ERROR))
                    self.close_after = False
                elif players.count() > 1:
                    self.messages.append(
                        Message(_("Ambiguous player: '%s'.") % ' '.join(query), type=Message.ERROR))
                    self.close_after = False
            return None

        return players.first()
コード例 #11
0
ファイル: staff_views.py プロジェクト: willung/aligulac
    def get_player(self, query, make_flag):
        players = find_player(lst=query, make=make_flag, soft=False)
        printable = ' '.join(str(x) for x in query)
        if players.count() != 1:
            if self.is_adm:
                if players.count() == 0:
                    self.messages.append(
                        Message(_("Could not find player: '%s'.") % printable, type=Message.ERROR))
                    self.close_after = False
                elif players.count() > 1:
                    self.messages.append(
                        Message(_("Ambiguous player: '%s'.") % printable, type=Message.ERROR))
                    self.close_after = False
            return None

        return players.first()
コード例 #12
0
ファイル: tools.py プロジェクト: KenanY/aligulac
def search(query, search_for=['players', 'teams', 'events'], strict=False):
    # {{{ Split query
    lex = shlex.shlex(query, posix=True)
    lex.wordchars += "'#-"
    lex.commenters = ''
    lex.quotes = '"'

    terms = [s.strip() for s in list(lex) if s.strip() != '']
    if len(terms) == 0:
        return None
    # }}}

    # {{{ Search for players, teams and events
    if 'players' in search_for:
        players = find_player(lst=terms, make=False, soft=True, strict=strict)
    else:
        players = None

    if 'teams' in search_for:
        teams = Group.objects.filter(is_team=True)
    else:
        teams = None

    if 'events' in search_for:
        events = Event.objects.filter(type__in=[TYPE_CATEGORY, TYPE_EVENT]).order_by('idx')
        events = events.filter(
            fullname__iregex=(
                r"\s".join(r".*{}.*".format(term) for term in terms)
            )
        )
    else:
        events = None

    for term in terms:
        if 'teams' in search_for:
            teams = teams.filter(Q(name__icontains=term) | Q(alias__name__icontains=term))

    if 'teams' in search_for:
        teams = teams.distinct()
    # }}}

    return players, teams, events
コード例 #13
0
ファイル: submitviews.py プロジェクト: orangeups/aligulac
 def get_player(lst, failure, make, adm):
     try:
         pls = find_player(lst, make=make)
     except Exception as e:
         failure.append((s, 'Could not parse: ' + e.message))
         return None
     if not pls.exists() and adm:
         # Player not found, and user logged in. Add failure message and return None.
         failure.append((s, 'Could not find player \'%s\', add !MAKE switch to create'\
                 % ' '.join(lst)))
         return None
     if pls.count() > 1 and adm:
         # Too many players found, and used logged in. Add failure message and return None.
         failure.append((s, 'Player \'%s\' not unique, provide more information'\
                 % ' '.join(lst)))
         return None
     if not pls.exists() or pls.count() > 1:
         # Too many or too few players found, and user not logged in. Just return None.
         return None
     return pls[0]
コード例 #14
0
def search(query, search_for=['players', 'teams', 'events'], strict=False):
    # {{{ Split query
    lex = shlex.shlex(query, posix=True)
    lex.wordchars += "'#-"
    lex.commenters = ''
    lex.quotes = '"'

    terms = [s.strip() for s in list(lex) if s.strip() != '']
    if len(terms) == 0:
        return None
    # }}}

    # {{{ Search for players, teams and events
    if 'players' in search_for:
        players = find_player(lst=terms, make=False, soft=True, strict=strict)
    else:
        players = None

    if 'teams' in search_for:
        teams = Group.objects.filter(is_team=True)
    else:
        teams = None

    if 'events' in search_for:
        events = Event.objects.filter(
            type__in=[TYPE_CATEGORY, TYPE_EVENT]).order_by('idx')
        events = events.filter(fullname__iregex=(r"\s".join(
            r".*{}.*".format(term) for term in terms)))
    else:
        events = None

    for term in terms:
        if 'teams' in search_for:
            teams = teams.filter(
                Q(name__icontains=term) | Q(alias__name__icontains=term))

    if 'teams' in search_for:
        teams = teams.distinct()
    # }}}

    return players, teams, events
コード例 #15
0
ファイル: views.py プロジェクト: Lukepmcauley/aligulac
def search(request):
    base = base_ctx(request=request)

    # {{{ Split query
    query = get_param(request, 'q', '')
    terms = [s.strip() for s in shlex.split(query) if s.strip() != '']
    if len(terms) == 0:
        return redirect('/')
    # }}}

    # {{{ Search for players, teams and events
    players = find_player(lst=terms, make=False, soft=True)

    teams = Group.objects.filter(is_team=True)
    events = Event.objects.filter(type__in=[TYPE_CATEGORY, TYPE_EVENT]).order_by('idx')
    for term in terms:
        teams = teams.filter(Q(name__icontains=term) | Q(alias__name__icontains=term))
        events = events.filter(Q(fullname__icontains=term))
    teams = teams.distinct()
    # }}}

    # {{{ 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)
コード例 #16
0
    def clean_players(self):
        lines = self.cleaned_data['players'].splitlines()
        lineno, ok, players = -1, True, []
        self.messages = []

        for line in lines:
            lineno += 1
            if line.strip() == '':
                continue

            if line.strip() == '-' or line.strip().lower() == 'bye':
                players.append(None)
                continue

            pls = find_player(query=line, make=False)
            if not pls.exists():
                # Translators: Matches as in search matches
                self.messages.append(
                    Message(_("No matches found: '%s'.") % line.strip(),
                            type=Message.ERROR))
                ok = False
            elif pls.count() > 1:
                self.messages.append(
                    NotUniquePlayerMessage(line.strip(),
                                           pls,
                                           update=self['players'].auto_id,
                                           updateline=lineno,
                                           type=Message.ERROR))
                ok = False
            else:
                players.append(pls.first())

        if not ok:
            raise ValidationError(
                _('One or more errors found in player list.'))

        return players
コード例 #17
0
ファイル: submitviews.py プロジェクト: Arzar/aligulac
 def get_player(lst, failure, base, make, adm):
     #try:
     pls = find_player(lst, make=make)
     #except Exception as e:
         #failure.append(s)
         #base['messages'].append(Message('Could not parse: ' + e.message,
                                         #s, Message.ERROR))
         #return None
     if not pls.exists() and adm:
         # Player not found, and user logged in. Add failure message and return None.
         failure.append(s)
         base['messages'].append(Message(
             'Could not find player \'%s\', add !MAKE switch to create.' % ' '.join(lst),
             s, Message.ERROR))
         return None
     if pls.count() > 1 and adm:
         # Too many players found, and used logged in. Add failure message and return None.
         failure.append(s)
         base['messages'].append(NotUniquePlayerMessage(' '.join(lst), pls))
         return None
     if not pls.exists() or pls.count() > 1:
         # Too many or too few players found, and user not logged in. Just return None.
         return None
     return pls[0]
コード例 #18
0
ファイル: views.py プロジェクト: peteryao/aligulac
def results_search(request):
    base = base_ctx('Results', 'Search', request)
    base.update(csrf(request))

    if 'op' in request.POST and request.POST['op'] == 'Modify' and base['adm'] == True:
        num = 0
        if request.POST['event'] != 'nochange' and int(request.POST['event']) != 2:
            event = Event.objects.get(id=int(request.POST['event']))
        else:
            event = None

        for key in request.POST:
            if request.POST[key] != 'y':
                continue
            if key[0:6] == 'match-':
                match = Match.objects.get(id=int(key.split('-')[-1]))
                if request.POST['event'] != 'nochange':
                    match.eventobj = event
                    base['markevent'] = event
                if request.POST['date'].strip() != '':
                    match.date = request.POST['date']
                    base['markdate'] = request.POST['date']
                if request.POST['type'] != 'nochange':
                    match.offline = (request.POST['type'] == 'offline')
                    base['markoffline'] = request.POST['type']
                if request.POST['game'] != 'nochange':
                    match.game = request.POST['game']
                    base['markgame'] = request.POST['game']
                match.save()
                num += 1

        base['message'] = 'Modified %i matches.' % num

    if 'op' in request.GET and request.GET['op'] == 'search':
        matches = Match.objects.all()

        try:
            ints = [int(x) for x in request.GET['after'].split('-')]
            td = datetime.date(ints[0], ints[1], ints[2])
            matches = matches.filter(date__gte=td)
            base['after'] = request.GET['after']
        except:
            pass

        try:
            ints = [int(x) for x in request.GET['before'].split('-')]
            td = datetime.date(ints[0], ints[1], ints[2])
            matches = matches.filter(date__lte=td)
            base['before'] = request.GET['before']
        except:
            pass

        if 'unassigned' in request.GET and request.GET['unassigned'] == 'yes' and base['adm']:
            base['unassigned'] = True
            base['unassigned_get'] = 'yes'
            matches = matches.filter(eventobj__isnull=True)

        if 'eventtext' in request.GET and request.GET['eventtext'].strip() != '':
            base['eventtext'] = request.GET['eventtext'].strip()
            queries = [f.strip() for f in request.GET['eventtext'].strip().split(' ') if f.strip() != '']
            for query in queries:
                q = Q(eventobj__isnull=True, event__icontains=query) |\
                    Q(eventobj__isnull=False, eventobj__fullname__icontains=query)
                matches = matches.filter(q)

        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'

        if 'game' in request.GET:
            if request.GET['game'] != 'all':
                matches = matches.filter(game=request.GET['game'])
            base['game'] = request.GET['game']
        else:
            base['game'] = 'all'

        players, failures = [], []
        base['errs'] = []
        base['pls'] = request.GET['players']
        for line in request.GET['players'].splitlines():
            if line.strip() == '':
                continue
            pls = find_player(line.strip().split(' '), make=False)
            if not pls.exists():
                base['errs'].append('No players matching the query \'%s\'.' % line.strip())
            else:
                players.append(pls)

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

        pls = []
        for p in players:
            pls += p

        if len(pls) > 1:
            qa, qb = Q(), Q()
            for p in pls:
                qa |= Q(pla=p)
                qb |= Q(plb=p)
            matches = matches.filter(qa & qb)
        elif len(pls) == 1:
            q = Q(pla=pls[0]) | Q(plb=pls[0])
            matches = matches.filter(q)

        base['count'] = matches.count()

        if base['count'] > 1000:
            base['errs'].append('Too many results (%i). Please add restrictions.' % base['count'])
            return render_to_response('results_search.html', base)

        matches = matches.order_by('-date', 'eventobj__lft', 'event', 'id')

        if 1 <= len(pls) <= 2:
            base['matches'] = display_matches(matches, date=True, fix_left=pls[0])
            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.pla_score < m.plb_score else 0) for m in base['matches']])
            base['left'] = pls[0]
            if len(pls) == 2:
                base['right'] = pls[1]
        else:
            base['matches'] = display_matches(matches, date=True)

        if base['adm']:
            base['events'] = Event.objects.filter(closed=False, rgt=F('lft')+1).order_by('lft')

    return render_to_response('results_search.html', base)
コード例 #19
0
ファイル: results_views.py プロジェクト: KenanY/aligulac
    def search(self, adm):
        # {{{ Check validity (lol)
        if not self.is_valid():
            msgs = []
            msgs.append(Message(_('Entered data was invalid, no changes made.'), type=Message.ERROR))
            for field, errors in self.errors.items():
                for error in errors:
                    msgs.append(Message(error=error, field=self.fields[field].label))
            return {'messages': msgs}
        # }}}

        matches = (
            Match.objects.all().prefetch_related('message_set')
                .prefetch_related('pla', 'plb', 'period', 'eventobj')
                .annotate(Count('eventobj__match'))
        )

        # {{{ All the easy filtering
        if self.cleaned_data['after'] is not None:
            matches = matches.filter(date__gte=self.cleaned_data['after'])

        if self.cleaned_data['before'] is not None:
            matches = matches.filter(date__lte=self.cleaned_data['before'])

        if self.cleaned_data['unassigned'] and adm:
            matches = matches.filter(eventobj__isnull=True)

        if self.cleaned_data['bestof'] == '3':
            matches = matches.filter(Q(sca__gte=2) | Q(scb__gte=2))
        elif self.cleaned_data['bestof'] == '5':
            matches = matches.filter(Q(sca__gte=3) | Q(scb__gte=3))

        if self.cleaned_data['offline'] != 'both':
            matches = matches.filter(offline=(self.cleaned_data['offline']=='offline'))

        if self.cleaned_data['game'] != 'all':
            matches = matches.filter(game=self.cleaned_data['game'])
        # }}}

        # {{{ Filter by event
        if self.cleaned_data['event'] != None:
            lex = shlex.shlex(self.cleaned_data['event'], posix=True)
            lex.wordchars += "'"
            lex.quotes = '"'

            terms = [s.strip() for s in list(lex) if s.strip() != '']

            no_eventobj_q = Q(eventobj__isnull=True)

            for term in terms:
                no_eventobj_q &= Q(event__icontains=term)

            matches = matches.filter(
                no_eventobj_q |
                Q(
                    eventobj__isnull=False,
                    eventobj__fullname__iregex=(
                        r"\s".join(r".*{}.*".format(term) for term in terms)
                    )
                )
            )

        # }}}

        ret = {'messages': []}

        # {{{ Filter by players
        lines = self.cleaned_data['players'].splitlines()
        lineno, ok, players = -1, True, []
        for line in lines:
            lineno += 1
            if line.strip() == '':
                continue

            pls = find_player(query=line, make=False)
            if not pls.exists():
                ret['messages'].append(Message(
                    # Translators: Matches here as in search matches.
                    _("No matches found: '%s'.") % line.strip(), type=Message.ERROR
                ))
                ok = False
            else:
                if pls.count() > 1:
                    ret['messages'].append(NotUniquePlayerMessage(
                        line.strip(), pls, update=self['players'].auto_id,
                        updateline=lineno, type=Message.WARNING
                    ))

                players.append(list(pls))

        if not ok:
            return ret

        pls = []
        for p in players:
            pls += p

        if len(pls) > 1:
            matches = matches.filter(pla__in=pls, plb__in=pls)
        elif len(pls) == 1:
            matches = matches.filter(Q(pla__in=pls) | Q(plb__in=pls))
        # }}}

        # {{{ Collect data
        ret['count'] = matches.count()
        if ret['count'] > 1000:
            ret['messages'].append(Message(
                _('Too many results (%i). Please add restrictions.') % ret['count'],
                type=Message.ERROR
            ))
            return ret

        matches = matches.order_by('-eventobj__latest', '-eventobj__idx', '-date', 'event', 'id')
        if 1 <= len(pls) <= 2:
            ret['matches'] = display_matches(matches, date=True, fix_left=pls[0], eventcount=True)
            ret['sc_my'], ret['sc_op'] = (
                sum([m['pla']['score'] for m in ret['matches']]),
                sum([m['plb']['score'] for m in ret['matches']]),
            )
            ret['msc_my'], ret['msc_op'] = (
                sum([1 if m['pla']['score'] > m['plb']['score'] else 0 for m in ret['matches']]),
                sum([1 if m['plb']['score'] > m['pla']['score'] else 0 for m in ret['matches']]),
            )
            ret['left'] = pls[0]
            if len(pls) == 2:
                ret['right'] = pls[1]
        else:
            ret['matches'] = display_matches(matches, date=True, eventcount=True)

        return ret
コード例 #20
0
    def search(self, adm):
        # {{{ Check validity (lol)
        if not self.is_valid():
            msgs = []
            msgs.append(
                Message(_('Entered data was invalid, no changes made.'),
                        type=Message.ERROR))
            for field, errors in self.errors.items():
                for error in errors:
                    msgs.append(
                        Message(error=error, field=self.fields[field].label))
            return {'messages': msgs}
        # }}}

        matches = (Match.objects.all().prefetch_related(
            'message_set').prefetch_related('pla', 'plb', 'period',
                                            'eventobj').annotate(
                                                Count('eventobj__match')))

        # {{{ All the easy filtering
        if self.cleaned_data['after'] is not None:
            matches = matches.filter(date__gte=self.cleaned_data['after'])

        if self.cleaned_data['before'] is not None:
            matches = matches.filter(date__lte=self.cleaned_data['before'])

        if self.cleaned_data['unassigned'] and adm:
            matches = matches.filter(eventobj__isnull=True)

        if self.cleaned_data['bestof'] == '3':
            matches = matches.filter(Q(sca__gte=2) | Q(scb__gte=2))
        elif self.cleaned_data['bestof'] == '5':
            matches = matches.filter(Q(sca__gte=3) | Q(scb__gte=3))

        if self.cleaned_data['offline'] != 'both':
            matches = matches.filter(
                offline=(self.cleaned_data['offline'] == 'offline'))

        if self.cleaned_data['game'] != 'all':
            matches = matches.filter(game=self.cleaned_data['game'])
        # }}}

        # {{{ Filter by event
        if self.cleaned_data['event'] != None:
            lex = shlex.shlex(self.cleaned_data['event'], posix=True)
            lex.wordchars += "'"
            lex.quotes = '"'

            terms = [s.strip() for s in list(lex) if s.strip() != '']

            no_eventobj_q = Q(eventobj__isnull=True)

            for term in terms:
                no_eventobj_q &= Q(event__icontains=term)

            matches = matches.filter(no_eventobj_q
                                     | Q(eventobj__isnull=False,
                                         eventobj__fullname__iregex=(
                                             r"\s".join(r".*{}.*".format(term)
                                                        for term in terms))))

        # }}}

        ret = {'messages': []}

        # {{{ Filter by players
        lines = self.cleaned_data['players'].splitlines()
        lineno, ok, players = -1, True, []
        for line in lines:
            lineno += 1
            if line.strip() == '':
                continue

            pls = find_player(query=line, make=False)
            if not pls.exists():
                ret['messages'].append(
                    Message(
                        # Translators: Matches here as in search matches.
                        _("No matches found: '%s'.") % line.strip(),
                        type=Message.ERROR))
                ok = False
            else:
                if pls.count() > 1:
                    ret['messages'].append(
                        NotUniquePlayerMessage(line.strip(),
                                               pls,
                                               update=self['players'].auto_id,
                                               updateline=lineno,
                                               type=Message.WARNING))

                players.append(list(pls))

        if not ok:
            return ret

        pls = []
        for p in players:
            pls += p

        if len(pls) > 1:
            matches = matches.filter(pla__in=pls, plb__in=pls)
        elif len(pls) == 1:
            matches = matches.filter(Q(pla__in=pls) | Q(plb__in=pls))
        # }}}

        # {{{ Collect data
        ret['count'] = matches.count()
        if ret['count'] > 1000:
            ret['messages'].append(
                Message(_('Too many results (%i). Please add restrictions.') %
                        ret['count'],
                        type=Message.ERROR))
            return ret

        matches = matches.order_by('-eventobj__latest', '-eventobj__idx',
                                   '-date', 'event', 'id')
        if 1 <= len(pls) <= 2:
            ret['matches'] = display_matches(matches,
                                             date=True,
                                             fix_left=pls[0],
                                             eventcount=True)
            ret['sc_my'], ret['sc_op'] = (
                sum([m['pla']['score'] for m in ret['matches']]),
                sum([m['plb']['score'] for m in ret['matches']]),
            )
            ret['msc_my'], ret['msc_op'] = (
                sum([
                    1 if m['pla']['score'] > m['plb']['score'] else 0
                    for m in ret['matches']
                ]),
                sum([
                    1 if m['plb']['score'] > m['pla']['score'] else 0
                    for m in ret['matches']
                ]),
            )
            ret['left'] = pls[0]
            if len(pls) == 2:
                ret['right'] = pls[1]
        else:
            ret['matches'] = display_matches(matches,
                                             date=True,
                                             eventcount=True)

        return ret
コード例 #21
0
ファイル: lp.py プロジェクト: Arzar/aligulac
#!/usr/bin/python

'''
This is a quick script to easily set Liquipedia links.
'''

import os, sys
from urllib2 import urlopen, Request

# Without this, Django imports won't work correctly
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aligulac.settings")

from ratings.tools import find_player

# Use the regular search tool to find the player
player = find_player(sys.argv[1:-1])

# There can only be one
if player.count() > 1:
    print 'Player not unique, add more information'
    sys.exit(1)
elif player.count() < 1:
    print 'Player not found'
    sys.exit(1)
else:
    player = player[0]

# Write to database
p.lp_name = sys.argv[-1]
p.save()
コード例 #22
0
ファイル: predictviews.py プロジェクト: Arzar/aligulac
def predict(request):
    base = base_ctx('Predict', 'Predict', request)

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

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

    try:
        fmt = int(request.GET['format'])
        formats[fmt]
    except:
        base['messages'].append(Message('Unrecognized format ID: %s.' % request.GET['format'],
                                type=Message.ERROR))
    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['messages'].append(Message(
            '\'Best of\' must be a comma-separated list of positive odd integers (1,3,5,...).',
            type=Message.ERROR))
    base['bo'] = request.GET['bo']

    failures, players, lineno = [], [], -1
    for line in request.GET['players'].splitlines():
        lineno += 1
        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['messages'].append(NotUniquePlayerMessage(line, dbplayer, update='players',
                                                           updateline=lineno))
        elif not dbplayer.exists():
            base['messages'].append(Message('No such player found.', line, Message.ERROR))
        else:
            players.append(dbplayer[0])
    base['pls'] = request.GET['players']

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

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

    if len(base['messages']) != 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))
    elif fmt == 4:
        return redirect('/predict/proleague/?bo=%s&ps=%s' % (bo, ps))

    return render_to_response('predict.html', base)
コード例 #23
0
ファイル: predict.py プロジェクト: peteryao/aligulac
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)
コード例 #24
0
ファイル: predict.py プロジェクト: orangeups/aligulac
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)