def classifyComment(type, mealID): if type == "1": svm = joblib.load( "E:\Pycharm\workspace\FoodOrder-master\saved_model\waimai.pkl") print(mealID) temp1 = DataBase.GetComment(mealID) print(temp1) for each in temp1: print(each[1]) if (each[1] == -1 or each[1] == "-1"): print("--------------------------------------") score = svm.classify(each[0]) DataBase.Updatecomment(mealID, each[0], score) elif type == "2": d = DictClassifier() temp1 = DataBase.GetComment(mealID) print(temp1) for each in temp1: print(each[1]) if (each[1] == -1 or each[1] == "-1"): print("--------------------------------------") result = d.analyse_sentence( each[0], runout_filepath="hyoupannokeka.txt", print_show=True) print(result) DataBase.Updatecomment(each[0], mealID, result)
def run(self): ''' 进程主入口方法,连接redis数据库,开启子线程读取读写器的信息 ''' self.r = redis.StrictRedis(host=Var.REDIS_HOST, port=Var.REDIS_PORT, db=Var.REDIS_DB) dataBase = DataBase() ips = dataBase.getReaderIP() threads = [] try: for ip in ips: # 为每个读写器的验证开一个线程 threads.append(threading.Thread(target=self.ping, args=(ip, ))) for thread in threads: thread.start() while True: for i in range(0, len(threads)): if threads[i].isAlive() == False: threads[i] = threading.Thread(target=self.ping, args=(ips[i], )) threads[i].start() self.r.ping() # self.clearRedis(dataBase) except Exception, ex: print "Monitor run error function" print ex
def start(bot, update): inCome_uid, inCome_name, inCome_user_id = exctract_info( update.message.from_user) try: with conn: isThere = db.query_user(conn, inCome_uid) if isThere == 0: db.add_user(conn, inCome_uid, inCome_name, inCome_user_id, state='not signed home') if inCome_user_id == 'None': inCome_user_id = '[NO USER ID]' else: inCome_user_id = '@' + inCome_user_id send_text( log_chan, ms.new_member_log + '\n' + inCome_user_id + '\n' + inCome_name) send_text(int(inCome_uid), ms.start, keyboard=bt.home_not_signed) else: db.update_user(conn, inCome_uid, name=inCome_name, user_id=inCome_user_id, state='not signed home') send_text(int(inCome_uid), ms.start, keyboard=bt.home_not_signed) except Exception as e: print(e)
def saveData(self, index): self.widgetView.save() dataname = str(index) + '.mat' dir = self.ini.file.savedir + dataname db.saveMatPoint( dir, self.data, self.ini.file.names[self.ini.parameter.sequence[index]])
def clustering(): kmeans = KMeans(n_clusters=db.num_cluster) kmeans.fit_predict(db.df) for i in range(db.num_cluster): db.dict_Cluster[i] = [] i = 0 for idx, row in db.df.iterrows(): cluster_idx = kmeans.labels_[i] id = idx db.dict_Cluster[cluster_idx].append(db.dict_Parcel[id]) i +=1 DBObj = db.getTMSDB('tmssample') db.dropDB('tmssample') now = datetime.datetime.now() todayDate = now.strftime('%Y-%m-%d') for v in db.dict_Cluster: cluster_num = str(v) for c in db.dict_Cluster[v]: DATA = {'id': c.id, 'date': todayDate, 'lat': c.lat, 'lon': c.lon, 'addr': c.addr, 'clusterNum':cluster_num, 'order':0, 'state':0, 'picName':''} DBObj.insert_one(DATA)
def show_report(code, startdate): df = ts.get_hist_data(code, start=startdate) df1 = df[::-1] x = df1.index xlist = x.tolist() y1 = df1['close'] ylist1 = y1.tolist() engine = create_engine("mssql+pyodbc://sa:123456@test") conn, cur = db.connDB() cur = db.exeQuery(cur,"select * from tb_report where code = '%s' and reportdate > '%s' order by reportdate" % (code,startdate)) all = cur.fetchall() db.connClose(conn,cur) ylist2 = [] num = 0 for eachx in xlist: isin = 0 for eachy2 in all: if eachy2[0] == eachx: isin = isin + 1 if isin == 0: ylist2.append(num) else: num = num + isin ylist2.append(num) x = np.arange(0,len(xlist)).tolist() plt.plot(x, ylist1,label=code) plt.plot(x,ylist2) plt.legend() plt.savefig(code+'.jpg',dpi=200) # plt.show() result = {} result['close'] = ylist1 result['report'] = ylist2 resultfm = pd.DataFrame(result, index=xlist) return resultfm
def send_text(message): if message.text.lower() == 'поиск по названию': msg = bot.send_message( message.chat.id, 'Введи название дорамы, котрую хочешь посмотреть(и мы попробуем её найти в нашей базе)' ) bot.register_next_step_handler(msg, process_title_search) elif message.text.lower() == 'поиск по жанру': msg = bot.send_message( message.chat.id, 'Введи нужные жанры(если несколько, то через запятую без пробелов)' ) bot.register_next_step_handler(msg, process_genre_search) elif message.text.lower() == 'поиск по актеру': msg = bot.send_message( message.chat.id, 'Введи нужных актеров(если несколько, то через запятую без пробелов)' ) bot.register_next_step_handler(msg, process_actor_search) elif message.text.lower() == 'поиск по году': msg = bot.send_message( message.chat.id, 'Введи нужный год или диапазон годов(если вводишь диапазон, то вводи в формате год-год)' ) bot.register_next_step_handler(msg, process_year_search) elif message.text.lower() == 'случайная дорама': msg = bot.send_message( message.chat.id, 'Держи случайную дораму из нашей базы, надеемся что тебе понравится \n' ) information = DataBase.random_dorama() bot.send_message(message.chat.id, information) elif message.text.lower() == 'добавить в избранное': msg = bot.send_message( message.chat.id, 'Введи название дорамы, которую хочешь добавить') bot.register_next_step_handler(msg, process_add_to_favourites) elif message.text.lower() == 'избранное': try: connection = DataBase.get_connection() cursor = connection.cursor() user_id = message.from_user.id command2 = "SELECT name_of_movie FROM Favourites WHERE id_user LIKE '%" + str( user_id) + "%'" cursor.execute(command2) titles = cursor.fetchall() if len(titles) == 0: raise NameError('Ошибка') msg = bot.send_message(message.chat.id, 'Ваш список избранного: \n') information = DataBase.select_from_favourites(user_id) bot.send_message(message.chat.id, information) except Exception as e: bot.reply_to(message, "Ваш список пуст") elif message.text.lower() == 'удалить из избранного': msg = bot.send_message( message.chat.id, 'Введи название дорамы, которую хочешь удалить из избранного:') bot.register_next_step_handler(msg, process_delete_from_favourites) else: bot.send_message(message.chat.id, "Не понял вашей команды")
def verify_inputs(self,entries): #inputs received from entries consumer_key=entries[0].get() consumer_secret=entries[1].get() access_token=entries[2].get() access_token_secret=entries[3].get() #Authentication With Twitter Developer Account try: if len(consumer_key)!=0 and len(consumer_secret)!=0 and len(access_token)!=0 and len(access_token_secret)!=0: auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) #create connection to db and add username user = api.me() print("success : ",user.name) DataBase.dropTable() DataBase.create_connection(user.name,consumer_key,consumer_secret,access_token,access_token_secret) print("success adding to db") time.sleep(1) tk.messagebox.showinfo(message="Success login to : "+user.name) self.controller.show_frame("StartPage") else: tk.messagebox.showinfo(message="Check your inputs") except: print("Error: Authentication Failed")
def database_type(database): if isinstance(database, str): return DataBase.py_db(file_path=database) elif isinstance(database, GamsDatabase): return DataBase.py_db(database_gdx=database) elif isinstance(database, DataBase.py_db): return database
def show_report_price(code,startdate): df = ts.get_hist_data(code, start=startdate) df1 = df[::-1] highdate='' highprice=0 lowdate=startdate lowprice=1000 i = 0 for each in df1.index: if df1['close'].iloc[i] > highprice: highprice = df1['close'].iloc[i] highdate = each i=i+1 i = 0 for each in df1.index: if each < highdate: if df1['close'].iloc[i] < lowprice: lowprice = df1['close'].iloc[i] lowdate = each i = i+1 print highdate, highprice print lowdate, lowprice print (highprice-lowprice)/lowprice engine = create_engine("mssql+pyodbc://sa:123456@test") conn, cur = db.connDB() cur = db.exeQuery(cur,"select * from tb_report where code = '%s' and reportdate <= '%s' and reportdate >= '%s' order by reportdate" % (code,highdate,lowdate)) all = cur.fetchall() db.connClose(conn,cur) print len(all)
def create_answer(data, group_id): DB.Message().add(data["text"], data["attachment"] if "attachment" in data else "Empty", data["payload"] if "payload" in data else "Empty", data["from_id"]) if data["text"].lower() == "начать": start_answer(data, group_id) return True if "payload" not in data: return False data["payload"] = json.loads(data["payload"]) if "command" in data["payload"]: start_answer(data, group_id) if "payload" in data: if data["payload"]["active"] == "True": DB.User_subscription().remove(data["payload"]["sub_id"], data["from_id"]) else: DB.User_subscription().add(data["from_id"], data["payload"]["sub_id"]) sub_kb = get_sub_kb(data["from_id"], group_id) community = get_community({"group_id": group_id}) Vk.send_message(data["from_id"], community["token"], message="Подписки обновлены", keyboard=sub_kb) return True return False
def GET(self): cabecera = "Bienvenido "+session.usuario+" <a href=\"salir\">SALIR</a> <li><a href=\"modificar\">Modificar</a><li> " self.registro = form.Form( form.Textbox('nombre',form.Validator("El nombre no puede estar vacio", lambda i: i !=""),description="Nombre",value=DataBase.getNombre()), form.Textbox('apellidos',form.Validator("Los apellidos no pueden estar vacios", lambda i: i !=""),description="Apellidos",value=DataBase.getApellidos()), form.Textbox('correo',vemail,description="Correo",value=DataBase.getCorreo()), form.Dropdown('dianacimiento',[(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10'), (11, '11'), (12, '12'), (13, '13'), (14, '14'), (15, '15'), (16, '16'), (17, '17'), (18, '18'), (19, '19'), (20, '20'), (21, '21'), (22, '22'), (23, '23'), (24, '24'), (25, '25'), (26, '26'), (27, '27'), (28, '28'), (29, '29'), (30, '30'), (31, '31')],description="Dia de nacimiento",value=DataBase.getDiaNacimiento()), form.Dropdown('mesnacimiento',[(1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), (6, '6'), (7, '7'), (8, '8'), (9, '9'), (10, '10'), (11, '11'), (12, '12')],description="Mes de nacimiento",value=DataBase.getMesNacimiento()), form.Dropdown('anonacimiento',[(1993,'1993'),(1992,'1992'),(1991,'1991')],description="Ano nacimiento",value=DataBase.getAnoNacimiento()), form.Textarea('direccion',form.Validator("La direccion no puede estar vacia", lambda i: i !=""),description="Direccion",value=DataBase.getDireccion()), form.Password('password',vpass,description="Password"), form.Password('password2',vpass,description="Verificacion"), form.Textbox('visa',vvisa,description="Numero visa",value=DataBase.getNumeroVisa()), form.Radio('formapago',['Contra reembolso','Tarjeta Visa'],value=DataBase.getFormaPago()), form.Checkbox('aceptacion', form.Validator("Acepta las clausulas", lambda i: i == 'true'), value='true'), form.Button('submit',type="submit", description="Enviar"), validators = [ form.Validator("Las pass no coinciden", lambda i: i.password == i.password2)] ) formulariomodificar = self.registro() return render.modificar(form=cabecera,enlaces=session.get('enlaces'),modificar="<form name=\"main\" method=\"post\"> "+formulariomodificar.render()+"</form>")
def POST(self): form = myform() nuevousuario = registro() if (not form.validates() or not login(form.d.user,form.d.contrasena)) and (not hasattr(session, 'usuario')): cabecera = "<form name=\"main\" method=\"post\"> "+form.render()+"</form>" if not nuevousuario.validates(): formularioRegistro = "<form name=\"main\" method=\"post\"> "+nuevousuario.render()+"</form>" else: formularioRegistro="" DataBase.insertar(nuevousuario.d.nombre,nuevousuario.d.apellidos,nuevousuario.d.correo,nuevousuario.d.dianacimiento,nuevousuario.d.mesnacimiento, nuevousuario.d.anonacimiento,nuevousuario.d.direccion,nuevousuario.d.password,nuevousuario.d.visa,nuevousuario.d.formapago) DataBase.close() else: session.usuario = form.d.user cabecera = "Bienvenido "+session.usuario+" <a href=\"salir\">SALIR</a><a href=\"modificar\">Modificar</a>" formularioRegistro="" addWeb("/") global rss global ultimahora global urlrss ultimahora=datetime.datetime.now() if datetime.datetime.now()-ultimahora>=datetime.timedelta(seconds=10) or rss==None: ultimahora=datetime.datetime.now() feed = feedparser.parse(urlrss) entradas = feed.entries rss="<ul>" for entrada in entradas: rss+="<li><a href=\""+entrada.link+"\">"+entrada.title+"</a></li>" rss+="</ul>" return render.index(form=cabecera,enlaces=session.get('enlaces'),registro=formularioRegistro,rss=rss)
def listen_to_client(self, client, address): client_name = client.recv(BUFF_SIZE) data_base = DataBase(self.key) if not data_base.is_exist("Clients", client_name): data_base.add_row_to_table("Clients", [client_name, address[0], address[1]]) print "Client " + client_name + " is connected" else: print "client " + client_name + " is connected again" while True: try: data = client.recv(BUFF_SIZE) print data if data: if "#" in data: data_list = self.unpack_command(data) print data_list answer = self.handle_command(data_list) print answer if type(answer) is list: print "list" packets = answer[1] client.send(str(answer[0])) for x in range(answer[0]): client.send(packets[x]) else: client.send(answer) else: pass else: print 'Client disconnected' except: print "Client " + client_name + " has been disconnected" client.close() return False
def check_fill(id, code): code = str(int(code) + 1) DB.set_state(id, code) message = vkMessage(DB.get_state_help(code)) message.keyboard = cancel_keyboard() message.attachment = "photo-147403573_456239150" return message
def send_list(self, data): data_base = DataBase(self.key) # client_name, classification packets = data_base.get_list(data[1], data[0]) if packets[0] == "": return [0, packets] return [len(packets), packets]
def getAll(self, table_name): # table_name: song, playlist, band, artist, album self.song_list.adapter.data.clear() self.ows = table_name self.lg = table_name if table_name == "song": self.songs = db.getAll(self.con, table_name) self.addToScreen(self.songs) #self.play() #self.pause() elif table_name == "band": self.bands = db.getAll(self.con, table_name) self.addToScreen(self.bands) elif table_name == "artist": self.artists = db.getAll(self.con, table_name) self.addToScreen(self.artists) elif table_name == "playlist": self.playlists = db.getAll(self.con, table_name) # self.addToScreen(self.playlists) for s in self.playlists: self.song_list.adapter.data.extend([ s.name + " " * (35 - len(s.name)) + "Tracks:" + str(s.numOfSongs) ]) self.song_list._trigger_reset_populate() elif table_name == "album": self.albums = db.getAll(self.con, table_name) self.addToScreen(self.albums)
def update(query, column_text, peer_id, state_code): state_code = str(int(state_code) + 1) args = (column_text, state_code, peer_id) DB.insert_data(query, args) message = vkMessage(DB.get_state_help(state_code)) message.keyboard = cancel_keyboard() return message
def obtener_discos(): musicbrainzngs.set_useragent('musicbrainzngs', '2.0') # results = musicbrainzngs.search_releases(artist='Ozzy Osbourne', country="us", limit=10) # pprint.pprint(results) # for artist in results['release-list']: # print(artist['id'], artist['artist-credit'][0]['name'], artist['release-group']['title'], artist['status'], artist['release-group']['type']) listilla = DataBase.Ver_Nombres() for i in range(0, len(listilla)): results = musicbrainzngs.search_releases(artist=listilla[i], country="us", limit=5) for artist in results['release-list']: if 'status' in artist: status = artist['status'] else: status = 'Unofficial' if 'type' in artist['release-group']: tipo = artist['release-group']['type'] else: tipo = 'Other' panecito = disquillos.album(artist['id'], artist['artist-credit'][0]['name'], artist['release-group']['title'], status, tipo) DataBase.Agregar_Elemento_Album(panecito)
def main(): DataBase.reset() DataBase.fill() driver = run_driver(set_proff()) open_mail(driver) open_fb(driver) create_accounts(driver)
def deletarCompromisso(): title = deletar_evento.lineEdit.text() typeofcomp = deletar_evento.comboBox.currentText() db.deletarcompromisso(title, typeofcomp) agendaSQLite() deletar_evento.hide() agenda.show()
def update_process(self, data): data_base = DataBase(self.key) # client name, process name primary_key = data_base.get_primary_key(data[3], data[1]) # param, value, classification_ID data_base.update_table("Classification", "Classification", data[0], primary_key) return "Process updated"
def login(usuario,contrasena): if usuario=="" or contrasena=="" or usuario==None or contrasena==None: return False elif usuario == DataBase.getNombre() and contrasena == DataBase.getPassword(): return True else: return False
def determineMessage(receivedMessage: str, phoneNum: str): receivedMessage = receivedMessage.strip() if receivedMessage.lower() == 'new': groupNum = generateCode() if not DataBase.MakeNewGroup(phoneNum, groupNum): messageToSend = 'You are already in a group. Please check out that group before you create a new one.' send_sms(messageToSend, phoneNum) return 'ERRORONNEW' messageToSend = 'You have successfully created a group. The code of the group is ' + str(groupNum) + '. Share this code with your friends and have them send it to (949) 835-5128 within 10 minutes.' send_sms(messageToSend, phoneNum) return groupNum elif (typeisint(receivedMessage) and len(receivedMessage) == 6): if DataBase.AddMember(phoneNum, int(receivedMessage)): messageToSend = 'You have successfully entered the group ' + str(receivedMessage) + '. To request money from this group, simply reply the amount of it.' else: messageToSend = 'Sorry, the group code you entered ({}) is invalid.'.format(receivedMessage) send_sms(messageToSend, phoneNum) elif re.match(r'^\$?(\d+(\.\d{1,2})?)$', receivedMessage) != None: messageToSend = 'We have got your split request of ${} in this group. All the friends in this group will be notified.'.format(receivedMessage) DataBase.AddTrans(phoneNum, re.match(r'^\$?(\d+(\.\d{1,2})?)$', receivedMessage).group(1)) send_sms(messageToSend, phoneNum) receiver = DataBase.getMembers(phoneNum) receiver.remove(phoneNum) comfirm = '{} just requested a ${} bill split from the group. Reply \'N\' within 10 minutes to withdraw from the split.'.format(phoneNum, receivedMessage) for num in receiver: send_sms(comfirm, num) elif re.match(r'^\d+[+\-\*//]\d+([+\-\*//]\d+)*$',receivedMessage) != None: total = str(round(eval(receivedMessage), 2)) messageToSend = 'We have got your split request of ${} in this group. All the friends in this group will be notified.'.format(total) DataBase.AddTrans(phoneNum, total) send_sms(messageToSend, phoneNum) receiver = DataBase.getMembers(phoneNum) receiver.remove(phoneNum) comfirm = '{} just requested a ${} bill split from the group. Reply \'N\' within 10 minutes to withdraw from the split.'.format(phoneNum, total) for num in receiver: send_sms(comfirm, num) elif receivedMessage.lower() == 'n': messageToSend = 'You have successfully quit from the last bill split.' if DataBase.Deny(phoneNum): send_sms(messageToSend, phoneNum) else: messageToSend = 'The 10-minute time limit has been exeeded and you are unable to quit from the last bill split.' send_sms(messageToSend, phoneNum) elif receivedMessage.lower() == 'checkout': result = DataBase.summary(phoneNum) if result == False: messageToSend = 'Your check out request is not accepted: only the creater of the group ({}) can make the check out request.'.format(DataBase.getMaster(phoneNum)) send_sms(messageToSend, phoneNum) else: for payer, topay in result.items(): messageToSend = 'User {} need pay to follwing person(s):\n'.format(payer) for receiver, amount in topay.items(): messageToSend += '{}: ${}\n'.format(receiver, amount) send_sms(messageToSend, payer) DataBase.clear(phoneNum) messageToSend = 'Group Deleted. See you next time!' send_sms(messageToSend, phoneNum) else: messageToSend = 'We are unable to recognize this command. To request money from this group, reply the amount of it.' send_sms(messageToSend, phoneNum)
def aanbieden(self, data): api = Api() db = DataBase() if db.saveAanbieder(data['titel'], api.getCurrentTime()): self.aanbieder.configure(text="Gasten lijst", command=lambda controller=self.controller: self.gastenlijst(controller, data))
async def process_start_command(message: types.Message): await message.answer( "Please, select language 🇬🇧\n" "Пожалуйста, выбери язык 🇷🇺\n", reply_markup=keyboard.languages()) if not database.user_exists(message.from_user.id): database.add_user(message.from_user.id) await msg.delete_message(bot, message)
def Sum(sql): db = DataBase("money.db") db.Execute(sql) result = db.GetResult() sum = 0.0 for i in result: sum += i[0] return sum
def SetType(typename): db = DataBase("money.db") sql = "INSERT INTO IncomeType VALUES( " sql += "NULL" sql += " , \"" sql += typename sql += "\")" db.Execute(sql)
def MessegesScreen(self): userList = self.getList() DataBase.updateUserTable(userList) folderLoad = FileSystemLoader('temp') createEnvironment = Environment(loader=folderLoad) getMsgPage = createEnvironment.get_template('onlineUsers.html') messegePage = getMsgPage.render(userList=userList) return messegePage
def user_signup(): if request.method == "POST": user_response = request.get_json() if validate_user_emailid(user_response["emailId"]): db.add_user_to_db(user_response) return jsonify({}), 200 else: return jsonify({}), 409
def user_name_isValid(inCome_uid, input_message): try: with conn: db.update_user(conn, inCome_uid, p_user_name=input_message) return 1 except Exception as e: print(e) return 0
def echo_message(message): bot.reply_to(message, message.text) print(message.text) entetys = (message.text, message.chat.id) con = DataBase.sql_connection() DataBase.sql_table(con) DataBase.sql_insert(con, entetys) con.close()
def add_process(self, data): data_base = DataBase(self.key) print data[3] if not data_base.is_process_exist(data[3], data[1]): # client name, process name, process signature, classification data_base.add_row_to_table("Classification", [data_base.classification_id_counter, data[3], data[1], str(data[2]), int(data[0])]) return "Process " + data[1] + " added to client " + data[3] + " with classification " + data[0] return "Process already exists"
def Grade(weid): if DataBase.Select(weid)==" ": return "请绑定教务网账号和密码格式如:\n14050205101&xasdascas" else: str=DataBase.Select(weid) user=str.partition('@') username=user[0] password=user[2]
def patientCreation(): data = '' if 'sigenID' and 'sex' in request.args.keys(): sigenID = request.args['sigenID'] sex = request.args['sex'] DataBase.createPatient(sigenID, sex) data = 'Patient Created: ' + sigenID return render_template("patientCreation.html", data=data)
def help_func(message): try: con = DataBase.sql_connection() ghu = DataBase.sql_getRow(con) bot.send_message(message.chat.id, "yhhhh") ## requests.get("http://18.188.44.19:9090/?login=gghsdsa") except: bot.send_message(message.chat.id, "херня какая-то")
def aanmelden(self, controller): if self.naam.get() == '' or self.email.get() == '': self.error.configure(text='Vul alle gegevens in.') else: api = Api() db = DataBase() ucode = uuid4().hex db.saveFilm(self.data["titel"], self.data["aanbieder"], api.getCurrentTime(), ucode, self.naam.get(), self.email.get()) controller.show_frame(qrFrame, ucode)
def POST(self): formulariomodificar = self.registro() cabecera = "Bienvenido "+session.usuario+" <a href=\"salir\">SALIR</a> <li><a href=\"modificar\">Modificar</a><li>" if formulariomodificar.validates(): DataBase.insertar(formulariomodificar.d.nombre,formulariomodificar.d.apellidos,formulariomodificar.d.correo,formulariomodificar.d.dianacimiento,formulariomodificar.d.mesnacimiento, formulariomodificar.d.anonacimiento,formulariomodificar.d.direccion,formulariomodificar.d.password,formulariomodificar.d.visa,formulariomodificar.d.formapago) return render.modificar(form=cabecera,enlaces=session.get('enlaces'),modificar="<p>TODO INSERTADO</p><form name=\"main\" method=\"post\"> "+formulariomodificar.render()+"</form>") else: return render.modificar(form=cabecera,enlaces=session.get('enlaces'),modificar="<form name=\"main\" method=\"post\"> "+formulariomodificar.render()+"</form>")
def remove_process(self, data): data_base = DataBase(self.key) print data[0] print data[1] # clint name, process name primary_key = data_base.get_primary_key(data[1], data[0]) print primary_key # classification_ID data_base.delete_row("Classification", primary_key) return "Process removed"
def new_report(id): query = """ INSERT INTO Reports(PersonId) VALUES(%s) """ DB.insert_data(query, (id, )) message = vkMessage(DB.get_state_help(6)) message.keyboard = cancel_keyboard() DB.set_state(id, 6) return message
def RegUsuário(): Usuário = registra.lineEdit.text() Senha = registra.lineEdit_2.text() Senha2 = registra.lineEdit_3.text() if Senha == Senha2: db.criarUsuario(Usuário, Senha) QMessageBox.about(registra, 'ALERTA', "USUÁRIO ADICIONADO!") registra.hide() Login.show() else: QMessageBox.about(registra, 'ALERTA', "AS SENHAS NÃO CONDIZEM")
def editarCompromisso(): titulo_Antigo = editar_evento.lineEdit_tituloAntigo.text() Tipo_Antigo = editar_evento.comboBox_TipoAntigo.currentText() Titulo_Novo = editar_evento.lineEdit_tituloNovo.text() Tipo_Novo = editar_evento.comboBox_TipoNovo.currentText() Descrição_Nova = editar_evento.lineEdit_descrio.text() db.editarCompromisso(titulo_Antigo, Tipo_Antigo, Titulo_Novo, Tipo_Novo, Descrição_Nova) agendaSQLite() editar_evento.hide() agenda.show()
class ServerSocket: def __init__(self): #Constructor self.server_socket = socket.socket() self.server_socket.bind(('0.0.0.0', 1729)) self.server_socket.listen(10) self.open_client_sockets = [] self.database = DataBase() def handle_clients(self): #handle all the clients using the service while True: read_list , write_list, error_list = select.select([self.server_socket]+ self.open_client_sockets, [], []) for current_socket in read_list: if current_socket is self.server_socket: (new_socket , address) = self.server_socket.accept() self.open_client_sockets.append(new_socket) else: data = current_socket.recv(1024) if data =="": self.open_client_sockets.remove(current_socket) print "connection with client close" else : datalist = self.unpack_command(data) current_socket.send(self.handle_command(datalist)) def unpack_command(self, command): #unpacking command parts like command itself, parameters , parameters' number params = [] details = command.split('#') command = details[0] param_number = int(details[1]) for x in xrange(param_number): params.append(details[x+2]) return [command, param_number, params] #region fill it def send_list(self, client_name, classification): return self.database.get_list(client_name, classification) def remove_process(self, classification_ID): self.database.delete_row("Classification", classification_ID) return "process removed" def update_process(self, param, value, classification_ID): self.database.update_table("Classification", param, value, classification_ID) return "process update" #endregion def handle_command(self, datalist): #call the right command from the dictionary commands_dict = {"GetWhiteList": self.send_list(datalist[2][0], datalist[2][1]), "GetBlackList": self.send_list(datalist[2][0], datalist[2][1]), "RemoveProcess": self.remove_process(datalist[2][0]), "UpdateProcess": self.update_process(datalist[2][0], datalist[2][1], datalist[2][2])} if (datalist[1] in commands_dict.keys()): return commands_dict[datalist[0]]
def loadData(self, index): if self.error: self.data = None return dataname = self.ini.file.names[self.ini.parameter.sequence[index]] dir = self.ini.file.datadir + dataname data, info = db.loadMatData(dir) dataname = str(index) + '.mat' dir = self.ini.file.savedir + dataname point = db.loadMatPoint(dir) self.data = db.BasicData(data, info, point)
def __cache(self, url, path, ids): ''' 缓存数据 ''' list = [] tagCasts = DataBase().tagCasts if not os.path.exists(path): os.mkdir(path) for iid in ids: # 标签EPC映射 castedId = tagCasts.has_key(iid) and tagCasts[iid] or iid id = re.compile(r'^0+').sub('', castedId) newUrl = url + str(id) data = urllib2.urlopen(newUrl).read() data = json.loads(data) data['EPC'] = iid qrCodes = DataBase().qrCodes data['qrCode'] = qrCodes.has_key(iid) and qrCodes[iid] or None # 缓存数据中的图片 if data['code'] == 200: # 缓存产品图片 data = self.cacheImgs(path, data, id, u'goods_img') # threading.Thread(target=self.cacheImgs, args=(data, id, u'goods_Img')).start() # 缓存商品颜色图片 data = self.cacheImgs(path, data, id, u'goods') # threading.Thread(target=self.cacheImgs, args=(data, id, u'goods')).start() # 缓存商标logo data = self.cacheImgs(path, data, id, u'brand_ico') # threading.Thread(target=self.cacheImgs, args=(data, id, u'brand_ico')).start() # 缓存默认商品图片 data = self.cacheImgs(path, data, id, u'goodsDefault') # threading.Thread(target=self.cacheImgs, args=(data, id, u'goodsDefault')).start() # 缓存促销banner图片 data = self.cacheImgs(path, data, id, u'promotion_banner') # threading.Thread(target=self.cacheImgs, args=(data, id, u'promotion_banner')).start() # 缓存同等商品图片 data = self.cacheImgs(path, data, id, u'sameGoods') # threading.Thread(target=self.cacheImgs, args=(data, id, u'sameGoods')).start() list.append(data) # 安排每5分钟运行一次自己 self.schedule.enter(300, 0, self.__cache, (url, path, ids)) return list
def listaDb(self): """Retorna uma lista com todos os Professores do DB""" lista = DataBase.getListDbAluno() if lista == None: return () else: return lista
def deleteHorario(self, turma): """Deleta horario da tabela no BD""" if DataBase.deleteTurma_Horario(turma): self.setHorario(None) return True else: return False
def addAluno(self, turma, aluno): """Add aluno relacionado a turma direto no bd""" if DataBase.addTurma_Aluno(turma, aluno): self.carregarAluno(self.getTurma()) return True else: return False
def deleteAluno(self, aluno): """Deleta aluno da tabela""" if DataBase.deleteTurma_Alunos(aluno): self.carregarAluno(self.getTurma()) return True else: return False
def addHorario(self, turma, disciplina1=None, disciplina2=None, disciplina3=None, disciplina4=None, disciplina5=None, disciplina6=None, disciplina7=None, disciplina8=None, disciplina9=None, disciplina10=None, disciplina11=None, disciplina12=None, disciplina13=None, disciplina14=None, disciplina15=None, disciplina16=None, disciplina17=None, disciplina18=None, disciplina19=None, disciplina20=None, disciplina21=None, disciplina22=None, disciplina23=None, disciplina24=None, disciplina25=None): """Add horario relacionado a turma direto no bd""" if DataBase.addTurma_Horario(turma, [disciplina1, disciplina2, disciplina3, disciplina4, disciplina5, disciplina6, disciplina7, disciplina8, disciplina9, disciplina10, disciplina11, disciplina12, disciplina13, disciplina14, disciplina15, disciplina16, disciplina17, disciplina18, disciplina19, disciplina20, disciplina21, disciplina22, disciplina23, disciplina24, disciplina25]): self.setHorario(self.carregarHorario(turma)) return True else: return False
def listaDb(self): """Returna uma lista com todos as disciplinas do BD""" lista = DataBase.getListDbDisciplina() if lista == None: return () else: return lista
def setData(self, data): apis = Api() db = DataBase() movie_list = apis.getMovieList(apis.getCurrentTime()) col = 0 date = apis.getCurrentTime() geenfilm = True for titel in movie_list: if db.checkFilmAanbieder(titel['titel'], date): images = ImageTk.PhotoImage(Image.open(str(titel['image']))) b1 = tk.Button(self, command=lambda controller=self.controller, titel=titel: self.details(controller, titel), image=images, height=290, width=168) b1.grid(row=3, column=col, pady=25, padx=10) # save the button image from garbage collection! b1.image = images tijd = datetime.datetime.fromtimestamp(int(titel['starttijd'])) titel['aanbieder'] = db.getFilmAanbieder(titel['titel'], date) titelbtn = tk.Button(self, command=lambda controller=self.controller, titel=titel: self.details(controller, titel), text=titel['titel'], font=("Tahoma", 10, "bold"), bg=FL_BG_COLOR, fg=FL_TEXT_COLOR, relief="flat", activebackground=FL_BG_COLOR, activeforeground=FL_TEXT_COLOR) titelbtn.grid(row=4, column=col) starttijd = tk.Label(self, text=str(tijd), font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) starttijd.grid(row=5, column=col) aanbieders = tk.Label(self, text=titel['aanbieder'], font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) aanbieders.grid(row=6, column=col) col += 1 geenfilm = False if geenfilm: if apis.getError() != '': label = tk.Label(self, text=apis.getError(), font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) label.grid(row=3, column=0, sticky='w', padx=25, columnspan=5) elif db.getError() != '': label = tk.Label(self, text=db.getError(), font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) label.grid(row=3, column=0, sticky='w', padx=25, columnspan=5) else: label = tk.Label(self, text="Er zijn geen aanbieders die een film aanbieden", font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) label.grid(row=3, column=0, sticky='w', padx=25, columnspan=5)
def delete(self, turma): """Deleta uma disciplina do BD""" self.carregarAluno(turma) if self.getAlunos() != None: for self.__i in self.getAlunos(): self.deleteAluno(self.__i) self.deleteHorario(turma) return DataBase.deleteTurma(turma)
def __init__(self, DataBase, attribList, tableList, conditionList): self.mFromTable = {} # ex. E : EMPLOYEE, but if no alias, it will EMPLOYEE : EMPLOYEE self.DB = DataBase self.mTable = DataBase.getTable() self.mattribList = attribList self.mtableList = tableList self.mconditionList = conditionList self.mresultTable = [] # use a list of dict to express the result table
def carregar(self, disciplina): """Carrega informacoes de uma disciplina do BD""" self.__result=DataBase.carregarDisciplina(disciplina) if self.__result == None: return False else: self.setDisciplina(disciplina) self.setProfessor(self.__result[1]) return True
def main(arg1, arg2): global similarities_list global user_input global country_name filename = "RawCorpus2.txt" create_corpus(filename) user_input = arg1 country_name = arg2 similarities_list = DataBase.get_data(country_name, user_input) if similarities_list: gen_colors(similarities_list) else: similarities_list = doc_similarity(user_input) DataBase.update_file(country_name, user_input, similarities_list) gen_colors(similarities_list)
def setData(self, data): apis = Api() database = DataBase() self.data = data gastenlijst = database.getGastLijst(data['titel'], apis.getCurrentTime()) if not gastenlijst: for cc in range(1, 4): geengasten = tk.Label(self, text='Geen gasten', font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) geengasten.grid(row=3, column=cc) else: for titels in gastenlijst: gasttitel = tk.Label(self, text=titels['film'], font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) gasttitel.grid(row=3, column=1) for namen in gastenlijst: naam_gast = tk.Label(self, text=namen['naam'], font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) naam_gast.grid(row=3, column=2) for mails in gastenlijst: mail_gast = tk.Label(self, text=mails['email'], font=FL_BASE_FONT, bg=FL_BG_COLOR, fg=FL_TEXT_COLOR) mail_gast.grid(row=3, column=3)
def carregar(self, login): """Carrega um login a partir do BD""" self.__result=DataBase.carregarLogin(login) if self.__result == None: return False else: self.setLogin(self.__result[0]) self.setSenha(self.__result[1]) self.setTipo(self.__result[2]) return True
def POST(self): form = myform() nuevousuario = registro() if (not form.validates() or not login(form.d.user,form.d.contrasena)) and (not hasattr(session, 'usuario')): cabecera = "<form name=\"main\" method=\"post\"> "+form.render()+"</form>" if not nuevousuario.validates(): formularioRegistro = "<form name=\"main\" method=\"post\"> "+nuevousuario.render()+"</form>" else: formularioRegistro="" DataBase.insertar(nuevousuario.d.nombre,nuevousuario.d.apellidos,nuevousuario.d.correo,nuevousuario.d.dianacimiento,nuevousuario.d.mesnacimiento, nuevousuario.d.anonacimiento,nuevousuario.d.direccion,nuevousuario.d.password,nuevousuario.d.visa,nuevousuario.d.formapago) DataBase.close() else: session.usuario = form.d.user cabecera = "Bienvenido "+session.usuario+" <a href=\"salir\">SALIR</a> <li><a href=\"modificar\">Modificar</a><li> " formularioRegistro="" addWeb("/") return render.index(form=cabecera,enlaces=session.get('enlaces'),registro=formularioRegistro)