async def new_chat_get_code(message, chat=None): lang = language(message.chat.id) if not chat: chat = int(message.text) if chat == message.chat.id: await message.reply(lang['warning_chat_with_yourself']) return existsQuery1 = "SELECT EXISTS (SELECT ID FROM users WHERE user_id=(%s))" existsQuery2 = "SELECT EXISTS (SELECT ID FROM chats WHERE (uid1=(%s) AND uid2=(%s) OR uid1=(%s) AND uid2=(%s)) AND active=1)" with DatabaseConnection() as db: conn, cursor = db cursor.execute(existsQuery1, [chat]) result1 = cursor.fetchone()[0] cursor.executemany(existsQuery2, [(message.chat.id, chat, chat, message.chat.id)]) result2 = cursor.fetchone()[0] if not result1: await message.reply(lang['warning_no_user_in_db']) return elif result2: await message.reply(lang['warning_chat_already_exists']) return insertQuery = "INSERT INTO chats (uid1, uid2) VALUES (%s, %s)" with DatabaseConnection() as db: conn, cursor = db cursor.executemany(insertQuery, [(message.chat.id, chat)]) conn.commit() with InformationSchemaConnection() as db: conn, cursor = db selectQuery = "SELECT `AUTO_INCREMENT` FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = (%s) AND TABLE_NAME = 'chats'" cursor.execute(selectQuery, [c.db]) ID = cursor.fetchone()[0] - 1 await message.answer(lang['chat_created'].format(ID, chat)) lang2 = language(chat) await _send_message(bot.send_message, chat_id=chat, text=lang2['chat_created_2'].format(ID, message.chat.id))
async def handle_text(message: types.Message, state: FSMContext): await state.finish() auth = await authentication(message) with open(c.strings_file, encoding='utf-8') as f: strings = json.load(f) if not auth: return False selectByIdQuery = "SELECT mail, pass FROM users WHERE user_id=(%s)" selectByFNQuery = "SELECT mail, pass FROM users WHERE f_name=(%s) AND l_name=(%s) GROUP BY stud_id" if message.forward_date: if not message.forward_from: await message.reply(strings[auth[mu.ResTypes.LANG]]['user_hidden']) return user_id = message.forward_from.id with DatabaseConnection() as db: conn, cursor = db cursor.execute(selectByIdQuery, [user_id]) result = cursor.fetchall() else: if not message.text: await message.reply(strings[auth[mu.ResTypes.LANG]]['wrong_format'] ) return if message.text in buttons_ua_1 + buttons_ua_2 + buttons_ru_1 + buttons_ru_2: await message.reply(strings[auth[mu.ResTypes.LANG]]['wrong_format'] ) return try: message.text.encode('utf-8') except UnicodeError: await message.reply(strings[auth[mu.ResTypes.LANG]]['wrong_format'] ) return s = message.text.replace('`', "'").split() if len(s) != 2: await message.reply(strings[auth[mu.ResTypes.LANG]]['wrong_format'] ) return with DatabaseConnection() as db: conn, cursor = db cursor.executemany(selectByFNQuery, [(s[0].capitalize(), s[1].capitalize())]) result = cursor.fetchall() if not result: await message.reply(strings[auth[mu.ResTypes.LANG]]['not_found']) return for res in result: answer = await api_request(message, email=res[0], passwd=res[1], page=1) if answer is None: continue if not answer: await message.reply(strings[auth[mu.ResTypes.LANG]]['not_found']) continue main_page = strings[auth[mu.ResTypes.LANG]]['page_1'].format( **answer[0]).replace("`", "'") await message.reply(main_page, parse_mode='Markdown') await sleep(.05)
def execute_task5(request): l = int(request.POST.get('number_of_layers')) k = int(request.POST.get('number_of_hashes_per_layer')) lsh = LSH(k=k, l=l) dbconnection = DatabaseConnection() if read_from_pickle('all_img_features_LSH.pickle') != None: all_image_hog_features = read_from_pickle('all_img_features_LSH.pickle') else: all_image_hog_features = dbconnection.get_object_feature_matrix_from_db(tablename='histogram_of_gradients') save_to_pickle(all_image_hog_features,'all_img_features_LSH.pickle') #SVD on hog features if(read_from_pickle('svd_hog_lsh.pickle')!=None): svd_obj = read_from_pickle('svd_hog_lsh.pickle') transformed_data = svd_obj['data_matrix'] vt = svd_obj['vt'] else: svd = SingularValueDecomposition() transformed_data,vt = svd.get_transformed_data_copy(all_image_hog_features['data_matrix'],400) save_to_pickle({"data_matrix":transformed_data,"images":all_image_hog_features['images'],"vt":vt},'svd_hog_lsh.pickle') # index_of_query_image = (all_image_hog_features['images']).index(query_image) # image_vector = transformed_data[index_of_query_image] bit_map = lsh.generate_representation_for_all_layers(transformed_data,all_image_hog_features['images']) save_to_pickle(lsh, 'lsh_model') return render(request, 'task5a_output.html')
def fetch_password(): username = input("Enter username to fetch from") with DatabaseConnection("data.db") as connection: cursor = connection.cursor() cursor.execute('SELECT * FROM validation WHERE username=?', (username, )) return [row for row in cursor.fetchall()]
def create_table(self): with DatabaseConnection(self.categories_database) as connection: cursor = connection.cursor() cursor.execute( 'CREATE TABLE IF NOT EXISTS categories(name text primary key, total real)' )
def quick_pay(self, name): with DatabaseConnection(self.bills_db) as connection: cursor = connection.cursor() try: cursor.execute('SELECT remaining FROM bills WHERE name=?', (name, )) # finish quick pay method bill_remaining = cursor.fetchone()[0] cursor.execute('SELECT payment FROM bills WHERE name=?', (name, )) bill_payment = cursor.fetchone()[0] cursor.execute('SELECT paid FROM bills WHERE name=?', (name, )) bill_paid = cursor.fetchone()[0] except TypeError: print('!! Invalid Query !!') return else: self._write_payment_log(name, bill_payment) bill_remaining -= bill_payment if bill_remaining <= 0: cursor.execute('UPDATE bills SET complete=? WHERE name=?', (1, name)) self.logger.info(f'{name.title()} PAID IN FULL') else: bill_paid += bill_payment cursor.execute('UPDATE bills SET remaining=? WHERE name=?', (bill_remaining, name)) cursor.execute('UPDATE bills SET paid=? WHERE name=?', (bill_paid, name))
def make_payment(self, name, amount): with DatabaseConnection(self.bills_db) as connection: cursor = connection.cursor() try: cursor.execute('SELECT remaining FROM bills WHERE name=?', (name, )) expense_remaining = cursor.fetchone()[0] cursor.execute('SELECT paid FROM bills WHERE name=?', (name, )) expense_paid = cursor.fetchone()[0] except TypeError: print('!! Invalid Query !!') return else: self._write_payment_log(name, amount) expense_remaining -= amount if expense_remaining <= 0: cursor.execute('UPDATE bills SET complete=? WHERE name=?', (1, name)) self.logger.info(f'{name.title()} PAID IN FULL') else: expense_paid += amount cursor.execute('UPDATE bills SET remaining=? WHERE name=?', (expense_remaining, name)) cursor.execute('UPDATE bills SET paid=? WHERE name=?', (expense_paid, name)) cursor.execute('UPDATE bills SET payment=? WHERE name=?', (amount, name))
async def handle_text(message: types.Message, state: FSMContext): await state.finish() if message.text == "/exit": await message.answer("Отменено") return try: test = await message.answer(message.text, parse_mode='Markdown') except exceptions.CantParseEntities: await message.answer("Неверный формат Markdown!") return await bot.delete_message(message.chat.id, test.message_id) selectQuery = "SELECT user_id FROM users" with DatabaseConnection() as db: conn, cursor = db cursor.execute(selectQuery) users = cursor.fetchall() i = 0 j = 0 len_users = len(users) progress_message = (await message.answer(f'0/{len_users}')).message_id for n, user in enumerate(users, 1): if await mu.send_message(bot.send_message, exceptions, chat_id=user[0], text=message.text, parse_mode='Markdown'): i += 1 else: j += 1 await bot.edit_message_text(f'{n}/{len_users}', message.chat.id, progress_message) await sleep(.1) await message.answer(f"Отправлено: {i}\nНе отправлено: {j}")
def current_database_lookup_headers(self): dbconn = DatabaseConnection(dbconnection_string, self.rin, self.delimiter) dbconn.connect() rpt_general = dbconn.rpt_general() rpt_file = dbconn.rpt_file() rpt_file = rpt_file.reset_index(drop=True) filetype = rpt_file.FILETYPE[0] version_db = rpt_general[5] date_db = rpt_general[1] tenement_db = rpt_general[0] holder_db = rpt_general[6] project_db = rpt_general[7] sample_count_db = rpt_general[3] ss_file_count_db = len(rpt_file) print ('sample_count_db: ', sample_count_db) print ('ss_file_count_db: ', ss_file_count_db) db_corrected_headers = [ self.delimiter.join(['H0002','Version',str(version_db)]), self.delimiter.join(['H0004','Reporting end date',str(date_db)]), self.delimiter.join(['H0100','Tenement_ID',str(tenement_db)]), self.delimiter.join(['H0101','Tenement_holder',str(holder_db)]), self.delimiter.join(['H0102','Project_name',str(project_db)]), self.delimiter.join(['H0202','Template_format',str(filetype)]) ] return db_corrected_headers
def reset(): try: with DatabaseConnection('categories.db') as connection: cursor = connection.cursor() cursor.execute('DROP TABLE categories') except OperationalError: pass
def make_payment(self, oid, amount): with DatabaseConnection(self.bills_db) as connection: cursor = connection.cursor() try: cursor.execute('SELECT remaining FROM bills WHERE oid=?', (oid, )) expense_remaining = cursor.fetchone()[0] cursor.execute('SELECT paid FROM bills WHERE oid=?', (oid, )) expense_paid = cursor.fetchone()[0] cursor.execute('SELECT name FROM bills WHERE oid=?', (oid, )) name = cursor.fetchone()[0] except TypeError: messagebox.showerror( title='Invalid Selection', message= 'You have made an invalid selection. Please select again') return None else: self._write_payment_log(name, amount) expense_remaining -= amount if expense_remaining <= 0: cursor.execute('UPDATE bills SET complete=? WHERE oid=?', (1, oid)) self.logger.info(f'{name.title()} PAID IN FULL') else: expense_paid += amount cursor.execute('UPDATE bills SET remaining=? WHERE oid=?', (expense_remaining, oid)) cursor.execute('UPDATE bills SET paid=? WHERE oid=?', (expense_paid, oid)) cursor.execute('UPDATE bills SET payment=? WHERE oid=?', (amount, oid)) return 1
def create_table(self): with DatabaseConnection(self.bills_db) as connection: cursor = connection.cursor() cursor.execute( "CREATE TABLE IF NOT EXISTS bills(name text primary key, total real, payment real, " "remaining real, paid real, complete BIT)")
async def message_handler(message: types.Message, state: FSMContext): await state.finish() if message.text == Buttons.back: await message.answer("Canceled", reply_markup=moderator_keyboard()) return code: str = message.text.lower() selectChatQuery = "SELECT ID FROM chats WHERE code=(%s)" selectMediaQuery = "SELECT type, file_id FROM media_messages WHERE chat=(%s)" selectTextQuery = "SELECT user, time, text FROM text_messages WHERE chat=(%s)" text, media = None, None with DatabaseConnection() as db: conn, cursor = db cursor.execute(selectChatQuery, [code]) chat_id = cursor.fetchone() if chat_id: cursor.execute(selectMediaQuery, [chat_id[0]]) media = cursor.fetchall() cursor.execute(selectTextQuery, [chat_id[0]]) text = cursor.fetchall() if not chat_id: await message.answer("Chat does not exist!", reply_markup=moderator_keyboard()) return if not text: await message.answer("There are no text messages") else: buffer = '' for t in text: user, time, text = t[0], t[1], t[2] buffer += f'{datetime.datetime.strftime(time, "%d.%m / %H:%M")} - {user}:\n{text}\n\n' with open(code, 'wt', encoding='utf-8') as f: f.write(buffer) del buffer await bot.send_document( message.chat.id, types.InputFile(code, f'{code} text messages.txt')) try: os.remove(code) except Exception as e: print(e) if not media: await message.answer("There are no media messages") else: for m in media: filetype, fileid = m[0], m[1] try: if filetype == c.PHOTO: await bot.send_photo(message.chat.id, fileid) elif filetype == c.VIDEO: await bot.send_video(message.chat.id, fileid) elif filetype == c.DOCUMENT: await bot.send_document(message.chat.id, fileid) except Exception as e: await message.answer(str(e)) await sleep(.05) await message.answer("Sending finished", reply_markup=moderator_keyboard())
def save_data(chat: int, name: str, text: str = None, data_type: str = None, data: str = None): insertTextQuery = "INSERT INTO text_messages (chat, user, text) VALUES (%s, %s, %s)" insertMediaQuery = "INSERT INTO media_messages (chat, type, file_id) VALUES (%s, %s, %s)" if text: with DatabaseConnection() as db: conn, cursor = db cursor.executemany(insertTextQuery, [(chat, name, text)]) conn.commit() if data: with DatabaseConnection() as db: conn, cursor = db cursor.executemany(insertMediaQuery, [(chat, data_type, data)]) conn.commit()
def __init__(self): # connect to database self.db = DatabaseConnection() self.db_connect = self.db.connect_database() # create a Cursor() method from established database connection self.cur = self.db_connect.cursor()
def __db_is_item_available(self, id): with DatabaseConnection() as db: inv, _ = db.get_table("available_items") q = db.query().\ add_columns(inv).\ filter(inv.c.id == id) db.execute(q) return len([r for r in db.fetchall()]) > 0
def __db_approve(self, id, approver): with DatabaseConnection() as db: co, _ = db.get_table("checked_out") q = co.update().\ where(co.c.id == id).\ values(approved_by=approver) db.execute(q) return
def __db_insert_competition(self, data): with DatabaseConnection() as db: comps, _ = db.get_table("competition") q = comps.insert().\ values( id=data['id'], documentation=data['documentation'], location=data['location']) db.execute(q)
def __db_insert_meeting(self, data): with DatabaseConnection() as db: mts, _ = db.get_table("meeting") q = mts.insert().\ values( id=data['id'], minutes=data['minutes'], required=data['required']) db.execute(q)
def add_username_password(): hashed_password = bcrypt.hashpw( input("Enter your password").encode("utf-8"), bcrypt.gensalt()) username = input("Enter your username") print(hashed_password) with DatabaseConnection("data.db") as connection: cursor = connection.cursor() cursor.execute('INSERT INTO validation VALUES(?,?)', (username, hashed_password))
def __db_get_others(self): with DatabaseConnection() as db: others, _ = db.get_table("not_students") q = db.query().add_columns(others) db.execute(q) rows = [ self.encode_id(dict(r), 'not_students_id') for r in db.fetchall() ] return rows
def __db_get_officers(self, current_only=False): with DatabaseConnection() as db: offs, _ = db.get_table("officers") if current_only else \ db.get_table("all_officers") q = db.query().add_columns(offs) db.execute(q) rows = [ self.encode_id(dict(r), 'officers_id') for r in db.fetchall() ] return rows
def __db_get_unregistered_people(self, search_email=None): with DatabaseConnection() as db: ppl, _ = db.get_table("people_read") q = db.query().add_columns(ppl.c.id, ppl.c.email).\ filter(ppl.c.password == None) if search_email: q = q.filter(ppl.c.email == search_email) db.execute(q) rows = [r for r in db.fetchall()] return rows
def __db_insert_request(self, data): with DatabaseConnection() as db: co, _ = db.get_table("checked_out") q = co.insert().\ values( item_id=data['item_id'], requested_by=data['person_id'], start_date=data['start_date'], expected_return_date=data['end_date']) db.execute(q)
def __db_get_positions(self): with DatabaseConnection() as db: positions, _ = db.get_table("position") q = db.query().\ add_columns( positions.c.pos_id, positions.c.person_id, positions.c.title, positions.c.start_date, positions.c.end_date) db.execute(q) positions = [ self.encode_id(dict(row), 'position_id') for row in db.fetchall() ] return positions[::-1]
def __db_get_inventory(self): with DatabaseConnection() as db: inv, _ = db.get_table("inventory") q = db.query().\ add_columns( inv.c.id, inv.c.description, inv.c.serial_number, inv.c.make, inv.c.model, inv.c.manufacturer, inv.c.location, inv.c.other_notes) db.execute(q) return [self.encode_id(dict(row), 'inventory_id') for row in db.fetchall()]
def __db_get_item(self, id): with DatabaseConnection() as db: inv, _ = db.get_table("inventory") q = db.query().add_columns(inv).filter(inv.c.id == id) db.execute(q) rows = [self.encode_id(dict(row), 'inventory_id') for row in db.fetchall()] if len(rows) != 1: return None return rows[0]
def _add_expense(self, name, amount): bill = self._get_bill(name) bill_remaining = bill['remaining'] bill_remaining += amount with DatabaseConnection(self.bills_db) as connection: cursor = connection.cursor() cursor.execute('UPDATE bills SET remaining=? WHERE name=?', (bill_remaining, name))
def read_from_file(): with DatabaseConnection('data.db') as connection: cursor = connection.cursor() cursor.execute('SELECT * FROM BOOKS') books = [{ 'name': row[0], 'author': row[1], 'read': row[2] } for row in cursor.fetchall()] print(books) return books
def __db_insert_student(self, data): with DatabaseConnection() as db: std, _ = db.get_table("students") q = std.insert().\ values( id=data['id'], eid=data['eid'], year=data['year'], major=data['major'], voting_member=data['voting_member']) db.execute(q)