def toggle_heart(self, widget): if widget.icon == "heart": widget.icon = "heart-outline" if widget.icon == "heart" else "heart-outline" toast("Job unsaved") else: widget.icon = "heart" if widget.icon == "heart-outline" else "heart" toast("Job saved")
def on_osc_init_ok(self, exception=None): if exception: toast('OSC bind error: {0}.'.format(exception) + '\nWrong IP/Port?') else: toast('OSC Init OK') _LOGGER.debug("GUI1: OSC init ok")
def callback(self, text, checkbox, value): toast(checkbox.group) if value: self.person_habits.append(checkbox.group) else: if checkbox.group in self.person_habits: self.person_habits.remove(checkbox.group)
def get_server_file_download(self, req_url, callback, file_path): def is_finished(dt): if req.is_finished is True: app = App.get_running_app() screen = app.manager.get_screen("server_readinglists_screen") screen.ids.sync_button.enabled = True Clock.schedule_once(self.download_file) else: Clock.schedule_once(is_finished, 0.25) app = App.get_running_app() username = app.config.get("General", "username") api_key = app.config.get("General", "api_key") str_cookie = f"API_apiKey={api_key}; BCR_username={username}" head = { "Content-Type": "application/json", "Accept": "application/json", "Cookie": str_cookie, } req = UrlRequest( req_url, req_headers=head, on_success=callback, file_path=file_path ) app = App.get_running_app() screen = app.manager.get_screen("server_readinglists_screen") if len(self.sync_list) != 0: screen.ids.sync_status_lbl.text = ( f"Sync is Running Left in Que: {len(self.sync_list)}" ) Clock.schedule_once(is_finished, 0.25) else: toast("Reading List has been Synced, Refreshing Screen") screen.ids.sync_status_lbl.text = "" screen.ids.sync_button.enabled = True app.sync_is_running = False
def sync_readinglist(self): if self.sync_options.ids.sw_syn_this.active is False: self.sync_options.ids.syn_on_off_label.text = f"Sync Not Turned On" self.open_sync_options() elif self.sync_options.ids.sw_syn_this.active is True: toast(f"Starting sync of {self.new_readinglist.name}") self.new_readinglist.do_sync()
def TestKey(self, key): if key == '365': toast('Ok!') self.popup.dismiss() else: toast('Error!')
def on_enter(self, *args): if self.width == 3: self.ids.toolbar.title = 'Врисование' elif self.width == 10: self.ids.toolbar.title = 'Спираль' if self.filename[0] == "L": self.ids.toolbar.title = self.ids.toolbar.title + ', левая рука' elif self.filename[0] == "R": self.ids.toolbar.title = self.ids.toolbar.title + ', правая рука' # self.ids.counter.text = 'Проведите линию по спирали от синей до красной точки' filename1 = self.filename + datetime.now().strftime( "%Y.%m.%d_%H:%M:%S") + '.csv' Spiral.pathfile = os.path.join(Spiral.folderpath, filename1) if os.path.exists( os.path.join( Spiral.path, str(Window.width) + '_' + str(Window.height) + '.csv')) == False: for i in range(self.ids.spiral.frames): self.ids.spiral.generate_spiral(i, Spiral.path) if self.ids.spiral.readfromfile(): toast(str(len(self.ids.spiral.points))) self.ids.spiral.static_spiral(self.width) else: toast('Error') self.ids.spiral.readfromfile()
def login(self, usr, passwd): if (usr.text == "salman97" and passwd.text == "salman"): #Snackbar(text="Welcome " + usr.text + "!").show() toast("Welcome " + usr.text + "!") self.manage_screens("home_screen", "add") self.change_screen("home_screen") else: toast("Incorrect username and/or password!")
def on_connection_timeout(self, hp, is_timeout): if is_timeout: if not self.server_started: _LOGGER.debug("GUI1: Starting service") self.start_server() toast(f'Timeout comunicating with server ({hp[0]}:{hp[1]})') _LOGGER.debug(f"GUI1: OSC timeout ({hp[0]}:{hp[1]})") self.server_started = True else: _LOGGER.debug(f"GUI1: OSC timeout OK ({hp[0]}:{hp[1]})") toast(f'OSC comunication OK ({hp[0]}:{hp[1]})')
def captureTrainingImages(self, student_name, student_id, screen_manager): print(len(student_name), len(student_id)) if len(student_name) > 0 and len(student_name) <= 23 and len( student_id) > 0 and len(student_id) <= 6: os.system("python captureTrainingImages.py {} {}".format( student_name, student_id)) toast("Training Images Collected.") screen_manager.current = "HomeScreen" else: toast("Please Enter Correct Details.")
def checkuser(self, femail, fpassword): self.femail = str(femail) self.fpassword = str(fpassword) regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' if (re.search(regex, femail) == None or len(fpassword) < 6): toast("Invalid ID or Password...", duration=2) else: try: mydb = mysql.connector.connect(host="localhost", user="******", passwd="", database="vidit") mycursor = mydb.cursor() sql = "SELECT password FROM users WHERE email = %s" femail = (str(femail), ) mycursor.execute(sql, femail) dpassword = mycursor.fetchone() if (dpassword): if (dpassword[0] == fpassword): toast("Login Successfully...", duration=2) f = open("current_user.txt", "w") f.write(femail[0]) f.close() self.sm.current = "screen3" else: toast("Please Enter Valid Id and Password...", duration=2) else: toast("Please Register Your Account...", duration=2) except BaseException as error: print('An exception occurred: {}'.format(error))
def download_file(self, dt): def got_thumb(results): pass app = App.get_running_app() screen = app.manager.get_screen("server_readinglists_screen") screen.ids.sync_button.enabled = False if len(self.sync_list) == 0: toast("Reading List has been Synced, Refreshing Screen") app = App.get_running_app() screen = app.manager.get_screen("server_readinglists_screen") screen.ids.sync_status_lbl.text = "" screen.ids.sync_button.enabled = True app.sync_is_running = False # screen.refresh_callback() return comic = self.sync_list.pop(0) self.file_download = False file_name = ntpath.basename(comic.FilePath) y = 240 part_url = f"/Comics/{comic.Id}/Pages/0?" app = App.get_running_app() part_api = f"&apiKey={app.api_key}&height={round(dp(y))}" thumb_url = f"{app.api_url}{part_url}{part_api}" if self.cb_optimize_size_active is False: sync_url = f"{app.api_url}/Comics/{comic.Id}/Sync/File/" elif self.cb_optimize_size_active is True: sync_url = f"{app.api_url}/Comics/{comic.Id}/Sync/Webp" app = App.get_running_app() id_folder = os.path.join(app.sync_folder, self.slug) self.my_comic_dir = Path(os.path.join(id_folder, "comics")) self.my_thumb_dir = Path(os.path.join(id_folder, "thumb")) if not self.my_comic_dir.is_dir(): os.makedirs(self.my_comic_dir) if not self.my_thumb_dir.is_dir(): os.makedirs(self.my_thumb_dir) t_file = os.path.join(self.my_comic_dir, file_name) self.get_server_file_download( sync_url, callback=self.got_file(comic, comic_file=t_file), file_path=t_file, ) thumb_name = f"{comic.Id}.jpg" self.fetch_data.get_server_file_download( thumb_url, callback=lambda req, results: got_thumb(results), file_path=os.path.join(self.my_thumb_dir, thumb_name), )
def set_result(self, results): txt = self.result_text complete_all = '' next_query = False _LOGGER.info(f'Query results arrived') _LOGGER.debug(f'Query results {results}') for i, result in enumerate(results): if self.query_state >= 0 and 'rows' in result and not result['rows']: break elif 'cols' in result and ['__file__'] == result['cols'] and len(results) > i + 1: if result['rows']: next_query = self.query_state >= 0 fname = join(db_dir('sessions'), result['rows'][0]) try: with open(fname, 'w') as out_file: for k in range(i + 1, len(results)): r = results[k] if r['cols'] and r['rows']: out_file.write(("\t".join(r["cols"])) + '\n') out_file.write(("\n".join(r["rows"])) + '\n') else: label, complete = self.format_result(r) txt += label txt += f'File {fname} written OK\n' except Exception as ex: txt += f'{ex.__class__.__name__}: File name: {fname} -> {ex}\n' break else: label, complete = self.format_result(result) txt += label if complete: complete_all += complete if complete_all: try: Clipboard.copy(complete_all) toast('Query result rows have been copied to clipboard') except Exception: _LOGGER.error(f'Copy Exception {traceback.format_exc()}') self.ids.id_result.text = self.result_text = txt if next_query: self.dispatch_on_query(self.get_query(self.query_text)) else: self.ids.id_query.readonly = False self.ids.id_toolbar.right_action_items = [ ["floppy", lambda x: self.start_querying()], ]
def got_file(results): self.num_file_done += 1 toast(f'{file_name} Synced') self.file_download = True self.sync_comics.put(comic.Id, file=file_name, slug=comic.slug, data_type='ComicBook', Series=comic.Series, Number=comic.Number, Month=comic.Month, Year=comic.Year, UserCurrentPage=comic.UserCurrentPage, UserLastPageRead=comic.UserLastPageRead, PageCount=comic.PageCount, Summary=comic.Summary, Index=comic_index, FilePath=comic.FilePath, ReadlistID=self.reading_list.slug )
def on_enter(self, *args): if self.filename[0] == "L": self.ids.toolbar.title = self.ids.toolbar.title + ', левая рука' elif self.filename[0] == "R": self.ids.toolbar.title = self.ids.toolbar.title + ', правая рука' # self.ids.counter.text = 'Повторите верхнюю спираль в нижнем квадрате' filename1 = self.filename + datetime.now().strftime( "%Y.%m.%d_%H:%M:%S") + '.csv' Two_Spiral.pathfile = os.path.join(Two_Spiral.folderpath, filename1) if os.path.exists( os.path.join( Two_Spiral.path, 'two_spiral_' + str(Window.width) + '_' + str(Window.height) + '.csv')) == False: for i in range(self.ids.spiral.frames_two_spiral): self.ids.spiral.generate_two_spiral(i, Two_Spiral.path) if self.ids.spiral.readfromfile_two_spiral() == True: self.ids.spiral.two_spiral(self.width) else: toast('Error') self.ids.spiral.readfromfile_two_spiral()
def registeruser(self, remail, rname, rcontact, rpassword, rcpassword): self.remail = str(remail) self.rname = str(rname) self.rcontact = str(rcontact) self.rpassword = str(rpassword) self.rcpassword = str(rcpassword) regex = '^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$' if (re.search(regex, remail) == None or len(rpassword) < 6): toast("Invalid ID or Password...", duration=2) if (rpassword != rcpassword): toast("Password and Confirm Password are Different...", duration=2) if (remail == '' or rname == '' or rcontact == '' or rpassword == '' or rcpassword == ''): toast("Please fill all the field...", duration=2) else: try: mydb = mysql.connector.connect(host="localhost", user="******", passwd="", database="vidit") mycursor = mydb.cursor() sql = "SELECT name FROM users WHERE email = %s" remail = (str(remail), ) mycursor.execute(sql, remail) result = mycursor.fetchone() if (result): toast("Email already Registered...", duration=2) else: sql = "INSERT INTO users (email,name,contact_no,password) VALUES (%s, %s, %s, %s)" val = (str(remail[0]), str(rname), str(rcontact), str(rpassword)) mycursor.execute(sql, val) mydb.commit() toast("Registered Successfully...", duration=2) except BaseException as error: print('An exception occurred: {}'.format(error))
def speechRec(self): r = sr.Recognizer() with sr.Microphone() as source: audio = r.listen(source, timeout=1) try: text = r.recognize_google(audio) if (text == "start"): toast("Starting the car!") elif (text == "stop" or text == "top"): toast("Stopping the car!") else: text("Could not recognize what you said!") except: toast("Could not recognize what you said!")
def upload_to_db(self): path = Root.path exam_ind = { 'patient_id': int, 'hand': str, 'type': str, 'bad_effects': str, 'exam_date': str, 'exam_time': str, 'data': dict } new_names = { "Фамилия": 'second_name', "Имя": 'first_name', "Отчество": 'middle_name', "Дата рождения": 'dob', "Диагноз": 'diagnosis', "Пол": 'sex', "Доминирующая рука": 'dominant_hand' } os.chdir(path) info = pd.DataFrame() folders = os.listdir(path) toast('upload_to_db') for folder in folders: if os.path.isdir(folder): files = os.listdir(folder) os.chdir(folder) df = pd.read_csv('Информация.txt', sep=': ', header=None, index_col=0) info = df.transpose() files.remove('Информация.txt') examinations = pd.DataFrame(columns=exam_ind) for file in files: data = pd.read_csv(file, names=['t', 'x', 'y']) data = data.to_json(orient='columns') exam = re.split('[_| ]', file) if len(exam) == 3: exam = { 'hand': exam[0], 'exam_date': exam[1], 'exam_time': exam[2].rstrip('.csv'), 'data': data } elif len(exam) == 5: exam = { 'hand': exam[0], 'type': exam[1], 'bad_effects': exam[2], 'exam_date': exam[3], 'exam_time': exam[4].rstrip('.csv'), 'data': data } exam = pd.DataFrame([exam], columns=exam.keys()) examinations = pd.concat([examinations, exam]) info['Дата рождения'] = pd.to_datetime(info['Дата рождения']) info.rename(new_names, axis=1) try: info.loc[info['Пол'] == 'Мужской', 'Пол'] = True info.loc[info['Пол'] == 'Женский', 'Пол'] = False except KeyError: pass try: info.loc[info['Доминирующая рука'] == 'Левая', 'Доминирующая рука'] = 'L' info.loc[info['Доминирующая рука'] == 'Правая', 'Доминирующая рука'] = 'R' info.loc[info['Доминирующая рука'] == 'Обе', 'Доминирующая рука'] = 'B' except KeyError: pass try: info = info.rename(new_names, axis=1) print('nen', info) upload(info, 'patients') except IntegrityError: pass values = info[[ 'first_name', 'second_name', 'middle_name', 'diagnosis', 'dob' ]].values patient_id_query = """ SELECT id FROM patients WHERE first_name = %s AND second_name = %s AND middle_name = %s AND diagnosis = %s AND dob = %s """ conn = create_connection() conn.autocommit = True cursor = conn.cursor() cursor.execute(patient_id_query, values.tolist()[0]) patient_id = cursor.fetchone()[0] examinations['patient_id'] = patient_id try: upload(examinations, 'examinations') except IntegrityError: pass os.chdir('../')
def file_finished_toast(dt): toast(f"{os.path.basename(comic_file)} Synced")
def show_toast(self): toast("Test Kivy Toast")
def hide_press(self): toast('Удачно списать =)')
def callback_for_setting_items(self, *args): print(args) toast(args[0])
def _finish_toast(dt): toast('Reading List has been Synceddd')
def __finish_toast(dt): toast("Reading List has been Synced, Refreshing Screen")
def carControl(self, control): if (control == "start"): toast("Starting the car!") elif (control == "stop"): toast("Stopping the car!")
def __finish_toast(dt): app = App.get_running_app() screen = app.manager.get_screen("server_readinglists_screen") screen.refresh_callback() toast("DataBase Refresh Complete")
def __init__(self, master, level, **kwargs): super().__init__(**kwargs) if platform != "android": self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text') if self._keyboard.widget: # If it exists, this widget is a VKeyboard object which you can use to change the keyboard layout. pass self._keyboard.bind(on_key_down=self._on_keyboard_down) self.master = master self.level = level self.dialog = None self.effect_cls = "ScrollEffect" self.scroll_type = ["bars"] self.bar_width = "10dp" self.pos_hint = {"top": .9} self.kanji_layout = MDRelativeLayout() self.kanji_data = get_kanji_from_level(self.level) if self.kanji_data is {} or self.kanji_data is None: toast( "Error has occured; No internet connection; Site may be blocked" ) self.kanji_layout.add_widget( Label( text= "Can't connect to the internet\nthe API may be blocked\nor poor connection", halign="center")) else: for k, v in self.kanji_data.items(): setattr(self, k, v) self.btn_texts = [ " Show Meanings ", " Show Radicals ", "Show Example Words" ] #self.kanji_layout.add_widget(Label(text=str(self.kanji), font_size=75,halign="center", pos_hint={"center_y":.8})) #self.kanji_layout.add_widget(Label(text=str(self.stroke_count), font_size=20,halign="center", pos_hint={"center_y":.7})) self.kanji_layout.add_widget( HighlightableText( text=f"{str(self.kanji)}: {self.stroke_count}", font_size="40sp", pos_hint={ "center_x": .5, "center_y": .9 })) self.carousel = KanjiStrokeImageCarousel(self.stroke_order_images) self.kanji_layout.add_widget(self.carousel) if platform != "android": self.prev_btn = MDIconButton( icon="menu-left", user_font_size="200sp", on_release=lambda x: self.carousel.load_previous(), pos_hint={ "center_x": .1, "center_y": .6 }) # pos_hint={"left":.2, "y":.5}, self.next_btn = MDIconButton( icon="menu-right", user_font_size="200sp", on_release=lambda x: self.carousel.load_next(), pos_hint={ "center_x": .9, "center_y": .6 }) # pos_hint={"right":.8, "y":.5} self.kanji_layout.add_widget(self.prev_btn) self.kanji_layout.add_widget(self.next_btn) """ for i, reading in enumerate(self.readings): # HighlightableText(text=reading, font_size=20, pos_hint={"center_x":.5,"center_y":.3-(i/20)}) self.kanji_layout.add_widget( HighlightableText(text=reading, font_size=20, pos_hint={"center_x":.4,"center_y":.3-(i/30)}) ) """ self.readings_formatted = "\n".join( [f"{k}: {v}" for k, v in self.readings.items()]) self.kanji_layout.add_widget( HighlightableText(text=f"{self.readings_formatted}", font_size="20sp", pos_hint={ "center_x": .5, "center_y": .35 })) #print(" ".join([j for j in [" ".join(i) for i in self.radicals_data]])) formated_radicals = " \n".join([ rad for rad in [" :".join(tup) for tup in self.radicals_data] ]) formated_word_examples = "\n".join(self.example_words) #self.kanji_layout.add_widget(Label(text=formated_radicals,halign="center", font_size=15, pos_hint={"center_x":.5,"center_y":.1})) self.meanings_btn = MDRaisedButton( text=self.btn_texts[0], pos_hint={ "center_x": .1, "center_y": .2 }, on_release=lambda x: self.showDialog("Meanings", self.meanings )) self.radicals_btn = MDRaisedButton( text=self.btn_texts[1], pos_hint={ "center_x": .5, "center_y": .2 }, on_release=lambda x: self.showDialog("Radicals", formated_radicals)) #self.kanji_layout.add_widget(self.radicals_btn) self.examples_btn = MDRaisedButton( text=self.btn_texts[2], pos_hint={ "center_x": .9, "center_y": .2 }, on_release=lambda x: self.showDialog("Example Words", formated_word_examples)) #self.kanji_layout.add_widget(self.examples_btn) for btn in [ self.meanings_btn, self.radicals_btn, self.examples_btn ]: self.kanji_layout.add_widget(btn) self.add_widget(self.kanji_layout)
def __got_readlist_data(results): def __updated_progress(results): pass the_keys = [ "Id", "Series", "Number", "Volume", "Year", "Month", "UserCurrentPage", "UserLastPageRead", "PageCount", "Summary", "FilePath", ] for server_comic in results["items"]: for db_comic in self.comics: if db_comic.Id == server_comic["Id"]: for key in the_keys: if getattr(db_comic, key) != server_comic[key]: if key in ( "UserCurrentPage", "UserLastPageRead", ) and (db_comic.is_sync): if ( db_comic.UserLastPageRead > server_comic["UserLastPageRead"] ) or ( db_comic.UserCurrentPage > server_comic["UserCurrentPage"] ): if ( db_comic.UserCurrentPage > db_comic.UserLastPageRead ): current_page = ( db_comic.UserCurrentPage ) # noqa else: current_page = ( db_comic.UserLastPageRead ) # noqa update_url = "{}/Comics/{}/Progress".format( api_url, db_comic.Id ) self.fetch_data.update_progress( update_url, current_page, callback=lambda req, results: __updated_progress( results ), ) else: x_str = db_comic.__str__ Logger.info( "Updating DB Record for {} of {}".format( key, x_str ) ) toast( "Updating DB Record for {} of {}".format( key, x_str ) ) db_item = Comic.get( Comic.Id == db_comic.Id ) if db_item: setattr( db_item, key, server_comic[key] ) db_item.save() setattr(self, key, db_item) Clock.schedule_once(__finish_toast, 3)