def nouns(): file = open("nouns.txt", "r") word_count = 0 for line in file: if Word.query.filter_by(word=line.rstrip()).count() == 0: dbWord = Word(word=line.rstrip()) dbWord.save() word_count += 1 file = open("actions.txt", "r") action_count = 0 for line in file: if Action.query.filter_by(action=line.rstrip()).count() == 0: dbAction = Action(action=line.rstrip()) dbAction.save() action_count += 1 file = open("categories.txt", "r") category_count = 0 for line in file: if Category.query.filter_by(name=line.rstrip()).count() == 0: dbCategory = Category(name=line.rstrip()) dbCategory.save() category_count += 1 return jsonify({ "Words Added": word_count, "Actions Added": action_count, "Categories Added": category_count })
def create_action(): token = str(request.json.get('token', '')) action = str(request.json.get('action', '')) user = User.query.filter_by(token=token) if user.count() > 0: if Action.query.filter_by(action=action).count() == 0: action = Action(action=action) action.save() obj = { 'id': action.id, 'action': action.action, } new_user_action = user_actions.insert().values( user_id=user[0].id, action_id=action.id) db.session.execute(new_user_action) db.session.commit() response = jsonify(obj) response.status_code = 201 return response else: abort( make_response( jsonify(message="You already have that action!"), 404)) else: abort(make_response(jsonify(message="Invalid user token."), 404))
def new(request, deposit_id): try: errors = [] d = Deposit.objects.get(pk=deposit_id) if d.is_archive: raise Exception dt = d.depositType.title querySet = Bill.objects.filter(client=request.user, currency=d.currency, is_private=True) F = ContractForm if request.method == 'POST': form = F(request.POST) form.fields["bill"].queryset = querySet if form.is_valid(): contract = form.save(commit=False) good = True if contract.start_amount < d.min_amount: errors.append('Сумма должна быть не меньше ' + str(d.min_amount) + " " + str(d.currency)) good = False elif not contract.bill.pop(contract.start_amount): errors.append('На счету (' + str(contract.bill.value_in_currency()) + ') недостаточно средств. ') good = False if good: bill = request.user.add_bill(d.currency, contract.start_amount, False) contract.deposit_bill = bill contract.deposit = d contract.calculate_end_date() contract.save() Action.add( action='Создание', contract=contract, money=contract.start_amount ) return redirect('contract:list') else: form = F() form.fields["bill"].queryset = querySet return render(request, 'contract/new.html', { 'ID': deposit_id, 'form': form, 'deposit': d, 'errors': errors }) except: return HttpResponse(status=404)
def keywords_parser(msg): """ 处理关键字命中规则 :param msg: 解析后的消息字典(用户) :return msg: kw业务处理后的消息字典(返回) """ # 获取数据,方便使用 phone = msg['Content'] query_id = msg['FromUserName'] # 查询query query = Query.filter_by_id(query_id) if query: # query存在,优先处理query if query.action == 'diss_call': # 开始diss_call骚扰,先使用DissCall验证输入的号码 phone_num = DissCall.check_phone(phone) if phone_num: # 电话验证通过, 提交骚扰 if DissCall.start_call(phone_num): # 提交成功 expire = query.expire - int(time.time()) msg['Content'] = '成功腹黑%s一次,已将其加入DISS骚扰队列。你可在%s秒内继续添加骚扰号码。' % ( phone, expire) return msg else: # 提交失败 msg['Content'] = '腹黑%s失败,请稍后重试!' % phone return msg else: # 电话验证不通过 msg['Content'] = '请输入合法的电话号码:' return msg elif msg['Content'] in diss_call_keywords: # query不存在,但命中diss_call关键字 # 添加diss_call的query, 360s后过期 action = Action(query_id, 'diss_call', 360) # 不在init中触发add,会有诡异问题,单数使用类方法add a = Query.save(action) # 组织msg msg['Content'] = '请添加骚扰过您的电话:' return msg else: # 未命中任何关键字 if msg['MsgType'] == 'text': # 仅当文本类型为text时 msg['Content'] = '不支持指令:%s。若需腹黑骚扰,请先回复“骚扰号码”或“骚扰电话”触发骚扰指令,然后输入骚扰过你的号码。(千万别拿自己或好友的号码来测试,不对其后果负责)' % msg[ 'Content'] return msg else: # 文本类型为event或image等,返回MsgParser处理后的内容 return msg
def _init_actions(self, actions): from app.models import Action for row in actions: project = self._projects.get(row['projectId']) context = self._contexts.get(row['contextId']) date = convert_to_date(row['start']) action = Action(row['_id'], row['description'], project, context, \ date, row['details'], row['complete']) self._buffer_action(action)
def __init__(self, editmode = False): QtGui.QWidget.__init__(self) self._action = Action() self.editmode = editmode content = self._setup_content() layout = QtGui.QHBoxLayout() layout.addWidget(content, 1) layout.addWidget(QtGui.QWidget(self), 1) self.setLayout(layout)
def add_action(): #data = json.loads(request.form) data=request.form.to_dict() code=data.get('action_code') has_action = Action.query.filter(Action.code == code).first() if has_action ==None: action1=Action(data.get('action_name')) action1.type=data.get('action_type') action1.code=code action1.comments=data.get('action_comments') db.session.add(action1) db.session.commit() else: return jsonify({ 'msg':'action code exist !' }) action_log(request,'添加操作权限') return jsonify({ 'msg':'sbumit success !' })
def action(): data = request.get_json(force=True) print(data) result = data["result"] newAction = Action(result["sessionId"], result["time"], result["actionId"], result["correctAnswer"], result["hotkeyUsed"], result["menuOpened"], result["menuDelay"] if "menuDelay" in result else None) db.session.add(newAction) db.session.commit() return "{}"
def save_action(self): action = self.get_action() if self.editmode: self.window().show_status("Action updated") self.hide_form() else: self.window().show_status("Action created") self.set_default() action.save() self._action = Action() event_register.action_change.emit()
def create_db(): "Create RoseGuarden database" print "Create database (this will remove old data)" db.create_all() User.query.delete() # add syncmaster-user for synchronisation print "Add syncmaster user" syncMasterUser = User('*****@*****.**', SYNC_MASTER_DEFAULT_PASSWORD, 'Sync', 'Master', 1) syncMasterUser.syncMaster = 1 db.session.add(syncMasterUser) # you can add some default user here print "Add admin user" defaultUser1 = User('Administrator', 'Admin1234', 'RoseGuarden', 'Admin', 1) defaultUser1.accessType = 1 db.session.add(defaultUser1) #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.137', keyMask = 0x01, local = 0x00 )) #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.138', keyMask = 0x01, local = 0x00 )) #db.session.add(Door(id = 0, name = 'front door', address = 'http://192.168.2.139', keyMask = 0x01, local = 0x00 )) print "Add local door" Door.query.delete() db.session.add( Door(name=config.NODE_NAME, displayName='Local', address='http://localhost', keyMask=0x03, local=0x01, password=config.SYNC_MASTER_DEFAULT_PASSWORD)) print "Add default settings" Setting.query.delete() db.session.add( Setting('NODE_VALID_KEYS_MASK', '3', Setting.SETTINGTYPE_INT)) print "Add log-entry" Action.query.delete() db.session.add( Action(datetime.datetime.utcnow(), config.NODE_NAME, syncMasterUser.firstName + ' ' + syncMasterUser.lastName, syncMasterUser.email, 'Remove all data & regenerate database', 'Init systen', 'L1', 1, 'Internal')) print "Save new database" db.session.commit() print "Successfully create new database"
def register_action(request): session = request.session if 'active' not in session: new_session = UserSession() db_session = Session() db_session.add(new_session) db_session.commit() session['id'] = new_session.id session['active'] = True db_session.close() new_action = Action(session_id=session['id'], url=request.url) db_session = Session() db_session.add(new_action) db_session.commit() db_session.close()
def redirect_link(link_hash): link = Link.query.filter_by(hash_str=link_hash).first() if link: ip = request.remote_addr agent = request.headers.get('User-Agent') new_action = Action(link_id=link.id, type_id=1, ip_address=ip, user_agent=agent, timestamp=datetime.utcnow()) db.session.add(new_action) db.session.commit() url = '{0}?partner_id={1}&hash={2}&k={3}'.format(link.site, 1, link.hash_str, current_app.config['ADVERT_SECRET_KEY']) return redirect(url)
def post(self, link_hash): link = Link.query.filter_by(hash_str=link_hash).first() if not link: return 'Not found', 404 data = request.args.to_dict() action_obj = ActionObject() action = Action( link_id=link.id, ip_address=data.get('subid1'), user_agent=data.get('subid2'), type_id=data.get('subid3'), purchase_amount=data.get('subid4'), ) db.session.add(action) db.session.commit() return action_obj.dump(action)
def hit_api(api, email, _from, _to): now = datetime.now() action = Action(time=now, api=api, email=email) db.session.add(action) db.session.commit() if api == 'google': url = google_url resp = requests.get(url.format(_from, _to)).json() return resp['rows'][0]['elements'][0]['duration']['value'] elif api == 'uber': url = uber_url _from, _to = _from.split(',') resp = requests.get(url.format(_from, _to)).json() return int( list(filter(lambda x: x['display_name'] == 'uberGO', resp['times']))[0]['estimate']) else: return 0
def submit(): form = SubmitForm() if form.validate_on_submit(): # Maßnahme hinzufügen # import pdb # pdb.set_trace() new_action = Action(name="var" + str(Action.query.count() + 1), description=form.description.data, sector=form.sector.data, category=form.category.data, savings=form.savings.data, solution_text=form.solution_text.data, reference=form.reference.data, comment=form.comment.data) # test_actions.append(new_action) db.session.add(new_action) db.session.commit() flash("Maßnahme #{}: {} wurde hinzugefügt".format( new_action.name, new_action.description)) return redirect(url_for("submit")) return render_template("submit_new.html", form=form)
def setUp(self): self.app = create_app(config_name="testing") self.client = self.app.test_client from app.models import User, Category, Action, Idea with self.app.app_context(): db.create_all() user = User(first_name="Ryan", last_name="Hantak", email="*****@*****.**", password="******") user.save() cat1 = Category(name="Finance") cat1.save() cat2 = Category(name="Education") cat2.save() cat3 = Category(name="Tech") cat3.save() action1 = Action(action="Create an app") action1.save() action2 = Action(action="Draft an ad campaign") action2.save() idea1 = Idea( user_id=user.id, random_word="Skate", action_id=action2.id, is_genius=True, question= "Create an ad campaign to sell a book about financial literacy.", response= "Two friends in a roller derby match are having a conversation about how they're investing their money, one tells the other about what they learned from the book and the second person is so impressed they want to buy it." ) idea1.save() idea2 = Idea( user_id=user.id, random_word="Bird", action_id=action1.id, is_genius=False, question="Create an app people use to trade stocks", response= "Make it easy to trade stocks mobile, charge a monthly fee so people don't feel like each trade costs them extra money and offer daily articles to encourage them to keep checking." ) idea2.save() user.categories.append(cat1) user.categories.append(cat2) user.categories.append(cat3) user.actions.append(action1) user.actions.append(action2) idea1.categories.append(cat1) idea1.categories.append(cat2) idea2.categories.append(cat1) idea2.categories.append(cat3) db.session.add_all([idea1, idea2]) db.session.commit() global user_token user_token = User.query.filter_by( email='*****@*****.**').first().token
def add_drexel_to_db(): import csv with open("static/data/food.csv", encoding="utf-8", newline='') as f: freader = csv.DictReader(f, delimiter="\t") # for line in freader: # logger.info(line["Lebensmittel"], line["CO2-Äquivalent in kg pro Person und Jahr"])) all = [] food = {} # keys = kategorien, vals = list of foods i, j = 0, 0 for line in freader: all.append(line) i += 1 if "Summe" in line["Lebensmittel"]: cat = line["Lebensmittel"][6:] food[cat] = all[j:i - 1] j = i logger.debug(f"{cat}: {food[cat]}") # Beginnen wir damit, für das Feld "Ernährung" je Kategorie eine Maßnahme # pro Reduktionsniveau zu definieren: REDUCTIONS = { "30%": 0.7, "50%": 0.5, "75%": 0.25, "90%": 0.1, "100%": 0.0, } for cat in food.keys(): for reduction in REDUCTIONS: co2standard = sum([ float(savings["CO2-Äquivalent in kg pro Person und Jahr"]) for savings in food[cat] ]) savings = round(co2standard * (1 - REDUCTIONS[reduction]), 4) action_dict = { "name": "".join([cat, " -", reduction]), "sector": "Ernährung", "category": cat, "savings": savings, "reduction_factor": REDUCTIONS[reduction], "description": f"Ernährungsstil: {cat} um {reduction} im Vergleich zum Durchschnitt reduzieren", "solution_text": f"Führt im Vergleich zum durchschnittlichen Ernährungsstil zu " \ f"Einsparungen von {savings} kg CO2eq pro Jahr", "reference": "https://www.zwei-grad-eine-tonne.at/hintergrund-berechnungen/abschnitt-i-lustvoll-die" "-welt-retten" } b = Action(**action_dict) db.session.add(b) logger.info(f"db.session.add({b})") action_dict = { "name": "Flexitarier, konventionell", "sector": "Ernährung", "category": "Gemischt", "description": "Zweimal pro Woche Fleisch oder Fisch, durchschnittliche Mengen an Wurtsprodukten, Milchprodukten, Obst und Gemüse.", "savings": 300.0, "reduction_factor": 300 / 1800, "solution_text": f"Führt im Vergleich zum durchschnittlichen Ernährungsstil zu Einsparungen von 300 kg CO2eq pro Jahr", "reference": "https://www.zwei-grad-eine-tonne.at/hintergrund-berechnungen/abschnitt-i-lustvoll-die" "-welt-retten" } rm1 = Action(**action_dict) db.session.add(rm1) logger.info(f"db.session.add({rm1})") # %% drexel_dict = { "name": "Bio-Flexitarier", "sector": "Ernährung", "category": "Gemischt", "description": " ".join([ action_dict["description"], "Wann immer möglich regional und bio." ]), "savings": 1800.0 - 1100, "reduction_factor": (1800.0 - 1100) / 1800, "solution_text": f"Führt im Vergleich zum durchschnittlichen Ernährungsstil zu Einsparungen von 300 kg CO2eq pro Jahr", "reference": "https://www.zwei-grad-eine-tonne.at/hintergrund-berechnungen/abschnitt-i-lustvoll-die" } rm2 = Action(**drexel_dict) db.session.add(rm2) logger.info(f"db.session.add({rm2})") with open("static/data/Abschnitt%20I%20Verkehr.csv", encoding="utf-8", newline='') as f: freader = csv.DictReader(f, delimiter=",") # for line in freader: # logger.info(line["Lebensmittel"], line["CO2-Äquivalent in kg pro Person und Jahr"]) all = [] # keys = kategorien, vals = list of foods i, j = 0, 0 for line in freader: if line["Verhalten"] != "": all.append(line) verkehrstile = [] sector = "Verkehr" for dicts in all: if dicts["Fahrzweck"] == "Summe": savings = 1.5177 * 1000 - float( dicts["CO2-Emission gesamt in Tonnen pro Person"]) * 1000 name = "".join([sector, ": ", dicts["Verhalten"]]) action_dict = { "name": name, "sector": sector, "category": "Gemischt", "description": name, "savings": savings, "reduction_factor": savings / (1.5177 * 1000), "solution_text": f"Führt im Vergleich zum durchschnittlichen Verkehrsverhalten zu Einsparungen von {savings} kg CO2eq pro Jahr", "reference": "https://www.zwei-grad-eine-tonne.at/hintergrund-berechnungen/abschnitt-i-lustvoll-die" "-welt-retten" } b = Action(**action_dict) db.session.add(b) if input(f"Commit to db? [y/n]? ").upper() == "Y": db.session.commit() logger.info(f"db.session.commit()")