Example #1
0
def show_contest(contestId, chat_id, admin):
    try:
        contest = backend.get_contest_information(contestId)
        if not 'activity' in contest:
            activity = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
            backend.update_contest(contest['id'], {'activity': activity})
        else:
            activity = contest['activity']
        contestInformation = "<b>" + contest['name'] + ":</b>\n\n"
        for num in range(3):
            contestInformation += 'Div. ' + str((num + 1)) + ':\n'
            for (index, color) in enumerate(const.activity):
                contestInformation += str(color[0]) + ': ' + str(activity[num][index]) + '\n'
            contestInformation += '\n'

        rating = contest['allActivity']
        if admin:
            key = InlineKeyboardMarkup()
            but_1 = InlineKeyboardButton(text="Изменить активность",
                                         callback_data="choose_div " + str(contestId) + ' ' + str(chat_id))
            key.add(but_1)
            bot.send_message(chat_id, contestInformation + 'Активность за контест:\n\n<pre>' + rating + '</pre>', parse_mode="html", reply_markup=key)
        else:
            bot.send_message(chat_id, contestInformation + 'Активность за контест:\n\n<pre>' + rating + '</pre>',
                             parse_mode="html")
    except Exception as err:
        print('Не удалось показать информацию о контесте', err)
        bot.send_message(chat_id, 'Не удалось показать информацию о контесте')
Example #2
0
def get_first_three_place(contestId):
    try:
        contestInfomation = backend.get_contest_information(contestId)
        cnt = 0
        firstPlaces = []
        for user in contestInfomation['users']:
            if contestInfomation['users'][user]['rank'] != 0:
                firstPlaces.append([user, contestInfomation['users'][user]['solvedCount']])
                cnt += 1
            if cnt == 3:
                break
        backend.update_contest(contestId, {'contestTop': firstPlaces})
    except:
        print('Не удалось взять топ 3')
Example #3
0
def change_activity(mes, chat_id, args):
    try:
        activity = [0, 0, 0, 0, 0]
        mes += ' '
        pos = 1
        while mes.find(' ') != -1:
            s = mes[0 : mes.find(' ')]
            activity[pos] = int(s)
            pos += 1
            mes = mes[mes.find(' ') + 1: len(mes)]
        new_activity = backend.get_contest_information(args['contest_id'])['activity']
        new_activity[int(args['div']) - 1] = activity
        backend.update_contest(args['contest_id'], {'activity': new_activity})
        show_contest(args['contest_id'], chat_id, True)
    except Exception as err:
        print('Не удалось поменять активность', err)
        bot.send_message(chat_id, 'Не удалось поменять активность')
Example #4
0
def get_contest_information(contestId):
    try:
        contestId = str(contestId)
        contest = backend.get_contest_information(contestId)
        standings = req.get_codeforces_contest_stadings(contestId, contest['apis'][0], contest['apis'][1], True)
        contestInformation = {}
        contestInformation['name'] = req.get_contestName(contestId, contest['apis'][0], contest['apis'][1])

        users = {}
        maxSolved = 1
        problemCount = len(standings['result']['problems'])
        contestInformation['problemCount'] = problemCount

        for user in standings['result']['rows']:
            userName = user['party']['members'][0]['handle']
            userName = get_username(userName)
            if not is_participant(userName):
                continue
            user_id = backend.get_users({'handle': userName})[0]['user_id']
            user_inf = backend.get_user(user_id)
            if not (user_inf['is_participant']):
                continue
            if not (user_id in users):
                users[user_id] = {}
                users[user_id]['rank'] = user['rank']
                users[user_id]['solved'] = [False for i in range(problemCount)]
                users[user_id]['upsolved'] = [False for i in range(problemCount)]

        for user in standings['result']['rows']:
            userName = user['party']['members'][0]['handle']
            if userName.find('=') == -1:
                continue
            userName = get_username(userName)
            if not is_participant(userName):
                continue
            user_id = backend.get_users({'handle': userName})[0]['user_id']
            user_inf = backend.get_user(user_id)
            if not (user_inf['is_participant']):
                continue

            if user['rank'] != 0:
                users[user_id]['rank'] = user['rank']

            for index, problem in enumerate(user['problemResults']):
                if user['rank'] != 0:
                    if problem['points'] == 1:
                        users[user_id]['solved'][index] = True
                else:
                    if problem['points'] == 1:
                        users[user_id]['upsolved'][index] = True

        official = 0
        used = [0] * 200
        for user in users:
            user_inf = users[user]
            if user_inf['rank'] != 0:
                official += 1
                used[int(user_inf['rank'])] = user
            users[user]['solvedCount'], users[user]['upsolvedCount'] = get_solved_count(users[user]['solved'],
                                                                                        users[user]['upsolved'])
            maxSolved = max(maxSolved, users[user]['solvedCount'])

        top = 1
        for i in range(0, len(users)):
            if used[i] != 0:
                users[used[i]]['rank'] = top
                top += 1

        for user in backend.get_users({'is_participant': True}):
            user_id = user['user_id']
            if not (user_id in users):
                users[user_id] = {}
                users[user_id]['rank'] = 0
                users[user_id]['solvedCount'] = 0
                users[user_id]['upsolvedCount'] = 0
                users[user_id]['solved'] = [False for i in range(problemCount)]
                users[user_id]['upsolved'] = [False for i in range(problemCount)]

        for user in users:
            contest_activity = contest['activity']
            user_inf = backend.get_user(int(user))
            user_div = int(user_inf['division'])
            user_activity = -1
            for kol in contest_activity[user_div - 1]:
                if kol <= users[user]['solvedCount'] + users[user]['upsolvedCount']:
                    user_activity += 1
                users[user]['user_activity'] = user_activity

        contestInformation['users'] = users

        status = req.get_codeforces_contest_status(contestId, contest['apis'][0], contest['apis'][1])
        try:
            for submission in range(len(status['result']) - 1, -1, -1):
                name = get_username(status['result'][submission]['author']['members'][0]['handle'])
                if not is_participant(name):
                    continue
                user_id = backend.get_users({'handle': name})[0]['user_id']
                user_inf = backend.get_user(user_id)
                if not (user_inf['is_participant']):
                    continue
                if status['result'][submission]['verdict'] == 'OK':
                    contestInformation['firstSubmission'] = {}
                    contestInformation['firstSubmission']['name'] = backend.get_users({'handle': name})[0]['user_id']
                    contestInformation['firstSubmission']['time'] = status['result'][submission][
                                                                        'relativeTimeSeconds'] // 60
                    break
        except Exception as err:
            print("Trouble with status", err)
        backend.update_contest(contestId, contestInformation)
    except Exception as err:
        print("Failed Contest Information", err)
Example #5
0
def get_sortedRating(contestId):
    try:
        contest_information = backend.get_contest_information(contestId)
        sortedRating = []
        for user in contest_information['users']:
            sortedRating.append(
                [contest_information['users'][user]['solvedCount'], contest_information['users'][user]['upsolvedCount'],
                 user]
            )

        def compare(x, y):
            if x[0] + x[1] > y[0] + y[1] or x[0] + x[1] == y[0] + y[1] and x[0] > y[0]:
                return -1
            elif x[0] + x[1] < y[0] + y[1] or x[0] + x[1] == y[0] + y[1] and x[0] < y[0]:
                return 1
            else:
                return 0

        sortedRating = sorted(sortedRating, key=cmp_to_key(compare))
        backend.update_contest(contestId, {'sortedRating': sortedRating})
        rating = table.Texttable()
        rating.set_deco(table.Texttable.HEADER)
        rating.set_cols_align(["l", "c", "r"])
        rating.set_cols_valign(["t", "t", "t"])
        rating.set_cols_dtype(['t', 't', 't'])
        rating.add_row(["Фамилия\n", "🏆\n", "Задачи"])
        space = '  '
        for index, item in enumerate(sortedRating):
            userName = backend.get_user(item[2])['name']
            name = userName[userName.find(' ') + 1:]
            if index == 9:
                space = ' '
            rating.add_row([str(index + 1) + space +
                            str(name),
                            str(contest_information['users'][item[2]]['solvedCount'] +
                                contest_information['users'][item[2]]['upsolvedCount']),
                            str(contest_information['users'][item[2]]['solvedCount']) + "/" + str(
                                contest_information['users'][item[2]]['upsolvedCount'])
                            ])
        backend.update_contest(contestId, {'allRating': rating.draw()})
        activity = table.Texttable()
        activity.set_deco(table.Texttable.HEADER)
        activity.set_cols_align(["l", "c", "c"])
        activity.set_cols_valign(["t", "t", "t"])
        activity.set_cols_dtype(['t', 't', 't'])
        activity.add_row(["Фамилия\n", "Div.\n", "Активность\n"])
        space = '  '
        for index, user in enumerate(sortedRating):
            user_inf = backend.get_user(user[2])
            user_div = int(user_inf['division'])
            userName = user_inf['name']
            name = userName[userName.find(' ') + 1:]
            user_activity = -1
            for kol in contest_information['activity'][user_div - 1]:
                if kol <= contest_information['users'][user[2]]['solvedCount'] + \
                        contest_information['users'][user[2]]['upsolvedCount']:
                    user_activity += 1
            backend.update_contest(contestId, {'users.' + user[2] + '.user_activity': user_activity})
            if index == 9:
                space = ' '
            activity.add_row([str(index + 1) + space + str(name),
                              str(user_div),
                              const.activity[user_activity][0]])
        backend.update_contest(contestId, {'allActivity': activity.draw()})
    except Exception as err:
        print('Ошибка при получении отсортированного рейтинга за контест', err)
Example #6
0
def get_hq_contests():
    try:
        for ind in range(3):
            hq_contest = req.get_codeforces_contest_list(const.apiKey[ind], const.apiSecret[ind], True)
            for contest in hq_contest['result']:
                if contest['name'].find("Тренировка H2Q №") != -1 and const.authors.count(contest['preparedBy']) != 0:
                    finished = False
                    if contest['phase'] == 'FINISHED':
                        finished = True
                    backend.update_contest(str(contest['id']),
                                           {
                                               'name': contest['name'],
                                               'apis': [const.apiKey[ind], const.apiSecret[ind]],
                                               'finished': finished
                                           })
                    contest_inf = backend.get_contest_information(contest['id'])
                    if not 'activity' in contest_inf:
                        activity = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
                        backend.update_contest(contest['id'], {'activity': activity})
                    if not 'good_luck' in contest_inf or finished:
                        backend.update_contest(str(contest['id']), {'good_luck': finished})
                    if not 'reminder' in contest_inf or finished:
                        backend.update_contest(str(contest['id']), {'reminder': finished})
                    if contest['relativeTimeSeconds'] >= -600 and contest['phase'] == 'BEFORE' and not (
                            contest_inf['good_luck']):
                        backend.update_contest(str(contest['id']), {'good_luck': True})
                        good_luck()
                    if contest['relativeTimeSeconds'] >= -61200 and contest['phase'] == 'BEFORE' and not (
                            contest_inf['reminder']):
                        backend.update_contest(str(contest['id']), {'reminder': True})
                        reminder()
    except:
        print('CF UPAL')