Beispiel #1
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]
Beispiel #2
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)
    def setresponse(self):
        try:
            requestParams ={
                'fields': {
                    "id": {
                        "type":"integer",
                        "required":True},
                    'action': {
                        "type":"string",
                        "required":True},
                    'response': {
                        "type":"string",
                        "required":True}
                },
                'message': {
                    'id': {
                        "type":"өгөгдлийн төрөл буруу байна",
                        "required":"Утга тодорхойгүй байна"},
                    'action': {
                        "type":"өгөгдлийн төрөл буруу байна",
                        "required":"Утга тодорхойгүй байна"},
                    'response': {
                        "type":"өгөгдлийн төрөл буруу байна",
                        "required":"Утга тодорхойгүй байна"}
                }
            }
            
            v = BuValidator(requestParams)            
            v.validate(request.json)
            ucount = session.query(Request)\
                        .filter(Request.id==request.json['id'])\
                        .filter(Request.status==Request.STATUS_PROCESSING)\
                        .update({
                            'status':Request.STATUS_FINISHED, #'response':request.json['response'],
                            'updated_at':datetime.datetime.now()
                        })
            
                
            if(ucount>0):
                if(request.json['action']=="searchbyname"):
                    res =json.loads(request.json['response'])
                    if('result' in res):
                        for x in res['result']:
                            c = session.query(Customer).filter_by(rnumber=x[3]).first()
                            if(c is None):
                                session.add(Customer(id=x[0],rnumber=x[3],lastname=x[1],firstname=x[2]))
                                session.flush()
            
            return json.dumps({
                'result':'success'
            },ensure_ascii=False).encode('utf8')

        except Exception as e:
            traceback.print_exc()
            msg =  e.args if len(e.args)>0 else str(e)            
            return json.dumps({
                'result':'error',
                'msg': msg
            },ensure_ascii=False).encode('utf8')
Beispiel #4
0
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()
Beispiel #5
0
    def create(self):
        try:
            createParams = {
                "fields" : {
                    "email": {
                        "type": "string", 
                        "required": True, 
                        "regex": '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
                    },
                    "password": {"type": "string","required": True,"minlength":4}
                },
                "message" : {
                    "email":{
                        "type": "тэмдэгт оруулна уу",
                        "required": "email тодорхойгүй байна",
                        "regex": "имэйлээ зөв оруулна уу"
                    },
                    "password":{
                        "type": "Нууц үг үсэг тоо байна",
                        "required": "Нууц үг тодорхойгүй байна",
                        "minlength": "Нууц үг 4 олон тэмдэгттэй байна"
                    }
                }
            }
            

            v = BuValidator(createParams)
            v.validate(request.json)
            code = '123456'
            password_hashed = bcrypt.hashpw(request.json['password'].encode("utf8"), bcrypt.gensalt())
            code_hashed = bcrypt.hashpw(code.encode("utf8"), bcrypt.gensalt())
            
            user = User(
                uuid=User.generateID(),
                email=request.json['email'],
                password = password_hashed,
                activation = code_hashed
            )            
            session.add(user)
            session.flush()
            return json.dumps({
                'result':'success' 
            })        
        except Exception as e:            
            msg =  e.args if len(e.args)>0 else str(e)
            return json.dumps({
                'result':'error',
                'msg': msg
            },ensure_ascii=False).encode('utf8')
Beispiel #6
0
    def crequest(self):

        try:
            requestParams = {
                'fields': {
                    'name': {
                        "type": "string",
                        "minlength": 2,
                        "required": True
                    }
                },
                'message': {
                    'name': {
                        "type": "Нэр буруу байна",
                        "minlength": "Нэр буруу байна",
                        "required": "Нэр тодорхойгүй байна"
                    },
                }
            }

            v = BuValidator(requestParams)
            dd = request.form.to_dict()
            del (dd['csrf_token'])
            v.validate(dd)

            req = json.dumps(
                {
                    "inputVal": request.form['name'],
                    "expression": "c.customername",
                    "id": "01",
                    "isCitizen": "true"
                },
                ensure_ascii=False).encode('utf8')

            cc = session.query(Request)\
                .filter(Request.action=="searchbyname")\
                .filter(Request.request==req)\
                .filter(Request.status.in_((0,1)))\
                .count()
            if (cc == 0):
                session.add(Request(action="searchbyname", request=req))
                session.flush()
            return redirect("/customer/index")

        except Exception as e:
            msg = e.args if len(e.args) > 0 else str(e)
            print(msg)
            return redirect("/customer/search")
    def import_schedule(self):
        rlist = []
        if('rnumbers_file' in request.files):
            f = request.files['rnumbers_file']            
            rlist = [x.decode('utf-8') for x in f.stream.readlines()]
            
        elif('rnumbers' in request.form):
            rlist = request.form['rnumbers'].splitlines()

        if(len(rlist)>0):
            #data = request.form['rnumbers'].splitlines()
            rnumbers = bu.remove_duplicate(rlist)            
            
            for rnumber in rnumbers:                
                rnumber = rnumber.strip()

                if(len(rnumber)==10):
                    #person
                    params = {
                        'id':'01',
                        'expression':'c.registerno',
                        'inputVal':rnumber,
                        'isCitizen': 'true'
                    } 
                elif(len(rnumber)==7):
                    #company
                    params = {
                        'id':'03',
                        'expression':'c.registerno',
                        'inputVal':rnumber
                    }
                else: continue

                filename = Info.generateFilename()
            
                info = Info(
                    user_uuid='ab6ea344-ccd9-4e87-8e85-2d457a52d77e',
                    rnumber=rnumber,
                    params = json.dumps(params, ensure_ascii=False),
                    filename = filename,
                    mode= Info.MODE_SCHEDULE,
                    status=Info.STATUS_PENDING
                )
                session.add(info)

            session.flush()
            return redirect("/home/index")
        return render_template("info/import_schedule.html")
Beispiel #8
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
Beispiel #9
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,
            )
Beispiel #10
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()
    def creates(self):
        try:
            requestParams = {
                'fields': {
                    'rnumbers': {
                        "type": "list",
                        "required": True
                    },
                    'mode': {
                        "type": "integer",
                        "allowed": [0, 1],
                        "required": True
                    }
                },
                'message': {
                    'rnumbers': {
                        "type": "өгөгдлийн төрөл буруу байна",
                        "required": "Регистрийн дугаар тодорхойгүй байна"
                    },
                    'mode': {
                        "type": "өгөгдлийн төрөл буруу байна",
                        "allowed": "Буруу утгатай байна",
                        "required": "Утга тодорхойгүй байна"
                    }
                }
            }
            v = BuValidator(requestParams)
            v.validate(request.json)
            for rnumber in request.json['rnumbers']:
                if (len(rnumber) == 10):
                    #person
                    params = {
                        'id': '01',
                        'expression': 'c.registerno',
                        'inputVal': rnumber,
                        'isCitizen': 'true'
                    }
                elif (len(rnumber) == 7):
                    #company
                    params = {
                        'id': '03',
                        'expression': 'c.registerno',
                        'inputVal': rnumber
                    }
                else:
                    continue

                filename = Info.generateFilename()

                info = Info(user_uuid=self.auth.uuid,
                            rnumber=rnumber,
                            params=json.dumps(params, ensure_ascii=False),
                            filename=filename,
                            mode=request.json['mode'],
                            status=Info.STATUS_PENDING)
                session.add(info)

            session.flush()
            return json.dumps({
                'result': 'success'
            }, ensure_ascii=False).encode('utf8')
        except Exception as e:
            msg = e.args if len(e.args) > 0 else str(e)
            traceback.print_exc()
            return json.dumps({
                'result': 'error',
                'msg': msg
            },
                              ensure_ascii=False).encode('utf8')
Beispiel #12
0
    def insert(cls, row):                
        ddrow = session.query(cls)\
            .filter_by(dd=row['d/d'],\
                registriindugaar=row['registriindugaar'],\
                zeeliinkhemzhee = row['zeeliinkhemzhee'],\
                zeelolgosonognoo = row['zeelolgosonognoo']\
            ).first()
        
        if(ddrow is None):                     
            new_row = Ddrows(
                downloaded_date=row['downloaded_date'],
                filename = row['filename'],                
                dd = row['d/d'],                
                registriindugaar = row['registriindugaar'],
                zeeliinkhemzhee = row['zeeliinkhemzhee'],
                zeelolgosonognoo = 	row['zeelolgosonognoo'],
                tologdokhognoo=row['tologdokhognoo'],
                valiutynner=row['valiutynner'],
                oriinuldegdel=row['oriinuldegdel'],
                kheviin=row['kheviin'],
                khugatsaakhetersen=row['khugatsaakhetersen'],
                kheviinbus=row['kheviinbus'],
                ergelzeetei=row['ergelzeetei'],
                muu=row['muu'],
                buleg=row['buleg'],
                dedbuleg=row['dedbuleg'],
                ukhekhbg_yndugaar=row['ukhekhbg-yndugaar'],
                ulsynburtgeliindugaar=row['ulsynburtgeliindugaar'],
                kartyndugaar=row['kartyndugaar'],
                tailbar=row['tailbar'],
                pred_tag=row['pred_tag'],
                payment_pred=row['payment_pred'],
                payment_pred_last=row['payment_pred_last'],
                rate_mean=row['rate_mean'],
                rate_pred=row['rate_pred'],
                month0=row['month0'],
                heviinbus_uldegdeltei=row['heviinbus_uldegdeltei'],
                heviinbus_uldegdelgui=row['heviinbus_uldegdelgui'],
                heviinbus_shugam=row['heviinbus_shugam'],

                loantypecode = row['loantypecode'],
                orgcode = row['orgcode'],
                statuscode = row['statuscode'],
                loanclasscode = row['loanclasscode']
            )
            
            session.add(new_row)
            session.flush()
        elif(ddrow.oriinuldegdel!=0 or ddrow.oriinuldegdel!=row['oriinuldegdel']):
            
            session.query(cls)\
                .filter_by(id=ddrow.id)\
                .update({
                    'downloaded_date':row['downloaded_date'],
                    'tologdokhognoo':row['tologdokhognoo'],
                    'valiutynner':row['valiutynner'],
                    'oriinuldegdel':row['oriinuldegdel'],
                    'kheviin':row['kheviin'],
                    'khugatsaakhetersen':row['khugatsaakhetersen'],
                    'kheviinbus':row['kheviinbus'],
                    'ergelzeetei':row['ergelzeetei'],
                    'muu':row['muu'],
                    'buleg':row['buleg'],
                    'dedbuleg':row['dedbuleg'],
                    'ukhekhbg_yndugaar':row['ukhekhbg-yndugaar'],
                    'ulsynburtgeliindugaar':row['ulsynburtgeliindugaar'],
                    'kartyndugaar':row['kartyndugaar'],
                    'tailbar':row['tailbar'],
                    'pred_tag':row['pred_tag'],
                    'payment_pred':row['payment_pred'],
                    'payment_pred_last':row['payment_pred_last'],
                    'rate_mean':row['rate_mean'],
                    'rate_pred':row['rate_pred'],
                    'month0':row['month0'],
                    'heviinbus_uldegdeltei':row['heviinbus_uldegdeltei'],
                    'heviinbus_uldegdelgui':row['heviinbus_uldegdelgui'],
                    'heviinbus_shugam':row['heviinbus_shugam'],

                    'loantypecode':row['loantypecode'],
                    'orgcode':row['orgcode'],
                    'statuscode':row['statuscode'],
                    'loanclasscode':row['loanclasscode']
                })
Beispiel #13
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}")
    if (len(rnumber) == 10):
        #person
        params = {
            'id': '01',
            'expression': 'c.registerno',
            'inputVal': rnumber,
            'isCitizen': 'true'
        }
    elif (len(rnumber) == 7):
        #company
        params = {
            'id': '03',
            'expression': 'c.registerno',
            'inputVal': rnumber
        }
    else:
        continue

    filename = Info.generateFilename()

    info = Info(user_uuid='ab6ea344-ccd9-4e87-8e85-2d457a52d77e',
                rnumber=rnumber,
                params=json.dumps(params, ensure_ascii=False),
                filename=filename,
                mode=mode,
                status=Info.STATUS_PENDING)
    session.add(info)
    i += 1
    if (i % 2 == 0): session.flush()

session.flush()
Beispiel #15
0
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()