def change_pass(self): """Change user password """ print("reg") print(self.__old_password_box.get()) print(self.__new_password_box.get()) print(self.__new_again_password.get()) print("okok") print(self.__new_password_box.get()) print(len(self.__new_password_box.get())) if (len(self.__new_password_box.get()) != 0 and len(self.__old_password_box.get()) != 0 and len(self.__new_again_password.get()) != 0): print("no empty") if db.check_pass(self.conn, self.__old_password_box.get()) is True: print("check pass aprove") if self.__new_password_box.get( ) == self.__new_again_password.get(): print("change") change_pass = (self.__new_password_box.get(), self.user_id) db.change_password(self.conn, change_pass) else: print("Hesla se neshodují") messagebox.showwarning("Chyba hesla!", "Hesla se neshodují!") else: print("Špatně zadané staré heslo") messagebox.showwarning("Chyba hesla!", "Špatně zadané staré heslo!") else: print("Hesla nesmí být prázdné") messagebox.showwarning("Chyba hesla!", "Hesla nesmí být prázdné!")
def update_user(self, new_email, new_password=None): Database.update(constants.USER_COLLECTION, {"email": self.email}, { "$set": { "email": new_email if new_email else self.email, "password": new_password if new_password else self.password } })
def __btn_update_event(self): """Button event - update user presence in listbox """ user_years: list = self.get_update_month_cb self.__cb_year["values"] = user_years print("__btn_update_event") print(self.user_id) self.clear() year: str = self.get_year month: str = self.get_month # print("mm: " + str(month)) p_rows: list = db.select_presence_by_user_id(self.__conn, self.user_id, year, month) for x in p_rows: print("jeje") print(x[1]) data_entry = "{0} :: {1} - ".format(helper.Validation.date_convert(x[3]), helper.Validation.time_covert(x[1])) if x[2] is None: # print("none") # print(x[2]) data_entry += "xx:xx" else: data_entry += helper.Validation.time_covert(x[2]) # print(datetime.strptime(helper.Validation.time_covert(x[2]), format) - datetime.strptime(helper.Validation.time_covert(x[1]), format)) data_entry += " > " + str(helper.Validation.number_of_hours(x[2], x[1])) self.__lb_data.insert(END, data_entry) self.__lb_time["text"] = self.__default_time + db.select_user_time(self.__conn, self.user_id, year, month) self.__lb_wage["text"] = self.__default_wage + db.select_user_wage(self.__conn, self.user_id, year, month) self.__lb_days["text"] = self.__default_days + str( db.select_user_day_count(self.__conn, self.user_id, year, month))
def __update_presence(conn, data): """Update a presence Args: conn: connection object data: presence data """ for item in data: print(item) pr2 = (item['timeIn'], item['timeOut'], item['userId'], item['id']) db.update_presence(conn, pr2)
def query(settings_path): from src import Database, load_settings conf = load_settings(settings_path) db = Database(**conf["db_settings"]) sql = f"""SELECT * FROM {db.table_name} LIMIT 1""" c = db.get_cursor() res = c.execute(sql).fetchall() c.close() print(res)
def login_user(self): """Login user """ name = self.username_box.get() password = self.password_box.get() # login_completed = self.login_completed.get() # AUTO DATA PRO TESTOVÁNÍ # name = "dom53" # password = "******" conn = db.create_connection() # us = db.select_user_by_id(conn, 1) # row = db.select_user_by_id(conn, 1)[0] # row = db.select_user_by_credentials(conn, name, password)[0] row: tuple try: row = db.select_user_by_credentials2(conn, name)[0] print("row") print(type(row)) except IndexError: messagebox.showwarning("Login Failed - Access Denied", "Username or Password incorrect!") raise ValueError("Wrong credentials! - Access denied") # print("name: " + name) # print("password: "******"row[1]: " + row[1]) # print("row[2]: " + row[2]) # global qq # global userId # global hire # global isEmployer self.user = row[3] + " " + row[4] self.user_id = row[0] self.hire = row[5] self.isEmployer = row[7] # print("tady typy") # print(type(self.user)) # print(type(self.user_id)) # print(type(self.hire)) # print(type(self.isEmployer)) # print("isEmployer") # print(self.isEmployer) # print(password) # print(row[2]) if name == row[1] and helper.Validation.verify_password( row[2], password): messagebox.showinfo("Login page", "Login successful!") self.__login.destroy() # Removes the toplevel window else: messagebox.showwarning("Login Failed - Access Denied", "Username or Password incorrect!")
def main(): db = Database() predefined_queries = queries() input_string = "mt-corretora> " print("MT Corretora (Database)") print( "A qualquer momento, você pode pressinar as seguintes opções para executar os comandos pré-definidos:" ) print("1 - O nome do trader e o valor médio de seus clientes.") print( "2 - O nome do trader e o total de remuneração por ano (salario + bonus). O salário de um trader é de 150 mil por ano." ) print( "3 - Um ranking com os 5 funcionarios com mais atendimentos ao cliente registrados" ) print( "4 - O nome do cliente e o valor total em ativos comprador e vendidos do tipo título prefixado." ) print( "5 - O saldo e nome dos clientes que investem apenas em ações do tipo ON." ) print( "6 - O nome dos traders que aconselham apenas clientes com perfil agressivo e que ja aconselharam pelo menos um cliente." ) print("Digite 'exit' para sair.") sql = input(input_string) while sql != 'exit': # Clear input if sql.isdigit(): i = int(sql) - 1 if i not in range(0, 6): print("Invalid option") else: sql = predefined_queries[i] print(sql) sql = sql.lower() # Execute sql results = [] try: results = db.execute(sql) except psycopg2.DatabaseError as e: print(e) else: if sql.startswith("select"): for r in results: print(r) else: print("Query executed successfully.") sql = input(input_string)
def __insert_presence(conn, data): """Insert a new presence Args: conn: connection object data: presence data """ for item in data: print(item) presence = (item['id'], item['timeIn'], item['timeOut'], item['date'], item['userID']) db.create_presence(conn, presence)
def get_by_email(cls, email): user = Database.find_one(collection=constants.USER_COLLECTION, query={"email": email}) if user: print(user) return cls(**user) return None
def test_create_book(self): testar = False if testar: self.db = Database.DatabaseBooks() self.assertTrue(self.db.createRecord("Meu livro", 420, 12)) print "O metodo createRecord criou registro 'Meu livro' com sucesso" else: print "Teste de criação de livro não realizado"
def __init__(self, user_log_in, user_id, hire_date, is_employer, root): super().__init__() self.root: Tk = root self.var = IntVar() self.__default_time: str = "Odchozeno hodin: " self.__default_wage: str = "Celková hrubá mzda: " self.__default_days: str = "Počet dnů: " self.__cb_year = Combobox(self, state="readonly") self.__lb_data = Listbox(self, font=('Courier New', 12)) self.__output = LabelFrame(self, text="Výpis") self.__lb_time = Label(self.__output, text=self.__default_time + "0:0") self.__lb_wage = Label(self.__output, text=self.__default_wage + "0,00 Kč") self.__lb_days = Label(self.__output, text=self.__default_days + "0") self.__conn = db.create_connection() self.user_id = user_id self.isEmployer = is_employer self.hire_date: str = hire_date self.user_log_in: str = user_log_in self.__init_ui() self.__btn_update_event()
def get_hierarchy(): conn = Database.dbConnection() hierarchy = {} hierarchy_list = [] try: cursor = conn.cursor(dictionary=True) # sql = "SELECT DISTINCT REPORTSTO,FIRSTNAME,LASTNAME FROM CLASSICMODELS.EMPLOYEES WHERE REPORTSTO <> 'NULL'" sql = "SELECT FIRSTNAME,LASTNAME,EMPLOYEENUMBER,REPORTSTO FROM EMPLOYEES" cursor.execute(sql) reports_to = cursor.fetchall() for i in range(0, len(reports_to)): hierarchy_dict = {} employee_number = reports_to[i]['EMPLOYEENUMBER'] sql = "SELECT FIRSTNAME,LASTNAME,EMPLOYEENUMBER FROM CLASSICMODELS.EMPLOYEES WHERE REPORTSTO = {}".format( employee_number) cursor.execute(sql) employee_details = cursor.fetchall() hierarchy_dict['head'] = reports_to[i] hierarchy_dict['staff'] = employee_details hierarchy_list.append(hierarchy_dict) hierarchy['hierarchy'] = hierarchy_list return jsonify(hierarchy) except Exception as exception: hierarchy['error'] = str(exception) return jsonify(hierarchy) finally: conn.close()
def run(self): self.average, self.entropy, self.kurtosis, self.max_v, self.median, self.min_v, self.skewness, self.standart_dev = Features.check_statistics( self) #self.wavelet_type, self.sampling_per, self.min_scale, self.max_scale, self.scale_step = Features.cont_check_wavelet(self) self.sampling_per = 1 self.min_scale = 1 self.max_scale = 8 self.scale_step = 1 wave_types = pywt.wavelist(kind='continuous') self.scaling = np.arange(self.min_scale, self.max_scale, self.scale_step) for wave_func in wave_types: self.wavelet_type = wave_func self.wavelet_level = len(self.scaling) - 1 col, self.header, self.db_header = Features.init_table( self, len(self.all_signals)) self.db_matrix = np.zeros( (len(self.all_signals), 8 * (self.wavelet_level + 1)), dtype=complex) for iter in range(0, len(self.all_signals)): #print(self.all_signals[iter]) self.signals.clear() self.audio, self.sample = librosa.load(self.all_signals[iter]) self.signals.append(self.audio) self.time = np.arange(0, len(self.audio)) / self.sample coef, freqs = pywt.cwt(self.audio, self.scaling, self.wavelet_type, int(self.sampling_per)) for i in range(0, self.wavelet_level + 1): self.signals.append( coef[i]) # adding signals array to coeffs self.db_matrix[iter] = Features.insertTableComplex( self, iter, col) w_name = str(self.wavelet_type) table_name = "Db_GTZAN_function_" + w_name + "_Scale_1_to_8_Period_1" Database.create_table( Database.database_name, table_name, self.db_header, "") # creating new table with statistic function Database.create_table(Database.database_name, table_name, self.db_header, "Comp_") for index in range(0, len(self.all_signals)): name = self.all_signals[index].split(sep='/') Database.add_values_to_table(Database.database_name, table_name, name[-1], self.db_header, self.db_matrix[index], "") Database.add_values_to_table(Database.database_name, table_name, name[-1], self.db_header, self.db_matrix[index], "Comp_") print(table_name)
def search(): pattern = request.form.get('pattern') result = Database.find(constants.POST_COLLECTION, {"author": { "$regex": u"{}".format(pattern) }}) li = [r for r in result] return render_template('search.html', posts=li, author=pattern)
def btn_entry_event(self): """Button event - entry presence """ date_now: str = datetime.today().strftime('%Y-%m-%d') time_now: str = datetime.today().strftime('%H:%M') entry: int = self.var.get() if entry == 0: print(entry) # Příchod # Nový zápis # Kontrola da už je tenhle datum zapsán # db.exist_timeIn(self.__conn, self.user_id, date_now) if not db.exist_time_in(self.__conn, self.user_id, date_now): presence_in = (time_now, date_now, self.user_id) db.create_presence_in(self.__conn, presence_in) else: print("Již je zapsán příchod") messagebox.showwarning("Chyba zapsání příchodu!", "Již je zapsán příchod!") else: print(entry) if db.exist_time_in(self.__conn, self.user_id, date_now): if not db.exist_time_out(self.__conn, self.user_id, date_now): presence_out = (time_now, date_now, self.user_id) db.create_presence_out(self.__conn, presence_out) else: print("Již je zapsán odchod") messagebox.showwarning("Chyba zapsání odchodu!", "Již je zapsán odchod!") else: print("Nejdříve zapište příchod") # Odchod # Update zápisu # Kontrola da už je tenhle datum zapsán self.__btn_update_event()
def __init__(self, root): super().__init__() self.root = root root.title("Hire") root.geometry("450x270+450+170") root.minsize(450, 270) root.maxsize(450, 270) self.var = BooleanVar() self.conn = db.create_connection() self.__init_ui()
def login_user(self): name = self.username_box.get() password = self.password_box.get() login_completed = self.login_completed.get() # AUTO DATA PRO TESTOVÁNÍ name = "dom53" password = "******" conn = db.create_connection() # us = db.select_user_by_id(conn, 1) # row = db.select_user_by_id(conn, 1)[0] row = db.select_user_by_credentials(conn, name, password)[0] print("name: " + name) print("password: "******"row[1]: " + row[1]) print("row[2]: " + row[2]) global qq global userId global hire global isEmployer qq = row[3] + " " + row[4] userId = row[0] hire = row[5] isEmployer = row[7] print("isEmployer") print(isEmployer) # Potom zapnout if name == row[1] and password == row[2]: #Main_Win.setUzv(uu) # Potom zapnout # messagebox.showinfo("Login page", "Login successful!") self.login.destroy() # Removes the toplevel window # self.main_win.deiconify() #Unhides the root window self.login_completed == 1 # Potom zapnout else: messagebox.showwarning("Login Failed - Acess Denied", "Username or Password incorrect!")
def __init__(self, root, user_id): super().__init__() self.root = root root.title("Hire") root.geometry("350x200+250+170") root.minsize(350, 200) root.maxsize(350, 200) self.user_id = user_id self.var = BooleanVar() self.conn = db.create_connection() print("toto -> " + str(self.user_id)) self.__init_ui()
def save_to_db(self): if (self.load_check and self.analyze_check): w_name = str(self.wavelet_type) table_name = "Db_GTZAN_function_" + w_name + "_Degree_" + str( self.wavelet_level) Database.create_table( Database.database_name, table_name, self.db_header, "") # creating new table with statistic function for index in range(0, len(self.all_signals)): name = self.all_signals[index].split(sep='/') #name of signal Database.delete_row(Database.database_name, table_name, name[-1], "") Database.add_values_to_table(Database.database_name, table_name, name[-1], self.db_header, self.db_matrix[index], "") #adding db to values Features.message("Your Data Saved Succesfully", QMessageBox.Information) else: if (self.load_check): Features.message("You have to analyze the signals first", QMessageBox.Warning) else: Features.message("You have to load at least 1 signal", QMessageBox.Warning)
def save_to_db(self): if (self.load_check and self.analyze_check): w_name = str(self.wavelet_type) table_name = "Db_GTZAN_function_" + w_name + "_Degree_" + str( self.wavelet_level) Database.create_table( Database.database_name, table_name, self.db_header, "") # İstatistiksel fonksiyonlar için tablo oluşturma for index in range(0, len(self.all_signals)): name = self.all_signals[index].split(sep='/') #Sinyalin adı Database.delete_row(Database.database_name, table_name, name[-1], "") Database.add_values_to_table(Database.database_name, table_name, name[-1], self.db_header, self.db_matrix[index], "") #Db'ye değerleri girme Features.message("Your Data Saved Succesfully", QMessageBox.Information) else: if (self.load_check): Features.message("You have to analyze the signals first", QMessageBox.Warning) else: Features.message("You have to load at least 1 signal", QMessageBox.Warning)
def registration(self): """New employee registration """ # Todo: Přidat dynamický datum print("reg") print(self.__username_box.get()) print(self.__password_box.get()) print(self.__first_name_box.get()) print(self.__surname_box.get()) print(self.__cal.get()) print("okok") print(self.__wage_box.get()) if not db.user_exist(self.conn, self.__username_box.get()): hire_user = (self.__username_box.get(), helper.Validation.hash_password( self.__password_box.get()), self.__first_name_box.get(), self.__surname_box.get(), "26.01.2019", int(self.__wage_box.get())) db.hire_user(self.conn, hire_user) else: print("Již je registrován uživatel") messagebox.showwarning("Chyba zapsání příchodu!", "Již je registrován uživatel!")
def get_employees(): conn = Database.dbConnection() employees_dictionary = {} try: cursor = conn.cursor(dictionary=True) sql = "SELECT * FROM EMPLOYEES" cursor.execute(sql) rs = cursor.fetchall() employees_dictionary['employees'] = rs return jsonify(employees_dictionary) except Error as exception: employees_dictionary['error'] = exception return jsonify(str(employees_dictionary)) finally: conn.close()
def get_job_titles(): conn = Database.dbConnection() job_dictionary = {} try: cursor = conn.cursor(dictionary=True) sql = "SELECT DISTINCT JOBTITLE FROM EMPLOYEES" cursor.execute(sql) job_dictionary['job_titles'] = cursor.fetchall() return jsonify(job_dictionary) except Exception as exception: job_dictionary['error'] = str(exception) return jsonify(job_dictionary) finally: conn.close()
def __init__(self): # ENV variables # self.DISCORD_TOKEN = environ.get('DISCORD_TOKEN') # self.DISCORD_CHANNEL_ID = int(environ.get('DISCORD_CHANNEL')) # self.WEBHOOK = environ.get('WEBHOOK') self.DISCORD_TOKEN = 'NzczMTUxNjE2MTEwODIxNDE2.X6FDjQ.iwIFli_40zZWCYrnlTuqnOmykE4' self.DISCORD_CHANNEL_ID = 773154253496909827 self.WEBHOOK = 'https://discord.com/api/webhooks/773160572308160523/9zmjE75bsOWMGQcKGb2_5P0JBjkuQLfSgrPNx55WxDMkOOAZ_7rhSzTi9qE_b3X-YiK4' # Discord client self.discord = Bot(command_prefix='!') # Database self.db = Database() # Attendance globals self.last_message = None self.last_attendance = None # Attendance (Period, at_home), see >> AttendanceMessage.py
def update_employee(request): conn = Database.dbConnection() update = {} try: first_name = request['FIRST_NAME'] last_name = request['LAST_NAME'] employee_number = request['EMPLOYEE_NUMBER'] cursor = conn.cursor() sql = "UPDATE EMPLOYEES SET FIRSTNAME = '{}',LASTNAME = '{}' WHERE EMPLOYEENUMBER={}".format( first_name, last_name, employee_number) cursor.execute(sql) conn.commit() update['success'] = "operation successful" return jsonify(update) except Exception as exception: update['error'] = str(exception) return jsonify(update) finally: conn.close()
def __init__(self): QMainWindow.__init__(self) loadUi("../ui/Prediction.ui", self) self.setWindowTitle("Wavelet Transform Data Analyzer Tool") self.setWindowIcon(QtGui.QIcon('../icon/icon.png')) Features.center(self) list_tables = Database.get_table_names(Database.database_name) Features.list_db_tables(self, list_tables) for i in range(2, 21): self.comboBox_kfold.addItem(str(i), i) self.selected_table_name = "" self.checkBox_knn.setChecked(True) self.checkBox_randomForest.setChecked(True) self.checkBox_svcLinear.setChecked(True) self.checkBox_svcPoly.setChecked(True) # prediction page checks self.checkBox_gaussianNB.setChecked(True) self.checkBox_svcRBF.setChecked(True) self.pushButton.clicked.connect(self.analyze_signal) self.dbTables_listWidget.itemSelectionChanged.connect(self.selectionChanged)
def get_update_month_cb(self) -> list: """Return user years Returns: list: user years """ user_years = list() print("userId: " + str(self.user_id)) temp_year = db.get_presence_group_by_year_by_id(self.__conn, self.user_id) print("temp: " + str(len(temp_year))) for x in temp_year: print("type x") print(type(x)) user_years.append(x) if len(temp_year) == 0: user_years.append("Žádný zápis") print(type(user_years)) return user_years
def __init__(self): """Наследуем все методы и задаем связь между элементами дизайна и функциями класса. """ super().__init__() self.setupUi(self) # Загружаем в Checkbox информацию по моделям self.init_models_info() # Инициализируем настройки self.settings_file = '.\\settings.ini' self.init_settings(self.settings_file) # Создаем объект для работы с удаленной базой self.postgresql = sql.PostgreSQL(settings=self.parametres) # Создаем временную БД self.db = data.Database() # Создаем поток для COM-порта self.COM_port = com.COMPortThread(database=self.db) # Инициализируем сигналы self.init_connections() # Обновляем список доступных COM-портов self.btn_click_update_com() # Инициализируем настройки дополнительных окон self.init_windows()
def test_field(self): self.db = Database.DatabaseBooks() self.assertEqual(u'marketing na era digital'.lower(), self.db.getRecords(id_record=26)[1]) print "O livro com id 26 foi testado e foi retornado com sucesso"
def test_size(self): self.db = Database.DatabaseBooks() self.assertEqual(43, self.db.getSizeRecords()) print "O banco de dados assume 43 registros como esperado"