Ejemplo n.º 1
0
def test_custom_no_score():
    assert ranks(Ranking([100, 50, 50, -1, -1], no_score=-1)) == \
           [0, 1, 1, None, None]
    assert ranks(Ranking([-1], no_score=-1)) == [None]
    assert ranks(Ranking([-1, -1], no_score=-1)) == [None, None]
    assert ranks(Ranking([3, 1, 1, -1], no_score=-1)) == [0, 1, 1, None]
    assert ranks(Ranking([1, 1, 3, -1], reverse=True, no_score=-1)) == \
           [0, 0, 2, None]
Ejemplo n.º 2
0
def leader(request):
    """Renders the leaderboard for all users"""
    currentuser = request.user
    pointlist = User.objects.filter(userpicks__game__season = currentseason)\
        .annotate(points=Sum('userpicks__pick__win'))\
        .order_by('-points', 'first_name')

    for person in pointlist:
        if person.points == None:
            person.points = 0

    def getPoints(self):
        return self.points

    def breakTie(self):
        return (abs(
            self.userpicks_set.get(game__game__contains=champgame).tiebreak -
            true_score), self)

    def getBreakTie(self):
        return breakTie(self)[0]

    true_score = Game.objects.get(game__contains=champgame).totalscore
    if true_score is None:
        ranks = Ranking(pointlist, start=1, key=getPoints)
        ranklist = list(ranks)
        winner = False
    else:
        ranks = Ranking(pointlist, start=1, key=getPoints)
        ranklist = list(ranks)

        firstplacelist = [x for (rank, x) in ranklist if rank == 1]

        firstplaceranks = [breakTie(x) for x in firstplacelist]
        firstplaceranks.sort()
        firstplace = firstplaceranks[0]
        pointlist2 = User.objects.filter(userpicks__game__season = currentseason)\
            .exclude(id = firstplace[1].id)\
            .annotate(points=Sum('userpicks__pick__win'))\
            .order_by('-points', 'first_name')
        for person in pointlist2:
            if person.points == None:
                person.points = 0
        therest = Ranking(pointlist2, start=2, key=getPoints)
        ranklist = list(therest)
        ranklist.insert(0, (1, firstplace[1]))
        winner = firstplace[1].first_name

    context = {
        'pointlist': ranklist,
        'currentuser': currentuser,
        'winner': winner
    }
    return render(request, 'picks/leaderboard.html', context)
Ejemplo n.º 3
0
def print_all_category_scores(weekly_score_dict):
    team_category_map = {}

    for category, category_list in weekly_score_dict.items():
        category_name = category_dict[category]

        category_string = f""
        for index, category_tuple in Ranking(category_list,
                                             strategy=FRACTIONAL,
                                             key=lambda x: x[1]):
            team_rank = index + 1
            team_id = category_tuple[0]
            team_name = team_dict[team_id]
            team_category_value = category_tuple[1]
            if team_name in team_category_map:
                team_category_map[team_name].update({
                    category_name: {
                        "rank": team_rank,
                        "category_value": team_category_value
                    }
                })
            else:
                team_category_map[team_name] = {
                    category_name: {
                        "rank": team_rank,
                        "category_value": team_category_value
                    }
                }

            category_string += f' ({team_rank}) {team_name} {team_category_value} |'
        print(category_string)
    return team_category_map
Ejemplo n.º 4
0
def get_csv(df, csv_path, risk_factor, questions, top_k = 1, device = -1, dict_path = 'Data/ranking_dict'):

    dataset = df #pd.read_csv(df_path, sep=';')

    ranking = Ranking('texts', path= dict_path)
    qa_model = pipeline('question-answering', device=device, model='bert-large-uncased-whole-word-masking-finetuned-squad')

    print('All loaded')

    all_query = ' '.join(questions)
    documents = get_documents(dataset, ranking, all_query, top_k = top_k)
    print('Length documents: {}'.format(len(documents)))

    results = pd.DataFrame(columns=['date', 'title', 'authors', 'design', 'level_of_evidence'] + questions)

    print('Starting docs for {}: \n'.format(risk_factor))

    for doc in documents:
        row = dataset.loc[dataset.text == doc]
        new_line = get_information(row)
        #new_line = {'paper_id': paper_id}
        for query in questions:
            answer, paragraph = get_answer_from_doc(query, doc, qa_model)
            new_line[query] = str(paragraph.replace(answer, f"<mark>{answer}</mark>")) 
            print(answer)
        results = results.append(new_line, ignore_index=True)
        
    results.to_csv(csv_path, sep=';', index=False)
Ejemplo n.º 5
0
def calculate_final_rankings(round_dicts, total_players=24):
    number_matches = 0
    previous_number_matches = 0
    for index, round in enumerate(round_dicts):
        number_matches = number_matches + len(round['division_final_matches'])
        if round['completed'] is not True:
            continue
        unranked_match_players = []
        matches_in_current_round = len(round['division_final_matches'])
        for match in round['division_final_matches']:
            for match_player in match['final_match_player_results']:
                if match_player['winner'] is not True or index == len(
                        round_dicts) - 1:
                    unranked_match_players.append(match_player)

        sorted_player_list = sorted(unranked_match_players,
                                    key=lambda e: e['papa_points_sum'],
                                    reverse=True)
        ranked_player_list = list(
            Ranking(sorted_player_list, key=lambda pp: pp['papa_points_sum']))
        ranked_player_dict = {
            ranked_player[1]['final_player_id']: ranked_player
            for ranked_player in ranked_player_list
        }
        base_rank = total_players - (number_matches * 4) / 2
        if index == len(round_dicts) - 1:
            base_rank = 0
        for ranked_final_player_id, ranked_final_player in ranked_player_dict.iteritems(
        ):
            if ranked_final_player[1]['winner'] is not True or index == len(
                    round_dicts) - 1:
                ranked_final_player[1][
                    'final_rank'] = base_rank + ranked_final_player[0] + 1
Ejemplo n.º 6
0
def remove_missing_final_player(final_player_list, app):
    pruned_final_players = []
    final_player_list = [
        final_player for final_player in final_player_list
        if final_player['type'] == 'result'
    ]
    for final_player in final_player_list:
        if 'removed' in final_player and final_player['removed'] is not True:
            final_player['removed '] = False
            final_player['reranked_seed'] = final_player['initial_seed']
            pruned_final_players.append(final_player)

    sorted_final_players = sorted(pruned_final_players,
                                  key=lambda e: e['reranked_seed'])
    reranked_pruned_final_players_list = list(
        Ranking(sorted_final_players,
                key=lambda pp: pp['reranked_seed'],
                reverse=True))
    # NOTE : reranked ranks start at 0, not 1
    reranked_pruned_final_players_hash = {
        final_player[1]["player_id"]: final_player[0]
        for final_player in reranked_pruned_final_players_list
    }
    for index, final_player in enumerate(final_player_list):
        #if 'removed' in final_player and final_player['removed']:
        #    final_player['initial_seed']=None
        if 'removed' in final_player and final_player['removed'] is False:
            final_player['reranked_seed'] = reranked_pruned_final_players_hash[
                final_player['player_id']]
    return final_player_list
Ejemplo n.º 7
0
 def get_ranking(self):
     """
     returns a ranking list, containing the ranks of the included
     target translations
     @return: the ranking list
     @rtype: Ranking
     """
     return Ranking([s.get_rank() for s in self.tgt])
    def getRankingForFile(self, filename) -> Ranking:
        repetition = defaultdict(lambda: 0)

        for baseWord in self._generate(filename):
            repetition[baseWord] += 1

        ranking = sorted(repetition.items(), key=itemgetter(1), reverse=True)
        return Ranking(ranking)
Ejemplo n.º 9
0
 def human_rank(self):
     from data_apis import top_human_squads
     ths = top_human_squads(self.game)
     squad_score = [
         x['human_points'] for x in ths if x['squad_id'] == self.id
     ][0]
     scores = [x['human_points'] for x in ths]
     return (Ranking(scores, start=1).rank(squad_score), len(ths))
Ejemplo n.º 10
0
 def zombie_rank(self):
     from data_apis import top_zombie_squads
     tzs = top_zombie_squads(self.game)
     squad_score = [
         x['zombie_points'] for x in tzs if x['squad_id'] == self.id
     ][0]
     scores = [x['zombie_points'] for x in tzs]
     return (Ranking(scores, start=1).rank(squad_score), len(tzs))
Ejemplo n.º 11
0
 def human_rank(self):
     from data_apis import top_humans
     th = top_humans(self.game)
     player_score = [
         x['human_points'] for x in th if x['player_id'] == self.id
     ][0]
     scores = [x['human_points'] for x in th]
     return (Ranking(scores, start=1).rank(player_score), len(th))
Ejemplo n.º 12
0
    def testAddUsersFromDB(self):
        self.R.reset()

        self.R.c.executemany(queries.INSERT_KNOWN_USERS, USERS)

        R = Ranking(1, conn=self.R.conn)

        self.assertTrue(all([user[0] in R.known_users for user in USERS]),
                        "All of the users were not added from DB")
Ejemplo n.º 13
0
def test_capsuled_scores():
    class User(object):
        def __init__(self, score):
            self.score = score

        def __lt__(self, other):
            raise NotImplemented

        def __gt__(self, other):
            raise NotImplemented

    users = [User(100), User(80), User(80), User(79)]
    with raises(TypeError):
        list(Ranking(users))
    key = lambda user: user.score
    ranking = Ranking(users, key=key)
    assert ranks(ranking) == [0, 1, 1, 3]
    assert isinstance(next(iter(ranking))[1], User)
Ejemplo n.º 14
0
 def guarda_puntajes(self):
     partida = Ranking(self.master.master.puntaje.get(),
                       self.master.master.nombre.get(),
                       self.master.master.dificultad.get(),
                       self.tiempo_juego_total, constantes.RANKING)
     if partida.es_puntaje_alto():
         t = Timer(1.1, lambda: [self.aviso_puntaje_alto()])
         t.start()
     partida.guarda_partida_csv()
     partida.ordena_puntaje_cvs()
Ejemplo n.º 15
0
def rank(x, ties_method="average"):
    ox = np.argsort(-x)
    sx = np.argsort(ox)
    if ties_method == "average":
        strategy = ranking.FRACTIONAL
    else:
        strategy = ranking.COMPETITION
    r = Ranking(x[ox], strategy=strategy, start=1)
    rnks = list(r.ranks())
    return np.array(rnks)[sx]
Ejemplo n.º 16
0
    def testAddDualsFromDB(self):
        self.R.c.executemany(queries.INSERT_DUALS, DUALS)
        self.R.c.executemany(queries.INSERT_RATINGS, RATINGS)

        R = Ranking(1, self.R.conn)

        submitters = [user[0] for user in USERS]
        self.assertTrue(
            all(dual.submitter[0] in submitters for dual in R.duals),
            "All of the duals were not added from the DB")
Ejemplo n.º 17
0
def sort_user_results_with_rankings(results: List[UserEventResults],
                                    event_format: EventFormat) -> List[Tuple[int, str, UserEventResults]]:
    """ Sorts a list of UserEventResults based on the event format (for tie-breaking), and then applies rankings
    (identical results receive identical rankings). Returns a list of tuples of the form (ranking, visible_ranking,
    userEventResult), where ranking is the raw numerical rank and visible_ranking is the same as ranking except
    duplicate ranks show as an empty string. """

    # Best-of-N results are only ranked by singles
    if event_format in [EventFormat.Bo1, EventFormat.Bo3]:
        results.sort(key=__sort_user_event_results_by_result)

    # Average/mean results are sorted by single first, to ensure any ties by overall result (average/mean) are broken
    # by the singles.
    else:
        results.sort(key=__sort_user_event_results_by_single)
        results.sort(key=__sort_user_event_results_by_result)

    # Build a list of tuples (average/mean, single), to be fed into the ranking mechanism.
    # If the time value cannot be interpreted as an int, it's a "DNF" or None, so just assign it some humongous value
    # which would sorted at the end.
    times_values = list()
    for result in results:
        try:
            average = int(result.result)
        except (ValueError, TypeError):
            average = 9999999999999
        try:
            single = int(result.single)
        except (ValueError, TypeError):
            single = 9999999999999
        times_values.append((average, single))

    # Rank the list of times tuples. Legitimately tied results will have the same rank, so we also send back a
    # "visible rank" which facilitates showing the results nicely. Ranks with ties will look something like this:
    #
    #   Place     Result
    #   -----     ------
    #     1        10.2
    #     2        15
    #              15
    #     4        17.84

    ranks_seen = set()
    ranked_results = list()

    for i, r in enumerate(Ranking(times_values, start=1, reverse=True)):
        rank = r[0]
        if rank not in ranks_seen:
            ranks_seen.add(rank)
            visible_rank = str(rank)
        else:
            visible_rank = ''
        ranked_results.append((rank, visible_rank, results[i]))

    return ranked_results
Ejemplo n.º 18
0
    def testAddSinglesFromDB(self):
        self.R.reset()
        self.R.c.executemany(queries.INSERT_SINGLES, SINGLES)
        self.R.c.executemany(queries.INSERT_RATINGS, RATINGS)

        R = Ranking(1, self.R.conn)

        submitters = [user[0] for user in USERS]
        self.assertTrue(
            all(match.submitter[0] in submitters for match in R.singles),
            "All of the matches were not added from the DB")
Ejemplo n.º 19
0
 def zombie_rank(self):
     from data_apis import top_zombies
     tz = top_zombies(self.game)
     try:
         player_score = [
             x['zombie_points'] for x in tz if x['player_id'] == self.id
         ][0]
     except:
         return None
     scores = [x['zombie_points'] for x in tz]
     return (Ranking(scores, start=1).rank(player_score), len(tz))
Ejemplo n.º 20
0
def update():
    container = Artikel.query.all()
    preproses = PreProses(container)
    stopword = preproses.stopword()
    stemming = preproses.stemming(stopword)
    normalisasi = preproses.normalisasi(stemming)
    koleksi = preproses.koleksi(normalisasi)

    rank_store = Ranking(normalisasi, koleksi)
    bobot_doc = rank_store.bobotDokumen()
    bobot_kata = rank_store.bobotKata(bobot_doc)
    bobot_kata_doc = rank_store.bobotKataDokumen(bobot_kata, bobot_doc)

    Koleksi.query.delete()
    Indexing.query.delete()
    BobotDoc.query.delete()
    BobotKata.query.delete()
    BobotKataDoc.query.delete()

    key_id = []
    for x in container:
        key_id.append(str(x.id))

    for i, dokumen in enumerate(normalisasi):
        for kata in dokumen:
            key = key_id[i]
            indexing_db = Indexing(key, kata)
            db.session.add(indexing_db)
    db.session.commit()

    for kata in koleksi:
        koleksi_db = Koleksi(kata)
        db.session.add(koleksi_db)
    db.session.commit()

    for i, dokumen in enumerate(bobot_doc):
        for kata in dokumen:
            index = str(i + 1)
            bobot_doc_db = BobotDoc(index, kata)
            db.session.add(bobot_doc_db)
    db.session.commit()

    for kata in bobot_kata:
        bobot_kata_db = BobotKata(kata)
        db.session.add(bobot_kata_db)
    db.session.commit()

    for i, dokumen in enumerate(bobot_kata_doc):
        for kata in dokumen:
            index = str(i + 1)
            bobot_kata_doc_db = BobotKataDoc(index, kata)
            db.session.add(bobot_kata_doc_db)
    db.session.commit()
    return redirect(url_for('admin', success='Articles successfully updated'))
Ejemplo n.º 21
0
    async def load_all(self):
        self.messages = load_messages()

        self.player_manager = PlayerManager()
        await self.player_manager.load_data()
        await self.update_mentions()

        ranking_config = load_ranking_config("base")
        self.ranking = Ranking(self.player_manager,
                               **ranking_config)

        await self.ranking.fetch_data(self.matchboard)
def convertToRanks(freqDistBigrams):

    #print("In RANKING")
    #print(freqDistBigrams)
    freqList = [x[1] for x in freqDistBigrams]
    #print(freqList)
    rankList = list(Ranking(freqList, start=1))
    #print(rankList)
    freDist_New = [
        tuple([x[0], y[0]]) for x, y in zip(freqDistBigrams, rankList)
    ]
    #print(freDist_New)
    return freDist_New
Ejemplo n.º 23
0
 def rank(self):
     competitors = self.competitors.filter(
         is_private=False,
         status__gt=0,
     ).distinct().order_by('-tot_points')
     points = [x.tot_points for x in competitors]
     ranked = Ranking(points, strategy=ORDINAL, start=1)
     for competitor in competitors:
         competitor.tot_rank = ranked.rank(competitor.tot_points)
         competitor.save()
     competitors = self.competitors.filter(
         is_private=False,
         status__gt=0,
     ).distinct().order_by('-mus_points')
     points = [x.mus_points for x in competitors]
     ranked = Ranking(points, start=1)
     for competitor in competitors:
         competitor.mus_rank = ranked.rank(competitor.mus_points)
         competitor.save()
     competitors = self.competitors.filter(
         is_private=False,
         status__gt=0,
     ).distinct().order_by('-per_points')
     points = [x.per_points for x in competitors]
     ranked = Ranking(points, start=1)
     for competitor in competitors:
         competitor.per_rank = ranked.rank(competitor.per_points)
         competitor.save()
     competitors = self.competitors.filter(
         is_private=False,
         status__gt=0,
     ).distinct().order_by('-sng_points')
     points = [x.sng_points for x in competitors]
     ranked = Ranking(points, start=1)
     for competitor in competitors:
         competitor.sng_rank = ranked.rank(competitor.sng_points)
         competitor.save()
     return
Ejemplo n.º 24
0
    def __init__(self, seed_file, data_dir, similarity_method):
        if not os.path.exists(data_dir):
            os.makedirs(data_dir)
        self.ranked_urls_file = data_dir + "/ranked_urls.csv"

        self.seed_urls = self._read_urls_from_file(seed_file)
        print "Number of seed urls: ", len(self.seed_urls)
        self.discovered_urls = set()
        for url in self.seed_urls:
            self.discovered_urls.add(url)

        self.searcher = Search_APIs(data_dir)
        self.ranker = Ranking(data_dir, self.seed_urls, similarity_method)
        self.seed_threshold = 0.1  # minimum score for an url to be selected as a seed
        self.search_threshold = 0.05  # minimum score for an url to be selected for search
Ejemplo n.º 25
0
 def __init__(self, win, connection=None):
     pygame.font.init()
     self.connection = connection
     self.win = win  # okno do wyswietlania
     # inicjalizacja parametrow
     self.ranking = Ranking(50, 125)
     self.tablica = Tablica(305, 125)
     self.pasek_gorny = PasekGorny(50, 10, 990, 100)
     self.pasek_gorny.zmiana_rundy(1)
     self.gracze = []
     self.pomin_button = PrzyciskTekstowy(810, 555, 225, 50, (255, 255, 0), "Pomin")
     self.pasek_dolny = PasekDolny(305, 880, self)
     self.chat = Chat(810, 125)
     self.kolor_rysowania = (0, 0, 0)
     self.rysujacy = False
Ejemplo n.º 26
0
async def exp_ranking(cmd, mu, sigma, beta, tau):
    t = time.time()
    async with cmd.typing():
        player_manager = PlayerManager()
        await player_manager.load_data()
        await kamlbot.update_mentions(player_manager=player_manager)
        kamlbot.experimental_ranking = Ranking(player_manager,
                                               mu=eval(mu),
                                               sigma=eval(sigma),
                                               beta=eval(beta),
                                               tau=eval(tau))

        await kamlbot.experimental_ranking.fetch_data(kamlbot.matchboard)

        dt = time.time() - t

        await cmd.channel.send(f"Experimental ranking initialized in {dt:.2f} s.")
Ejemplo n.º 27
0
    def list(self, request):
        try:
            date_from = request.GET.get('date_from', '2.1.1410')
            date_from = datetime.datetime.strptime(date_from, '%d.%m.%Y')
        except ValueError:
            date_from = datetime.date(1410, 8, 15)

        date_from -= datetime.timedelta(days=1)

        try:
            date_to = request.GET.get('date_to', '31.12.9999')
            date_to = datetime.datetime.strptime(date_to, '%d.%m.%Y')
        except ValueError:
            date_to = datetime.date(9999, 12, 31)

        # cmnt = Movie.objects.filter(
        #     Q(comment__date__range=(date_from, date_to)) |
        #     Q(comment__date__isnull=True)).values("id").annotate(
        #     total_comments=Count("comment")).order_by('-total_comments')

        # SQL STMT that can do all above and adds 0 for movies with no comments
        # but much easier
        sql_qry = \
            'SELECT "movies_movie"."id" AS "movie_id", ' \
            'SUM(CASE WHEN "movies_comment"."date" ' \
                'BETWEEN datetime("%s") AND datetime("%s") ' \
                'THEN 1 ELSE 0 end) as "total_comments" ' \
            'FROM "movies_movie" LEFT OUTER JOIN "movies_comment" ' \
            'ON ("movies_movie"."id" = "movies_comment"."movie_id_id") ' \
            'GROUP BY "movies_movie"."id" ' \
            'ORDER BY "total_comments" DESC' % (date_from, date_to)

        with connection.cursor() as c:
            c.execute(sql_qry)

            "Return all rows from a cursor as a dict"
            columns = [col[0] for col in c.description]
            cmnt = [dict(zip(columns, row)) for row in c.fetchall()]

        # add rank
        total_comments = [c['total_comments'] for c in cmnt]
        ranked_comments = list(Ranking(total_comments, strategy=DENSE))
        for i in range(len(cmnt)):
            cmnt[i]['rank'] = ranked_comments[i][0] + 1

        return Response(cmnt)
Ejemplo n.º 28
0
    def testMatchesPerUser(self):
        self.R.reset()
        self.R.c.executemany(queries.INSERT_KNOWN_USERS, USERS)
        self.R.c.executemany(queries.INSERT_RATINGS, RATINGS)

        # Use a fresh Ranking to load the information from DB
        R = Ranking(1, conn=self.R.conn)

        for dual in DUALS:
            R.add_dual_match((dual[0], dual[4]), (dual[1], dual[5]),
                             (dual[2], dual[6]), (dual[3], dual[7]), dual[8],
                             dual[9], dual[10])

        try:
            R.matches_per_user()
        except Exception:
            self.fail(
                "Calculating the number of matches per user should not throw error."
            )
Ejemplo n.º 29
0
    def ranking(self, obj, scoreing_class = None, validation_class = None,
                scoreing_args = None, validation_args = None, reverse = False):
        """
        Get a ranking for a Rankable object
        @param obj:              ranked object (Category, Course, ...)
        @param scoreing_class:   scoreing strategy used, None for default strategy
        @param validation_class: validation strategy used, None for default strategy
        @param scoreing_args:    scoreing args, None for default args
        @param validation_args:  validation args, None for default args
        @param reverse:          produce reversed ranking
        """

        if type(obj) == OpenRuns:
            scoreing_class = scoreing_class or ControlPunchtimeScoreing
            validation_class = validation_class or ControlPunchtimeScoreing
            validation_args = validation_args or scoreing_args
            reverse = True
            
        return Ranking(obj, self, scoreing_class, validation_class,
                       scoreing_args, validation_args, reverse)
Ejemplo n.º 30
0
def mainLoop():
    global config
    global ranking
    global chatIds
    config = util.readConfig()
    ranking = Ranking(config)
    chatIds = util.readChatIds()

    tg.readRequestUrl()
    callbacks = [(checkUpcomingContest, 60, 0), (tg.startPolling, 1, 0)]
    while True:
        for i in range(len(callbacks)):
            (fun, timeIt, lastTimeStamp) = callbacks[i]
            if time.time() - lastTimeStamp >= timeIt:
                callbacks[i] = (fun, timeIt, time.time())
                try:
                    fun()
                except Exception as e:
                    traceback.print_exc()
                    print(traceback.format_exc())
        time.sleep(0.01)