コード例 #1
0
ファイル: app.py プロジェクト: ewilson/screentime
def hello_world():
    if request.method == 'GET':
        conn = data.create_connection()
        readers = data.select_all_readers(conn)
        return render_template('hello.html', readers=readers)
    elif request.method == 'POST':
        reader_id = request.form.get("reader")
        activity = request.form.get('activity')
        endpoint = request.form.get('endpoint')
        conn = data.create_connection()
        endpoint = data.EndpointTuple(reader_id, datetime.now().isoformat(), activity, endpoint)
        data.insert_endpoint(conn, endpoint)
        return redirect('/')
コード例 #2
0
def send_everyone(contestId):
    connection = data.create_connection(dbname)

    ids = data.execute_read_query(connection, ids_handler.select_all_ids())
    contestants, name = cf.get_contestants(contestId)
    if contestants is None:
        connection.close()
        return

    for x in ids:
        id = x[0]
        handles = data.execute_read_query(connection,
                                          ids_handler.select_cf_handles(id))

        maxLenNickname = 0
        for y in handles:
            handle = y[0]
            if contestants.get(handle) is None:
                continue
            maxLenNickname = max(maxLenNickname, len(handle))

        if maxLenNickname == 0:
            continue

        results = list()

        for y in handles:
            handle = y[0]
            if contestants.get(handle) is None:
                continue
            oldRating = contestants[handle][0]
            newRating = contestants[handle][1]
            delta = newRating - oldRating
            if delta < 0:
                delta = str(delta)
            else:
                delta = '+' + str(delta)

            results.append((handle, oldRating, newRating, delta))

        results.sort(reverse=True, key=lambda x: int(x[3]))

        header = '[{0}](https://codeforces.com/contest/{1}) был обновлен!\n\n'.format(
            name, contestId)
        message = ''

        for handle, oldRating, newRating, delta in results:
            message += handle
            message += ': '
            message += ' ' * (maxLenNickname - len(handle))
            message += '{0} -> {1} ({2})\n'.format(oldRating, newRating, delta)

        send_message(id,
                     message,
                     header=header,
                     mode='markdown',
                     web_page_preview=False,
                     all_monospace=True)

    connection.close()
コード例 #3
0
ファイル: commands.py プロジェクト: dsheshenya/cfrcw
def sync(message):
    id = message.chat.id
    if (message.chat.type == 'group'):
        send_message(
            id,
            'Эта команда не может быть выполнена в групповых чатах в целях безопасности ваших данных'
        )
    else:
        connection = data.create_connection(dbname)

        elems = data.execute_read_query(connection,
                                        keys_handler.select_keys(id))
        if elems == []:
            send_message(id, 'Вы не добавили api ключи. Посмотрите /help')
        else:
            open, secret = elems[0]
            handles, status = cf.get_friends(open, secret)

            if handles is None:
                if 'Incorrect API key' in status:
                    send_message(id, 'Вы указали неправильные ключи')
                else:
                    send_message(
                        id,
                        'Что-то пошло не так. Скорее всего, codeforces сейчас недоступен.'
                    )
                    logger.critical(status)
            else:
                send_message(
                    id,
                    util.__add_handles(id,
                                       list(map(lambda x: x.lower(), handles)),
                                       handles, connection))

        connection.close()
コード例 #4
0
ファイル: commands.py プロジェクト: dsheshenya/cfrcw
def cancel_button_handler(call):
    chatId = call.message.chat.id
    messageId = call.message.message_id
    try:
        if call.message and call.data == 'cancel':
            with data.create_connection(dbname) as connection:
                edit_message(chatId, messageId,
                             util._cancel(chatId, connection))
    except Exception as e:
        logger.error(str(e))
コード例 #5
0
def edit_message(chatId, messageId, message):
    try:
        Bot.edit_message_text(message, chatId, message_id=messageId)
        return True
    except Exception as e:
        e = str(e)
        if 'Forbidden: bot was kicked from the group chat' in e or \
                'Forbidden: bot was blocked by the user' in e:
            with data.create_connection(dbname) as connection:
                _clear(chatId, connection)
        elif not 'Bad Request: message is not modified' in e:
            logger.error('Unknown error: {0}'.format(e))
            return False
コード例 #6
0
ファイル: commands.py プロジェクト: dsheshenya/cfrcw
def remove_handles(message):
    id = message.chat.id
    connection = data.create_connection(dbname)

    args = message.text.split()[1:]
    if len(args) == 0:
        data.execute_query(connection, queue_handler.remove_id(id))
        data.execute_query(connection, queue_handler.insert_id(id, 1))
        send_message(id, 'Введите хэндлы', markup=util.create_keyboard())
    else:
        send_message(id, util._remove_handles(id, args, connection))

    connection.close()
コード例 #7
0
def check_changes():
    try:
        resp = requests.get(
            'https://codeforces.com/api/contest.list?gym=false').json()
    except Exception as e:
        logger.critical(str(e))
        return list()

    if resp['status'] == 'FAILED':
        logger.critical(resp['comment'])
        return list()

    res = list()
    connection = data.create_connection(dbname)

    i = 0
    while resp['result'][i]['relativeTimeSeconds'] < maxTime:
        id = resp['result'][i]['id']

        if resp['result'][i]['phase'] != 'FINISHED' or \
                data.execute_read_query(connection, contests_handler.select_id(id)) != []:
            i += 1
            continue

        try:
            resp2 = requests.get(
                'https://codeforces.com/api/contest.ratingChanges?contestId={0}'
                .format(id)).json()
        except Exception as e:
            logger.critical(str(e))
            i += 1
            continue

        logger.debug('i = {0}; id = {1};'.format(i, id))

        if resp2['status'] == 'OK' and resp2['result'] != []:
            res.append(id)
            data.execute_query(connection, contests_handler.insert_id(id))
        i += 1

    connection.close()
    logger.debug('found {0}'.format(res))

    return res
コード例 #8
0
def send_message(chatId, message, mode = None, markup = None, \
                 web_page_preview = True, all_monospace = False, header = None):
    try:
        if all_monospace:
            mode = 'markdown'

        splitted_text = split_string(message, 3000)

        for text in splitted_text:
            if all_monospace:
                text = '`' + text + '`'
            if header is not None:
                text = header + text
                header = None

            success = False
            while not success:
                try:
                    Bot.send_message(
                        chatId,
                        text,
                        parse_mode=mode,
                        reply_markup=markup,
                        disable_web_page_preview=not web_page_preview)
                    success = True
                except Exception as e:
                    se = str(e)
                    if 'Too Many Requests' in se:
                        time = int(se[se.find('retry_after') +
                                      len('retry_after') + 1:-4]) + 0.5
                        sleep(time)
                    else:
                        raise e
        return True
    except Exception as e:
        e = str(e)
        if 'Forbidden: bot was kicked from the group chat' in e or \
                'Forbidden: bot was blocked by the user' in e:
            with data.create_connection(dbname) as connection:
                _clear(chatId, connection)
        else:
            logger.error('Unknown error: {0}'.format(e))
            return False
コード例 #9
0
ファイル: test_cards.py プロジェクト: kunxin-chor/gm-cardpads
def test_add_card():
    response = app.test_client().post('/add-card',
                                      json={
                                          'title': 'Hello world',
                                          'content':
                                          'This is a good day to live',
                                          'tags': 'a,b,c'
                                      })
    assert response.status_code == 200

    response_data = response.get_json()

    # test the db
    with data.create_connection() as conn:
        found = conn['cardpad_test']['cards'].find_one(
            {'_id': ObjectId(response_data['new_card_id']['$oid'])})
        assert found != None
        assert found['title'] == 'Hello world'
        assert found['content'] == 'This is a good day to live'
        assert found['tags'] == 'a,b,c'
コード例 #10
0
ファイル: commands.py プロジェクト: dsheshenya/cfrcw
def add_keys(message):
    id = message.chat.id
    if (message.chat.type == 'group'):
        send_message(
            id,
            'Эта команда не может быть выполнена в групповых чатах в целях безопасности ваших данных'
        )
    else:
        connection = data.create_connection(dbname)
        args = message.text.split()[1:]

        if len(args) == 2:
            send_message(id, util._add_keys(id, args, connection))
        elif len(args) == 0:
            send_message(id,
                         'Введите ключи (открытый и закрытый, через пробел)',
                         markup=util.create_keyboard())
            data.execute_query(connection, queue_handler.insert_id(id, 2))
        else:
            send_message(id, 'Неверные аргументы. Посмотрите /help')

        connection.close()
コード例 #11
0
ファイル: commands.py プロジェクト: dsheshenya/cfrcw
def text_handler(message):
    id = message.chat.id
    connection = data.create_connection(dbname)

    resp = data.execute_read_query(connection, queue_handler.select_type(id))
    if resp == []:
        connection.close()
        return

    data.execute_query(connection, queue_handler.remove_id(id))
    args = message.text.split()
    if resp[0][0] == 0:
        message = util._add_handles(id, args, connection)
    elif resp[0][0] == 1:
        message = util._remove_handles(id, args, connection)
    else:
        if len(args) == 2:
            message = util._add_keys(id, args, connection)
        else:
            message = 'Неверные аргументы. Посмотрите /help'
    send_message(id, message)

    connection.close()
コード例 #12
0
import matplotlib.pyplot as plt
from data import create_connection, select_all, get_table_name

label = ['a', 'b', 'c', 'd']
x_vertical = [900, 1800, 4000, 4110]
color = ['r', 'y', 'b', 'g']

if __name__ == '__main__':
    conn = create_connection("sqlite.db")
    TABLE_NAME = get_table_name()
    zoomdata = select_all(conn, TABLE_NAME)
    x_time = []
    y_count = []
    for pair in zoomdata:
        x_time.append(pair[0])
        y_count.append(pair[1])

    #remove obvious outliers
    for x in range(1, len(x_time)):
        if abs(y_count[x] - y_count[x - 1]) > 100:
            y_count[x] = y_count[x - 1]

    plt.figure(dpi=200)
    plt.plot(x_time, y_count)
    for x in range(len(label)):
        plt.axvline(x=x_vertical[x], color=color[x], label=label[x])
    plt.legend()
    plt.show()
コード例 #13
0
ファイル: commands.py プロジェクト: dsheshenya/cfrcw
def get_ratings(message):
    id = message.chat.id
    with data.create_connection(dbname) as connection:
        send_message(id, util._get_ratings(id, connection), all_monospace=True)
コード例 #14
0
ファイル: commands.py プロジェクト: dsheshenya/cfrcw
def list_handles(message):
    id = message.chat.id
    with data.create_connection(dbname) as connection:
        send_message(id, util._list(id, connection), all_monospace=True)
    connection.close()
コード例 #15
0
ファイル: commands.py プロジェクト: dsheshenya/cfrcw
def remove_id(message):
    id = message.chat.id
    with data.create_connection(dbname) as connection:
        send_message(id, util._clear(id, connection))
コード例 #16
0
ファイル: test_cards.py プロジェクト: kunxin-chor/gm-cardpads
def setup_function():
    data.DATABASE_NAME = "cardpad_test"
    with data.create_connection() as conn:
        conn[data.DATABASE_NAME]['cards'].delete_many({})