コード例 #1
0
ファイル: manage.py プロジェクト: warownia1/pokemoncord
def create_tables():
    database.connect()
    try:
        database.create_tables([Pokemon])
        database.commit()
    finally:
        database.close()
コード例 #2
0
ファイル: test_views.py プロジェクト: SirBigG/url_shortener
 def tearDown(self) -> None:
     # Close connection after test
     database.close()
     # Back to old database
     database.init(DB_NAME)
     # Remove test db file
     os.remove(TEST_DB_NAME)
コード例 #3
0
def start_training(message):
    """Command: start training - starts a one hour training."""
    if message.author.id in stop_training_events:
        yield from client.send_message(message.channel,
                                       "You are already training.")
        return
    stop_event = asyncio.Event()
    stop_training_events[message.author.id] = stop_event
    start_time = client.loop.time() - 5
    handler = client.loop.call_later(3600, stop_event.set)
    yield from client.send_message(message.channel, "Training started.")
    yield from stop_event.wait()
    handler.cancel()
    del stop_training_events[message.author.id]
    delta_time = (client.loop.time() - start_time) // 60
    database.connect()
    try:
        team = (Pokemon.select().where((Pokemon.owner_id == message.author.id)
                                       & (Pokemon.storage == TEAM)))
        for pkmn in team:
            pkmn.add_exp(delta_time)
            pkmn.save()
        database.commit()
    finally:
        database.close()
    ensure_future(
        client.send_message(
            message.author,
            "Training finished. You trained for %u minutes." % delta_time))
コード例 #4
0
ファイル: manage.py プロジェクト: warownia1/pokemoncord
def drop_tables():
    database.connect()
    try:
        database.drop_tables([Pokemon])
        database.commit()
    finally:
        database.close()
コード例 #5
0
ファイル: who_from.py プロジェクト: rouge8/gv_analysis
def interactive(classifier):
    try:
        while True:
            print "CLASSIFY YOUR MESSAGE:"
            text = raw_input("enter a text: ")
            print "result:", classifier.classify(tokenize(text))
            print
    except KeyboardInterrupt:
        database.close()
コード例 #6
0
def list_pokemon_team(message):
    """Command: team - list the pokemons in user's team."""
    database.connect()
    text = 'Your team:\n' + '\n'.join(
        " - **{0.name}** lv. {0.level}".format(pkmn) for pkmn in
        (Pokemon.select().where((Pokemon.owner_id == message.author.id)
                                & (Pokemon.storage == TEAM))))
    database.close()
    yield from client.send_message(message.channel, text)
コード例 #7
0
def main():
    try:
        database.connect()
        user_data_sync_service = UserDataSyncService()
        user_data_sync_service.sync()
    except:
        print("Unexpected error: ", sys.exc_info()[0])
    finally:
        database.close()
コード例 #8
0
ファイル: who_from.py プロジェクト: pombredanne/gv_analysis
def interactive(classifier):
    try:
        while True:
            print 'CLASSIFY YOUR MESSAGE:'
            text = raw_input('enter a text: ')
            print 'result:', classifier.classify(tokenize(text))
            print
    except KeyboardInterrupt:
        database.close()
コード例 #9
0
def start_trade(message):
    seller = message.author
    buyer = message.mentions[0]
    channel = message.channel

    tokens = message.content.split()
    pkmn_name = ' '.join(tokens[3:])
    database.connect()
    try:
        seller_pkmn = Pokemon.get(Pokemon.owner_id == seller.id,
                                  Pokemon.name == pkmn_name)
    except Pokemon.DoesNotExist:
        return
    finally:
        database.close()

    # pokemon exists, send invitation to trade
    text = ("{}, {} invites you to trade and offers {}.\n"
            "Enter 'pkmn offer {} <pokemon>' to trade.".format(
                buyer.mention, seller.name, pkmn_name, seller.mention))
    yield from client.send_message(channel, text)

    # wait for buyer to accept trade
    def check(message):
        return message.content.startswith('pkmn offer {}'.format(
            seller.mention))

    response = yield from client.wait_for_message(300,
                                                  channel=channel,
                                                  author=buyer,
                                                  check=check)
    if not response:
        yield from client.send_message(channel, 'Trade cancelled.')
        return
    tokens = response.content.split()
    pkmn_name = ' '.join(tokens[3:])
    database.connect()
    try:
        buyer_pkmn = Pokemon.get(Pokemon.owner_id == buyer.id,
                                 Pokemon.name == pkmn_name)
        buyer_pkmn.owner_id = seller.id
        seller_pkmn.owner_id = buyer.id
        buyer_pkmn.storage = seller_pkmn.storage = BOX
        buyer_pkmn.save()
        seller_pkmn.save()
        database.commit()
    except Pokemon.DoesNotExist:
        return
    except:
        database.rollback()
        raise
    finally:
        database.close()

    yield from client.send_message(channel, 'Trade completed.')
コード例 #10
0
def drop_tables():
    database.connect()

    # Initialize db by deleting all tables
    Item.drop_table(fail_silently=True)
    User.drop_table(fail_silently=True)
    Address.drop_table(fail_silently=True)
    Order.drop_table(fail_silently=True)
    OrderItem.drop_table(fail_silently=True)
    Picture.drop_table(fail_silently=True)

    database.close()
コード例 #11
0
def create_tables():
    database.connect()

    # Create new table with the same name
    Item.create_table()
    User.create_table()
    Address.create_table()
    Order.create_table()
    OrderItem.create_table()
    Picture.create_table()

    database.close()
コード例 #12
0
def create_superuser(email, password):
    database.connect()

    User.create(
        uuid=uuid.uuid4(),
        first_name='',
        last_name='',
        email=email,
        password=(crypt_password(password)),
        superuser=True,
    )

    database.close()
コード例 #13
0
def test_db():
    conn = database.connect()
    user = Users(create_date=datetime.now(),
                 email="*****@*****.**",
                 first_name="Serkan",
                 surname="Dağlıoğlu",
                 password="******",
                 follower_count=0,
                 following_count=0,
                 username="******")
    user.save()
    database.close()
    return 'Hello World!'
コード例 #14
0
def create_tables():
    database.connect()
    database.create_tables([Goods, Admins, Orders_Info, Orders_Content],
                           safe=True)
    Goods.create(name='.BASE_CAT', amount=0)
    Goods.create(name='Браслеты', amount=100, parent_id=1)
    Goods.create(name='Значки', amount=75, parent_id=1)
    Goods.create(name='Кружки', amount=150, price=100, parent_id=1)
    Goods.create(name='Синие', amount=50, price=10, parent_id=2)
    Goods.create(name='Красные', amount=36, price=15, parent_id=2)
    Goods.create(name='Желтые', amount=14, price=20, parent_id=2)
    Goods.create(name='Жестяные', amount=30, price=17, parent_id=3)
    Goods.create(name='Деревянные', amount=45, price=13, parent_id=3)
    Admins.create(chat_id='1234')
    database.close()
コード例 #15
0
def deposit_pkmn_handler(message):
    tokens = message.content.split()
    pkmn_name = ' '.join(tokens[2:])
    database.connect()
    try:
        pkmn = (
            Pokemon.select().where((Pokemon.storage == TEAM)
                                   & (Pokemon.owner_id == message.author.id)
                                   & (Pokemon.name == pkmn_name)).first())
        pkmn.storage = BOX
        pkmn.save()
    finally:
        database.commit()
        database.close()
    yield from client.send_message(message.channel,
                                   '{} sent to box'.format(pkmn.name))
コード例 #16
0
def show_pokemon(message):
    """Command: show [index] - show the pokemon from your team.

    Displays information about the pokemon in the current channel.
    The pokemon is selected fron your team at the specified index,
    if index is not given, show the first pokemon.
    """
    num = int(message.content[10:] or 1)
    database.connect()
    pkmn = (Pokemon.select().where((Pokemon.owner_id == message.author.id) & (
        Pokemon.storage == TEAM)).offset(num - 1).limit(1).first())
    database.close()
    if pkmn is None:
        return
    em = discord.Embed(title='{} lv. {}'.format(pkmn.name, pkmn.level),
                       colour=0xC00000)
    em.set_image(url=pkmn.get_img_url())
    yield from client.send_message(message.channel, embed=em)
コード例 #17
0
def add_caught_pokemon(user, pkmn, channel):
    """Add caught pokemon to the user's storage.

    Adds the pokemon to the storage and sends a notification about caught
    pokemon to the channel.
    """
    text = ('Congratulations! {} caught {}.'.format(user.mention, pkmn.name))
    pkmn.owner_id = user.id
    database.connect()
    count = (Pokemon.select().where((Pokemon.owner_id == user.id)
                                    & (Pokemon.storage == 1)).count())
    if count < TEAM_SIZE:
        pkmn.storage = TEAM
    else:
        pkmn.storage = BOX
        text += '\nPokemon was added to your box.'
    pkmn.save()
    database.commit()
    database.close()
    ensure_future(client.send_message(channel, text))
コード例 #18
0
def withdraw_pokemon(message):
    database.connect()
    num = (Pokemon.select().where((Pokemon.storage == TEAM) & (
        Pokemon.owner_id == message.author.id)).count())
    if num >= TEAM_SIZE:
        database.close()
        yield from client.send_message(message.channel, 'Your team is full.')
        return
    try:
        tokens = message.content.split()
        pkmn_name = ' '.join(tokens[2:])
        pkmn = (
            Pokemon.select().where((Pokemon.storage == BOX)
                                   & (Pokemon.owner_id == message.author.id)
                                   & (Pokemon.name == pkmn_name)).first())
        pkmn.storage = TEAM
        pkmn.save()
    finally:
        database.commit()
        database.close()
    yield from client.send_message(message.channel,
                                   '{} withdrawn.'.format(pkmn.name))
コード例 #19
0
ファイル: who_from.py プロジェクト: rouge8/gv_analysis
def interactive(classifier):
    try:
        while True:
            print "CLASSIFY YOUR MESSAGE:"
            text = raw_input("enter a text: ")
            print "result:", classifier.classify(tokenize(text))
            print
    except KeyboardInterrupt:
        database.close()


if __name__ == "__main__":
    database.connect()
    train, test = split_me_not_me(0.9)

    print "ME AND NOT ME:"
    run_naive_bayes(train, test)

    threshold = 200
    print
    print "PEOPLE WITH OVER %d TEXTS:" % threshold
    run_naive_bayes(*people_with_many_texts(threshold))
    print

    # train, test = split_me_not_me(1.0)
    # train, test = people_with_many_texts(threshold)
    # classifier = build_classifier(train)
    # interactive(classifier)

    database.close()
コード例 #20
0
ファイル: test_db_creator.py プロジェクト: ckier/shipdb
 def inner_clean_up():
     database.close()
     utilities.recursively_delete_directory(self._tempdir)
コード例 #21
0
ファイル: app.py プロジェクト: ofirpe/projSystem
def _db_close(_):
    if not database.is_closed():
        database.close()
コード例 #22
0
ファイル: who_from.py プロジェクト: pombredanne/gv_analysis
def interactive(classifier):
    try:
        while True:
            print 'CLASSIFY YOUR MESSAGE:'
            text = raw_input('enter a text: ')
            print 'result:', classifier.classify(tokenize(text))
            print
    except KeyboardInterrupt:
        database.close()


if __name__ == '__main__':
    database.connect()
    train, test = split_me_not_me(0.9)

    print 'ME AND NOT ME:'
    run_naive_bayes(train, test)

    threshold = 200
    print
    print 'PEOPLE WITH OVER %d TEXTS:' % threshold
    run_naive_bayes(*people_with_many_texts(threshold))
    print

    # train, test = split_me_not_me(1.0)
    # train, test = people_with_many_texts(threshold)
    # classifier = build_classifier(train)
    # interactive(classifier)

    database.close()
コード例 #23
0
ファイル: app.py プロジェクト: gonzabaldi/Acme_gonzalo
def close_db(resp):
    database.close()
    return resp
コード例 #24
0
ファイル: app.py プロジェクト: gonzabaldi/Acme_gonzalo
def close_db_on_err(err):
    database.close()
コード例 #25
0
ファイル: app.py プロジェクト: NKNaaS/HaikU-Server
def close_db_connection():
    database.close()
コード例 #26
0
def _db_close(_):
    if not database.is_closed():
        print("[DEBUG] close() called")
        database.close()
コード例 #27
0
ファイル: helpers.py プロジェクト: h3dw4rd0/adnow
 def on_finish(self):
     if not database.is_closed():
         database.close()
     return super().on_finish()
コード例 #28
0
ファイル: test_data_extractor.py プロジェクト: ckier/shipdb
 def teardown_method(self, method):
     database.close()
     self._output_manager.stop()
     self._data_extractor.stop()
     self._db_creator.stop()
     utilities.recursively_delete_directory(self._tempdir)
コード例 #29
0
def database_disconnect(response):
    if not database.is_closed():
        database.close()
    return response
コード例 #30
0
ファイル: app.py プロジェクト: nadav-pesach/riddle-me-this
def after_request(response):
    database.close()
    return response