예제 #1
0
def create_trigger(factor_id):
    trigger_form = TriggerForm()
    trigger_form.controller.choices = [
        (c.id, c.controller_type)
        for c in session.query(DeviceController).all()
    ]
    plant = session.query(Plant).first()
    factor = session.query(PlantFactor).filter(
        PlantFactor.id == factor_id).one_or_none()
    if trigger_form.validate():
        trigger = PlantFactorTrigger(
            plant_id=plant.id,
            factor_id=factor.id,
            threshold=trigger_form.threshold.data,
            operator=trigger_form.operator.data,
            controller_id=trigger_form.controller.data,
            action_type=trigger_form.action_type.data)
        try:
            session.add(trigger)
            session.commit()
        except:
            session.rollback()
            raise
        return redirect('/')
    context = dict(plant=plant, trigger_form=trigger_form)
    return render_template('top.html', **context)
예제 #2
0
def translate(text, user):
    """ Takes a string and tries to find the correct translation direction
    between the two languages. If both give results, both are printed.
    It uses the translation engine specified in the users preferences.
    """
    print('starting')
    # TODO: move the translate functions to the translator classes/objects
    # somehow and select it from user settings
    lan1 = user.lan1.upper()
    lan2 = user.lan2.upper()  # 'DE', 'EN' ...
    trans1 = pydeepl.translate(text, lan1, lan2)
    trans2 = pydeepl.translate(text, lan2, lan1)
    # TODO: logic depends on user.direction
    user.count += 1
    session.add(user)
    session.commit()
    if user.direction == 1:
        return [trans1]
    elif user.direction == 2:
        return [trans2]
    else:  # auto
        if trans1.lower() == text.lower() and trans2.lower() != text.lower():
            return [trans2]
        if trans1.lower() != text.lower() and trans2.lower() == text.lower():
            return [trans1]
        else:
            return [trans1, trans2]
예제 #3
0
def top():
    session.commit()
    plant = session.query(Plant).first()
    trigger_form = TriggerForm()
    trigger_form.controller.choices = [
        (c.id, c.controller_type)
        for c in session.query(DeviceController).all()
    ]
    context = dict(plant=plant, trigger_form=trigger_form)
    return render_template('top.html', **context)
예제 #4
0
def delete_trigger(trigger_id):
    trigger = session.query(PlantFactorTrigger).filter(
        PlantFactorTrigger.id == trigger_id).one_or_none()
    if trigger:
        try:
            session.delete(trigger)
            session.commit()
        except:
            session.rollback()
            raise
    return redirect('/')
예제 #5
0
파일: init.py 프로젝트: farmy-maker/seed
def generate_fake_data(session):
    channels = session.query(DeviceChannel).all()
    for channel in channels:
        for i in range(30):
            recorded_at = datetime.now() - timedelta(minutes=random.randint(1, 60*24))
            c_data = ChannelData(channel_id=channel.id, value=random.randint(0, 700), recorded_at=recorded_at)
            session.add(c_data)

    plant = session.query(Plant).first()
    for i in range(20):
        plant_snap = PlantSnapshot(plant_id=plant.id,
                                   created_at=datetime(2018, 10, 16, random.randint(0, 23), random.choice([0, 30])))
        session.add(plant_snap)
    session.commit()
예제 #6
0
def create_user(update):
    """ Create a new user from a telegram update object and add it to the db.
    Returns object of the User model.
    """
    print('creating')
    user = User()
    user.chat_id = update.message.chat.id
    print('id set')
    user.name = update.message.chat.first_name
    print('name set')
    session.add(user)  # cashes data for db
    print('added')
    # Care if commit does not work no error is raised it just stops there
    session.commit()  # writes all cached data to file
    print('creating done')
    return user
예제 #7
0
async def process_2nd_language(message: types.Message, state: FSMContext):
    # Update state and data
    await Form.select.set()
    async with state.proxy() as data:
        data['learning'] = message.text
        await bot.send_message(
            message.chat.id,
            md.text(
                md.text('Native:', md.code(data['native'])),
                md.text('Learning:', data['learning']),
                sep='\n',
            ),
            reply_markup=select_keys,
            parse_mode=ParseMode.MARKDOWN,
        )
        users = session.query(User).filter(
            User.chat_id == message.chat.id).all()
        logging.info(f'checking if user {message.chat.id} in the system')
        if len(users) == 0:  # if no user exists create a new from update
            user = User()
            user.chat_id = message.chat.id
            user.name = message.chat.first_name
            user.lan1 = data['native']
            user.lan2 = data['learning']
            session.add(user)  # cashes data for db
            session.commit()  # writes all cached data to file
            logging.info(
                f'new user {user.chat_id} created {user.lan1} {user.lan2}')
        elif len(users) == 1:  # if a user is found return it
            user = users[0]
            user.lan1 = data['native']
            user.lan2 = data['learning']
            session.commit()  # writes all cached data to file
            logging.info(f'updated {user.chat_id}, {user.lan1} {user.lan2}')
        else:
            logging.error(f'found multiple users id: {message.chat.id}')
            await bot.send_message(
                message.chat.id,
                md.text("I'm sorry something went wrong with your user id."),
                reply_markup=None,
                parse_mode=ParseMode.MARKDOWN,
            )
예제 #8
0
파일: init.py 프로젝트: farmy-maker/seed
def init_all(session):
    # TODO: init from json or csv file
    plant = Plant(name=u"Plant")
    session.add(plant)
    device = Device(name="Raspberry Pi")
    session.add(device)
    session.commit()
    for factor in PlantGrowthFactor:
        channel = DeviceChannel(device_id=device.id)
        session.add(channel)
        session.commit()
        plant_factor = PlantFactor(plant_id=plant.id,
                                   factor_type=factor,
                                   channel_id=channel.id)
        session.add(plant_factor)
        session.commit()
    pump_controller = DeviceController(device_id=device.id, controller_type=PlantControllerType.PUMP)
    session.add(pump_controller)
    led_controller = DeviceController(device_id=device.id, controller_type=PlantControllerType.LED)
    session.add(led_controller)
    session.commit()
예제 #9
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 11 14:29:41 2017

@author: sarbot
"""

from models.base import Base
from models.user import User
from models.base import engine
from models.base import session

user = User()
user.name = 'Frank'
session.add(user)
session.commit()
예제 #10
0
async def continue_adding(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        w_native = ''
        w_learning = ''
        if data['direction'] == 1:
            dct = Dictionary(YANDEX_API,
                             from_lang=data['native'],
                             to_lang=data['learning'])
            from_lang = data['native']
            to_lang = data['learning']
            w_native = str(message.text).capitalize()
            result = dct.lookup(message.text)
        elif data['direction'] == 2:
            dct = Dictionary(YANDEX_API,
                             from_lang=data['learning'],
                             to_lang=data['native'])
            from_lang = data['learning']
            to_lang = data['native']
            w_learning = str(message.text).capitalize()
            result = dct.lookup(message.text, ui='en')
        else:
            logging.error("CHECK YOUR CODE")
            pass
        if not result.is_found:
            return await message.reply("not found")

        tr = result.get_tr('text', 'gen', 'pos')[0]

        if from_lang == 'DE':
            if result.gen == 'n':
                article = "das"
            elif result.gen == 'm':
                article = "der"
            else:
                article = "die"
            w_learning = f"{article} {result.text}"
        elif to_lang == 'DE':
            if tr['gen'] == 'n':
                article = "das"
            elif tr['gen'] == 'm':
                article = "der"
            else:
                article = "die"
            w_learning = f"{article} {tr['text']}"
        else:
            w_learning = tr['text']

        if data['direction'] == 2:
            w_native = str(tr['text']).capitalize()

        logging.info(f'checking if card {w_native} already exists')
        cards = session.query(Card).filter(Card.side1 == w_native).all()

        if len(cards) != 0:
            if to_lang == w_native:
                logging.debug(f'Exists! Reply native from Card')
                return await message.reply(cards[0].side1)
            else:
                logging.debug(f'Exists! Reply learning from Card')
                return await message.reply(cards[0].side2)

        logging.debug(f'adding new card')
        new_card = Card()
        new_card.user_id = data['user']
        new_card.lan1 = from_lang
        new_card.lan2 = to_lang
        new_card.side1 = w_native
        new_card.side2 = w_learning
        session.add(new_card)  # cashes data for db
        session.commit()  # writes all cached data to file
        logging.info(f'new card created {new_card.side1} {new_card.side2}')
        return await message.reply(f"{new_card.side1} - {new_card.side2}")