def new_subscription(bot, update): lang = update.callback_query.from_user.language_code[:2] lang = 'en' if lang != 'es' else lang service = TvmazeService() query = update.callback_query user_id = update.callback_query.from_user.id serie_id = query['data'] if 'baja' in serie_id: serie_baja = serie_id.split('baja') serie_id = int(serie_baja[1]) search = database.search(user_id, serie_id) if search: remove = database.remove_register(user_id, serie_id) if remove: text = translations['remove_subscription'][lang] else: text = 'ERROR' else: serie_id = int(serie_id) serie = service._next_episode(serie_id) serie_name = serie['name'] search = database.search(user_id, serie_id) if not search: register = database.insert_register(user_id, serie_id, update.effective_chat.id, serie_name) if register: text = translations['new_subscription'][lang].format( serie=serie_name) else: text = 'ERROR' else: text = translations['already_subscribed'][lang] bot.answerCallbackQuery(query.id, text=text)
def execute_program(HMMER=False, filter=True, score_threshold=False): """ Executes the program and creates a gene list. This function is used if this is the first time executing the progam. This fuction creates a gene list and stores all of the relevant information from a variety of databases and HMMER output. Parameter HMMER: says whether to create a new HMMER file. Preconditon: HMMER is a bool Parameter filter: says whether to filter out other proteins except the longest transcript Preconditon: filter is a bool Parameter score_threshold: says whether to get only output proteins with a score above 17.7 Preconditon: score_threshold is a bool """ data = genetics.hmmer_output(create_new=HMMER) full_dict_proteins = genetics.Protein.full_protein_dict() protein_list = genetics.Protein.create_protein_set(data) gene_list = genetics.Gene.create_gene_list(protein_list, full_dict_proteins) genetics.Protein.get_zf_protein_info(data, gene_list) genetics.Protein.gene_list_set_sequence(gene_list, full_dict_proteins) database.search(gene_list) database.search_mutation_info(gene_list) genetics.Protein.remove_proteins(gene_list, score_threshold) output.info(gene_list, create_txt=True, create_tab=True, create_chart=True, create_tab_dis=True)
def run_query_performance_analysis(columns): query_times = [] for query_file in sorted(glob(f"{ANNOTATION_CACHE}/*query.txt")): with open(query_file, "r") as f: query_str = f.readlines()[0].strip().split(" ")[0] formatted_query = query_str.replace("oxc1_", "") + ".jpg" img_file = os.path.join(OXFORD_CACHE, formatted_query) start = time.time() database.search(DATABASE_DIR, columns, num_results=10, query=Image.open(img_file)) taken = time.time() - start query_times.append(taken) return query_times
def queryModel(): userName = request.json["userName"] password = request.json["password"] modelName = request.json["modelName"] #Authentication userId = authentication(userName, password) if userId == -1: return jsonify({"status": -1, "info": "authentication failed"}) userId = str(userId) sql = "select * from model where userId=" + userId + " and modelName=" + "\"" + modelName + "\"" result = database.search(mysql_host, mysql_user, mysql_password, "datastudio", sql) if len(result) == 0: return jsonify({ "status": -1, "info": "model: " + modelName + " does not exist" }) info = {} info["modelName"] = result[0][1] info["algoName"] = result[0][2] info["status"] = result[0][3] info["time"] = result[0][5] info["algoPara"] = eval(result[0][6]) info["createTime"] = result[0][7] info["datasetName"] = result[0][8] return jsonify(info)
def lookup(): if request.args['contestid'] is None: return jsonify({}) if request.args['index'] is None: return jsonify({}) return search(request.args['contestid'], request.args['index'], gen_id(request.args['contestid'], request.args['index']))
def test_search_database(): fields = dict(name=u'', lastname=u'', age='', dx=u'sac', assistance=u'', test=u'') meta, data = database.search(dbpath, **fields) assert len(meta) == 1 assert len(data) == 4 fields = dict(name=u'', lastname=u'', age='25-35', dx=u'', assistance=u'', test=u'') meta, data = database.search(dbpath, **fields) assert len(meta) == 1 assert len(data) == 4 fields = dict(name=u'', lastname=u'', age='', dx=u'', assistance=u'', test=u'') database.search(dbpath, **fields)
def search(): if request.method == 'POST': imgs = db.search(request.form['serch']) if 'username' in session: user = session['username'] insess = True else: user = '' insess = False return render_template('index.html', sess=insess, imgs=imgs)
def f_search(): if session.get("user"): search_dict = {} search_dict["min_storage"] = request.args.get("min_storage", "", type=str) search_dict["max_storage"] = request.args.get("max_storage", "", type=str) search_dict["min_memory"] = request.args.get("min_memory", "", type=str) search_dict["rec_memory"] = request.args.get("max_memory", "", type=str) search_dict["min_os"] = request.args.get("min_os", "", type=str) search_dict["rec_os"] = request.args.get("rec_os", "", type=str) search_dict["min_graphics"] = request.args.get("min_graphics", "", type=str) search_dict["rec_graphics"] = request.args.get("rec_graphics", "", type=str) search_dict["min_processor"] = request.args.get("min_processor", "", type=str) search_dict["rec_processor"] = request.args.get("rec_processor", "", type=str) search_dict["min_price"] = request.args.get("min_price", "", type=str) search_dict["max_price"] = request.args.get("max_price", "", type=str) search_dict["min_directX"] = request.args.get("min_directX", "", type=str) search_dict["rec_directX"] = request.args.get("rec_directX", "", type=str) search_dict["min_discount"] = request.args.get("min_discount", "", type=str) search_dict["max_discount"] = request.args.get("max_discount", "", type=str) search_dict["min_reviews"] = request.args.get("min_reviews", "", type=str) search_dict["max_reviews"] = request.args.get("max_reviews", "", type=str) search_dict["min_statics"] = request.args.get("min_statics", "", type=str) search_dict["max_statics"] = request.args.get("max_statics", "", type=str) search_dict["min_overall"] = request.args.get("min_overall", "", type=str) search_dict["max_overall"] = request.args.get("max_overall", "", type=str) search_dict["genre"] = request.args.get("genre", "", type=str) search_dict["word"] = request.args.get("word", "", type=str) search_dict["min_release_date"] = request.args.get("min_release_date", "", type=str) search_dict["max_release_date"] = request.args.get("max_release_date", "", type=str) print "123" if search(search_dict, "0"): stup = list(search(search_dict, "0")) slis = [list(i) for i in stup] for item in slis: item[2] = str(item[2]) item[3] = str(item[3]) if "Publisher" in item[3]: d = item[3].index("Publisher") item[3] = item[3][:d] return json.dumps(slis) return "0" return redirect(url_for("f_home"))
def retrieve(index): caption = annotations[index // 5]["sentences"][index % 5]["raw"] results = database.search(db_dir, columns=columns, num_results=25, query=caption) image_file = img_dir + annotations[index // 5]["filename"] try: return results.index(image_file) except ValueError: return len(results)
def searchModel01(userId, modelName): sql = "select modelPath from model where userId="+ \ userId+" and modelName="+"\""+modelName+"\"" result = database.search(mysql_host, mysql_user, mysql_password, "deeplearn", sql) if len(result) == 0: return "" modelPath = result[0][0] return modelPath
def main(): if request.method == 'GET': pets = database.get() model = {"title": "Awesome Pet Photos", "header": "Photos", "pets": pets} print('Pets Home Page Requested!') if request.method == 'POST': data = request.form.to_dict(flat=True) pets = database.search(data['search']) model = {"title": "Awesome Pet Photos", "header": "Some Pets!", "pets": pets} print('Search Requested: ' + data['search']) return render_template('index.html', model=model)
def searchDataset(userId, dataset): sql = "select dataPath from dataset where userId="+ \ userId+" and datasetName="+"\""+dataset+"\"" result = database.search(mysql_host, mysql_user, mysql_password, "datastudio", sql) if len(result) == 0: return "" dataPath = result[0][0] return dataPath
def suggests(): for res in list(database.view()): word_row = str(res) new = "" word_row_indexed = word_row.rindex('\'', 1) words_list.append(word_row[2:word_row_indexed]) sug = get_close_matches(word.get(), words_list, n=1) entry2.delete(0, END) entry2.insert(END, sug) list1.delete(0, END) for x in sug: new += x for res in database.search(new): list1.insert(END, res)
def find_ads(session, page_num, homeurl): """Find ads from page_num pages from given url First checks if url exists in database ads Returns a list of pages where each page is a list of AdTuple objects """ links_articles = [] for number in xrange(page_num): url = create_url(homeurl, number) ads = database.search(session, url) if ads: links_articles += ads.data else: links_articles += yield fetch_from_url_and_store(session, url) raise gen.Return(links_articles)
def find(message, code: int): object_list = users[message.chat.id].list_of_object_to_search object_titles = db.search( message.text.split(", ")[0], [ get_property(object_list[i], code) for i in range(0, len(object_list)) ]) if len(object_titles) == 1: for object in object_list: if get_property(object, code) == object_titles[0]: return [object] elif len(object_titles) == 0: return list() else: return object_titles
def authentication(user, passwd): sql = "select userId,password from user where userName="******"\"" + user + "\"" result = database.search(mysql_host, mysql_user, mysql_password, "datastudio", sql) if len(result) == 0: return -1 password = result[0][1] userId = result[0][0] if passwd == password: return userId else: return -1
def do_GET(self): path = cleanPath(self.path) print("Got request - " + path) body = {} if path.startswith("/course/"): body = database.getCourse(path[8:]) elif path.startswith("/search/"): body = database.search(path[8:]) self.send_response(200) self.send_header('Content-type','text/html') self.send_header("Access-Control-Allow-Origin", "*") self.end_headers() # Send the html message self.wfile.write(bytes(json.dumps(body))) return
def echo(bot, update): uid = update.message.from_user message_dict = update.message.to_dict() event_name = update.message.text botan.track(config.BOTAN_TOKEN, uid, message_dict, event_name) lang = update.message.from_user.language_code[:2] lang = 'en' if lang != 'es' else lang service = TvmazeService() text = '' serie = service.next_episode(update.message.text) serie_active = False reply_markup = None if serie: serie_active = True if serie['status'] != 'Ended' else False if lang == 'es': serie['status'] = translations[serie['status']][lang] text += translations['title'][lang].format(name=serie['name'], status=serie['status']) next_episode = serie.get('next', None) previous_episode = serie.get('previous', None) text = print_episode(text, previous_episode, lang, 'last_episode') if next_episode: text = print_episode(text, next_episode, lang, 'next_episode') else: if serie_active: text += translations['serie_active'][lang] else: text += "Not found." if serie_active: search = database.search(update.message.from_user.id, serie['id']) if not search: button_list = [[ telegram.InlineKeyboardButton( text=translations['subscribe'][lang], callback_data=str(serie['id'])), ]] else: button_list = [[ telegram.InlineKeyboardButton( text=translations['unsubscribe'][lang], callback_data=str('baja' + str(serie['id']))), ]] reply_markup = telegram.InlineKeyboardMarkup(button_list) bot.send_message(chat_id=update.message.chat_id, text=text, reply_markup=reply_markup, parse_mode=telegram.ParseMode.HTML)
def main_menu(): """Main menu for the knowledge base""" while True: print("*** Knowledge Base menu") print("1. Search") print("2. Add entry") print("3. Show all entries") print("4. Show all notes") print() option = input("Choose your option, empty to exit: ").strip() if option == '1': keyword = input("Search keyword: ") if len(keyword) > 0: entries = db.search(conn, keyword) print_entries(entries) if len(entries) > 0: entry_id = choose_entry(len(entries)) if entry_id != 0: entry, notes = db.get_entry(conn, entry_id) print_entry(entry) print_notes(notes) entry_actions(entry_id) else: print("\nInvalid entry!\n") elif option == '2': add_entry() elif option == '3': entries = db.get_all_entries(conn) print("Displaying all KB entries...") print_entries(entries) elif option == '4': notes = db.get_all_notes(conn) print("Displaying all notes...") print_entries(notes) elif option == '': print("\nGoodbye!\n") break else: print("\nInvalid option!\n")
def pkSearch(self, package): resp = [] for repo in repos: resp = database.search().search(repo, package) if resp: break for pkg in self.findInAur(package): resp.append(pkg) if not resp: msg = "NO EXISTE EL PAQUETE, QUE QUIERES QUE TE LO CREE TAMBIEN" else: msg = (" || ").join(resp[:12]) if len(resp) > 12: msg += " 01***SERE UN BOT PERO NO IDIOTA. SE MAS ESPECÍFIC@ QUE HAY MÁS DE 12 RESULTADOS***" self.bot.sendtext( msg, True)
def search(self, event): searchText = self.master.entry.get() if searchText != "": self.master.treeview.delete(*self.master.treeview.get_children()) results = database.search(searchText) count = 1 for data in results: if count % 2 == 0: tag = "even" else: tag = "odd" self.master.treeview.insert('', 'end', text=count, values=(data[1], data[2], data[3], data[4], data[5], data[6], data[7], data[8]), tags=tag) count += 1
def user(): try: b = database.search(titletext.get()) c = b[0] #print(c) d = database.view1() e = d[0] #print(e) database.delete() if c[0] == titletext1.get() or c[1] == e[0]: root.destroy() welcome.wel() else: messagebox.askretrycancel( "login error", "pls check your user id and password") except: b = messagebox.showwarning( "warning", "pls confirm your face , user id and password") if b == "ok": root.destroy()
def query(query_sequence): """Encodes a query and searches for it in the data base. Args: query: A genetic sequence (string) to be searched for. Returns: The 'Gene' that is the 'best match' to the query. The IOU for the 'best match' and the query. """ print("encoding query...") query = encode(query_sequence) print("...query complete") print("performing search...") gene, iou = database.search(query) print("...search complete \n") return gene, iou
async def search(request): try: request_body = request.json except Exception as e: return error(TMVException.ID_PARSE_JSON, 'Couldn\'t parse request body as JSON') try: verify_input(request_body, [{ 'name': 'query', 'required': True, 'type': 'str[]', 'empty': False }]) result = database.search(request_body['query']) return json({'response': result}) except TMVException as e: return error(e.error_id, e.error_msg) except Exception as e: return unknown_error(e)
def browse(): search = request.args.get(key='search', default=None, type=str) query = request.args.get(key='query', default=None, type=str) page = request.args.get(key="page", default=1, type=int) sort = request.args.get(key="sort", default=None, type=str) if search is None: return render_template("browse.j2", has_result=False) if search == 'isbn': item_id = database.getStoreItemIDByISBN(query) if item_id is None: return render_template( "browse.j2", has_error=True, error="Whoops! We do not have any books with the isbn: %s" % (query)) else: return redirect(url_for('item_details', item_id=item_id)) else: #this search can be handled by paged_query items, is_next_page = database.search(search, query, page, sort) if len(items) == 1: return redirect(url_for('item_details', item_id=items[0].id)) elif len(items) == 0: return render_template( "browse.j2", has_error=True, error="Whoops! No books found for the query %s" % (query)) else: return render_template("browse.j2", has_result=True, items=items, page=page, sort=sort, is_next_page=is_next_page, query=query, search=search) return render_template("browse.j2", has_result=False)
def buttonPress( status): # Will run this script everytime the button is pressed minimum = database.search("internet", "id=(SELECT MIN(id) FROM internet)") minimum = int(minimum[5]) - 1 if minimum == 0: minimum = -1 if status: writeLog("Internet Schedule changed to off due to button", 5) database.appendValue( "internet", ["0", "0", "23", "59", str(time.time() + 3600), str(minimum)], ) else: writeLog("Internet Schedule changed to on due to button", 5) database.appendValue( "internet", ["2", "1", "2", "1", str(time.time() + 3600), str(minimum)])
def search(): error = "" isError=False if request.method == "POST": #location = request.form['query'] #response = database.search(location) zipcode = request.form['zipcode'] keywords = request.form['keyword'] if zipcode == "" and keywords == "": error = "You forgot to enter values!" isError=True return render_template("results.html", error=error, isError=isError) if keywords != None: keywords = keywords.split() response = database.search(keywords, zipcode) #print '~~~~~~~~~~~~~~~~~~~~~' #print response if response != []: sortedlocs = database.sort_votes(response) return render_template("results.html", session=session, users=users, locations=sortedlocs, get_timestamp=get_timestamp, get_votes=database.get_votes_pst, isError=isError) else: error = "There aren't any Bizcuits in this location yet." isError=True return render_template("results.html", error=error, isError=isError)
any(col in index for index in glob(db_dir + "/*.index")) for col in column_set ] if not all(indices_exist): database.insert( db_dir=db_dir, img_dir=img_dir, columns=[ col for col, exist in zip(column_set, indices_exist) if not exist ], num_workers=4, ) aps = [] for query in tqdm(sorted(glob(f"{annot_dir}/*query.txt"))): with open(query, "r") as f: file_str = f.readlines()[0].strip().split(" ")[0] img_file = img_dir + "/" + file_str.replace("oxc1_", "") + ".jpg" results = database.search(db_dir, column_set, num_results=25, query=Image.open(img_file)) ap = compute_ap(results, query) aps.append(ap) print( f"average precision: \t\t min = {np.min(aps):.3f} \t\t median = {np.median(aps):.3f} \t\t mean = {np.mean(aps):.3f} \t\t max = {np.max(aps):.3f}" )
writeFile(location + "data.json", info) if lastBackup != callTime()[1]: try: f = open(location + "maintenance-mode", "w") f.close() if developmentMachine: writeLog("Doing fake backup", 9) else: database.backUp("/var/lib/mysql", "/backup/main", False) database.backUp("/var/lib/mysql", "/backup/reserve", False) except: writeLog("Database backup failed", 9) os.remove(location + "maintenance-mode") lastBackup = callTime()[1] try: minimum = database.search("internet", "id=(SELECT MIN(id) FROM internet)") if not minimum: database.appendValue("internet", internetOnDeafult) minimum = internetOnDeafult writeLog("No internet schedule found creating a new one", 8) while int(minimum[4]) < time.time(): oldMinimum = minimum database.delete("internet", f"id={minimum[5]}") minimum = database.search("internet", "id=(SELECT MIN(id) FROM internet)") if not minimum: database.appendValue("internet", internetOnDeafult) minimum = internetOnDeafult writeLog( f"Changing internet schedule from; {oldMinimum[0]}:{oldMinimum[1]} to {oldMinimum[2]}:{oldMinimum[3]}, to {minimum[0]}:{minimum[1]} to {minimum[2]}:{minimum[3]}", 8,
def search_specific_data(): database_list.delete(0, tk.END) for row in database.search(name.get(), blood_group.get(), city.get(), contact.get()): database_list.insert(tk.END, row)
def search_command(): list.delete(0, END) for row in database.search(date_text.get(), earning_text.get(), exercise_text.get(), study_text.get(), diet_text.get(), python_text.get()): list.insert(END, row)
def searchcommand(): list1.delete(0, END) rows = database.search(title.get(), Author.get(), Year.get(), isbn.get()) for row in rows: list1.insert(END, row)
elif mark == "all": database.update_all_marks() input("Enter to continue......") else: print("Invalid option, try again") # choice 4 data presentation elif choice.lower() == "students": database.table() input("Enter to continue....") # choice 5 searching elif choice.lower() == "search": stud = input("Enter Student number: ") database.search(stud) input("Enter to continue....") elif choice.lower() == "graph": graph.graph() input("Enter to continue....") elif choice.lower() == "visual": stud = eval(input("Enter student number: ")) graph.student_average(stud) input("Enter to continue....") elif choice == "quit": print(""" Are sure yo want to exit: No
def search(query): if not query: return '' # @TODO regex this result = database.search(query) return result