class ProxySpeedTestApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) self.icon = f"{environ['KITCHEN_SINK_ASSETS']}icon.png" self.version = __version__ self.theme_cls.primary_palette = "LightBlue" self.dialog_change_theme = None self.toolbar = None self.scaning = Queue() self.running = Queue() self.currentSpeed = Queue() self.pbar0 = Queue() self.pbar1 = Queue() self.pbar2 = Queue() self.totalpb = Queue() configs = dbRW.getAllConfigs() mirrors = dbRW.getAllMirrors() self.selLId = configs[0][2] if self.selLId: totalScan = dbRW.getProxysInxTS(self.selLId)[0] getips = dbRW.getAllCurrentProxys(self.selLId) protocol = getips[0][4] self.scan_list = [] if self.selLId: for l in getips: if not None in l: self.scan_list.append({ "IP": l[0], "SIZE": l[1], "TIME": l[2], "SPEED": l[3], "top3c": l[6]}) self.theme_cls.theme_style = configs[0][0] miInx = configs[0][1] self.configs = { 'protocol': protocol if self.selLId else 'http', 'mirror': mirrors[miInx][0], 'timeout': int(configs[0][3]), 'fileSize': int(configs[0][4]), 'miInx': miInx, 'proxysInx': [], 'mirrors': mirrors, 'proxys': getips if self.selLId else[], 'totalScan': totalScan if self.selLId else 0 } # def on_resume(self): # self.ads.request_interstitial() def changeThemeMode(self, inst): self.theme_cls.theme_style = inst dbRW.updateThemeMode(inst) def checkUpdates(self, ava=False, d=False): # print(ava) upCURL = 'https://raw.githubusercontent.com/biplobsd/proxySpeedTestApp/master/updates.json' # from json import load # with open('updates.json', 'r') as read: # updateinfo = load(read) # toast("Checking for any updates ...") try: updateinfo = get(upCURL).json() except: updateinfo = { "version": float(self.version), "messages": "", "changelogs": "", "force": "false", "release": { "win": "", "linux": "", "android": "", "macosx": "", "unknown": "", "kivy_build": "" } } # toast("Faild app update check!") if updateinfo: try: appLink = updateinfo["release"][platform] except KeyError: return title = f"App update v{updateinfo['version']}" msg = "You are already in latest version!" b1 = "CENCEL" force = False if updateinfo['version'] > float(self.version) and appLink != "": if updateinfo['messages']:title = updateinfo['messages'] msg = "" b2 = "DOWNLOAD" force = bool(updateinfo['force']) if force: b1 = "EXIT" ava = True else: b2 = "CHECK" self.updateDialog = MDDialog( title=title, text=msg+updateinfo['changelogs']+f"\n\n[size=15]Force update: {force}[/size]", auto_dismiss=False, buttons=[ MDFlatButton( text=b1, text_color=self.theme_cls.primary_color, on_release=lambda x: self.updateDialog.dismiss() if b1 == "CENCEL" else self.stop() ), MDRaisedButton( text=b2, on_release=lambda x:open_link(appLink) if b2 == "DOWNLOAD" else self.FCU(self.updateDialog), text_color=self.theme_cls.primary_color ), ], ) self.updateDialog.ids.title.theme_text_color = "Custom" self.updateDialog.ids.title.text_color = self.theme_cls.primary_light if ava:self.updateDialog.open() def FCU(self, inst): inst.dismiss() Clock.schedule_once(partial(self.checkUpdates, True)) def on_pause(self): return True def save_UpdateDB(self, l=[]): dbRW = MyDb() if l:dbRW.updateScanList(l) def build(self): if platform == "android": self._statusBarColor() Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/list_items.kv" ) Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/dialog_change_theme.kv" ) return Builder.load_file( f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/start_screen.kv" ) @run_on_ui_thread def _statusBarColor(self, color="#03A9F4"): window = activity.getWindow() window.clearFlags(WindowManager.FLAG_TRANSLUCENT_STATUS) window.addFlags(WindowManager.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) window.setStatusBarColor(Color.parseColor(color)) window.setNavigationBarColor(Color.parseColor(color)) def show_dialog_change_theme(self): if not self.dialog_change_theme: self.dialog_change_theme = KitchenSinkDialogChangeTheme() self.dialog_change_theme.set_list_colors_themes() self.dialog_change_theme.open() def on_start(self): """Creates a list of items with examples on start screen.""" unsort = self.scan_list # print(unsort) if unsort: sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True) # print(sort) self.show_List() self.show_List(sort) self.root.ids.Tproxys.text = f"proxys: {len(sort)}" self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}" else: self.root.ids.Tscan.text = "scan: 0" self.root.ids.Tproxys.text = "proxys: 0" self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" self.root.ids.Smirror.text = f"Mirror: {parse.urlparse(self.configs['mirror']).netloc}".upper() # self.root.ids.backdrop._front_layer_open=True Logger.info(f"Platform: {platform}") # if platform == 'android': # self.ads = KivMob(adMobIds.APP) # self.ads.new_banner(adMobIds.BANNER, top_pos=False) # self.ads.request_banner() # self.ads.show_banner() # self.root.ids.adsShow.size = (self.root.ids.backdrop_front_layer.width, 110) self.mirrorPic() self.protPic() self.listPic() self.tap_target_list_view = MDTapTargetView( widget=self.root.ids.Slist, title_text="Pic a lists", description_text="I will remember your list later!", widget_position="right_top", # outer_radius=dp(320), cancelable=True, outer_circle_color=self.theme_cls.primary_color[:-1], outer_circle_alpha=0.9, ) Thread(target=self.checkUpdates).start() def listPic(self): proxysInx = dbRW.getProxysInx() self.selLId = dbRW.getConfig('proxysInx')[0] Logger.debug(self.selLId) self.configs['proxysInx'] = proxysInx if proxysInx: selLIdindxDict = {} self.ListItems = [] i = 0 for Inx in proxysInx: self.ListItems.append({"icon": "playlist-remove", "text": f'#{i} '+agoConv(Inx[0])}) selLIdindxDict[Inx[0]] = i i += 1 else: self.ListItems = [{"icon": "playlist-remove", "text": "None"}] if proxysInx: self.selLIdindx = selLIdindxDict[self.selLId] self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper() if proxysInx else "list :" self.listSel = MDDropdownMenu( caller=self.root.ids.Slist, items=self.ListItems, width_mult=3, opening_time=0.2, use_icon_item=False, position='auto', max_height=0, callback=self.set_list, ) def set_list(self, ins): import re self.selLIdindx = int(re.search(r'#(\d)\s', ins.text).group(1)) # withoutHash = re.search(r'#\d\s(.+)', ins.text).group(1) Logger.debug(self.selLIdindx) proxysInx = dbRW.getProxysInx() self.selLId = proxysInx[self.selLIdindx][0] proxys = dbRW.getAllCurrentProxys(self.selLId) protocol = proxys[0][4] dbRW.updateConfig("proxysInx", self.selLId) scan_list = proxys self.scan_list = [] if self.selLId: for l in scan_list: if not None in l: self.scan_list.append({ "IP": l[0], "SIZE": l[1], "TIME": l[2], "SPEED": l[3], "top3c": l[6] }) unsort = self.scan_list if unsort: sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True) # print(sort) self.show_List() self.show_List(sort) self.configs['proxys'] = proxys self.configs['protocol'] = protocol self.root.ids.Slist.text = f"list : {ins.text}".upper() self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}" # print(getips) toast(ins.text) # print(indx) self.listSel.dismiss() if self.tap_target_list_view.state == 'open': self.tap_target_list_view.stop() def protPic(self): items = [{"icon": "protocol", "text": protocol.upper()} for protocol in ['http', 'https', 'socks4', 'socks5']] self.protSel = MDDropdownMenu( caller=self.root.ids.Sprotocol, items=items, width_mult=2, opening_time=0.2, use_icon_item=False, position='auto', callback=self.set_protocol ) def set_protocol(self, ins): self.configs['protocol'] = ins.text.lower() self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}" toast(self.configs['protocol']) self.protSel.dismiss() def mirrorPic(self): mirrors = dbRW.getAllMirrors() self.configs['mirrors'] = mirrors items = [{"icon": "web", "text": parse.urlparse(mirror[0]).netloc} for mirror in mirrors] self.mirrSel = MDDropdownMenu( caller=self.root.ids.Smirror, items=items, width_mult=5, opening_time=0.2, use_icon_item=False, position='auto', max_height=0, callback=self.set_mirror, ) def set_mirror(self, ins): miInx = 0 for l in self.configs['mirrors']: if ins.text in l[0]: break miInx += 1 self.configs['mirror'] = self.configs['mirrors'][miInx][0] self.root.ids.Smirror.text = f"Mirror: {ins.text}".upper() dbRW.updateConfig("proxysInx", self.selLId) dbRW.updateConfig("miInx", self.configs['miInx']) toast(self.configs['mirror']) self.mirrSel.dismiss() def update_screen(self, dt): try: while not self.pbar0.empty(): sp = self.pbar0.get_nowait() if sp != 0: self.root.ids.progressBar1.value += sp else: self.root.ids.progressBar1.value = 0 except Empty: pass try: while not self.pbar1.empty(): sp = self.pbar1.get_nowait() if sp != 0: self.root.ids.progressBar2.value += sp else: self.root.ids.progressBar2.value = 0 except Empty: pass try: while not self.pbar2.empty(): sp = self.pbar2.get_nowait() if sp != 0: self.root.ids.progressBar3.value += sp else: self.root.ids.progressBar3.value = 0 except Empty: pass try: proxysL = len(self.configs['proxys']) while not self.totalpb.empty(): sp = self.totalpb.get_nowait() if sp != 0: self.root.ids.totalpb.value += sp comP = (self.root.ids.totalpb.value/proxysL)*100 self.root.ids.totalpbText.text = f"{round(comP)}%" else: self.root.ids.totalpb.max = proxysL self.root.ids.totalpb.value = 0 except Empty: pass self.speedcal() self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper() def start_scan(self, instance): # print("Clicked!!") if instance.text == "Start": self.mirrorPic() self.listPic() self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}" if len(self.configs['proxys']) == 0: try: if self.configs['proxysInx']: self.tap_target_list_view.start() self.listSel.open() # toast("Pick that list!") return except: pass PSTDialogInput().open() toast("First input proxys ip:port list then start scan.") return instance.text = "Stop" color = "#f44336" instance.md_bg_color = get_color_from_hex(color) self.theme_cls.primary_palette = "Red" if platform == "android":self._statusBarColor(color) self.scaning.put_nowait(1) self.running.put_nowait(1) IndexTime = datetime.now() dbRW.updateConfig('proxysInx', IndexTime) dbRW.updateProxysInx(IndexTime, self.selLId) dbRW.updateProxys(IndexTime, self.selLId) configs = dbRW.getAllConfigs() self.configs['totalScan'] = dbRW.getProxysInxTS(IndexTime)[0] self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}" # print(totalScan) self.configs['timeout'] = int(configs[0][3]) self.configs['fileSize'] = int(configs[0][4]) self.selLId = str(IndexTime) self.show_List() self.upScreen = Clock.schedule_interval(self.update_screen, 0.1) Thread(target=self.proxySpeedTest, args=( self.configs['proxys'], self.configs['protocol'], self.configs['mirror'], )).start() # self.proxySpeedTest('start') elif instance.text == "Stoping": toast(f"Waiting for finish {self.root.ids.currentIP.text[8:]}!") else: while not self.scaning.empty(): self.scaning.get_nowait() if not self.running.empty(): instance.text = "Stoping" # instance.text_color color = "#9E9E9E" self.theme_cls.primary_palette = "Gray" instance.md_bg_color = get_color_from_hex(color) if platform == "android":self._statusBarColor(color) def downloadChunk(self, idx, proxy_ip, filename, mirror, protocol): Logger.info(f'Scaning {idx} : Started') try: proxies = { 'http': f'{protocol}://{proxy_ip}', 'https': f'{protocol}://{proxy_ip}' } req = get( mirror, headers={ "Range": "bytes=%s-%s" % (0, self.configs['fileSize']), "user-agent": "Mozilla/5.0", }, stream=True, proxies=proxies, timeout=self.configs['timeout'] ) with(open(f'{filename}{idx}', 'ab')) as f: start = datetime.now() chunkSize = 0 # oldSpeed = 0 chunkSizeUp = 1024 for chunk in req.iter_content(chunk_size=chunkSizeUp): end = datetime.now() if 0.1 <= (end-start).seconds: delta = round(float((end - start).seconds) + float(str('0.' + str((end - start).microseconds))), 3) speed = round((chunkSize) / delta) # if oldSpeed < speed: # chunkSizeUp *= 3 # else: # chunkSizeUp = speed oldSpeed = speed start = datetime.now() self.currentSpeed.put_nowait(speed) chunkSize = 0 if chunk: chunkSize += sys.getsizeof(chunk) self.showupdate(idx) f.write(chunk) except ProxyError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}") return False except connError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}") return False except IndexError: self.showupdate(idx, 'd') Logger.info(f'Thread {idx} : You must provide a testing IP:PORT proxy') return False except ConnectTimeout: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : ConnectTimeou for {proxy_ip}") return False except ReadTimeout: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : ReadTimeout for {proxy_ip}") return False except RuntimeError: self.showupdate(idx, 'd') Logger.info(f"Thread {idx} : Set changed size during iteration. {proxy_ip}") return False except KeyboardInterrupt: self.showupdate(idx, 'd') Logger.info(f"Thread no {idx} : Exited by User.") self.showupdate(idx, 'd') def showupdate(self, idx, mode='u', error=True): if mode == 'u': if idx == 0: self.pbar0.put_nowait(1) elif idx == 1: self.pbar1.put_nowait(1) elif idx == 2: self.pbar2.put_nowait(1) elif mode == 'd': # color = "#f44336" if idx == 0: self.pbar0.put_nowait(0) elif idx == 1: self.pbar1.put_nowait(0) elif idx == 2: self.pbar2.put_nowait(0) self.root.ids.top_text.text = "0 KB/s" def proxySpeedTest(self, proxys, protocol, mirror): filename = 'chunk' unsort = list() sort = list() astTop3 = list() roundC = 0 self.totalpb.put(0) Logger.debug(proxys) for c, part in enumerate(proxys): if self.scaning.empty(): break proxy_ip = part[0].strip() self.root.ids.currentIP.text = f"CURRENT: {proxy_ip}" # Removing before test chunk file for i in range(3): if exists(f'{filename}{i}'): remove(f'{filename}{i}') # Starting chunk file downloading timeStart = datetime.now() downloaders = [ Thread( target=self.downloadChunk, args=(idx, proxy_ip, filename, mirror, protocol), ) for idx in range(3)] for _ in downloaders:_.start() for _ in downloaders:_.join() timeEnd = datetime.now() filesize = 0 for i in range(3): try: filesize = filesize + getsize(f'{filename}{i}') except FileNotFoundError: continue filesizeM = round(filesize / pow(1024, 2), 2) delta = round(float((timeEnd - timeStart).seconds) + float(str('0.' + str((timeEnd - timeStart).microseconds))), 3) speed = round(filesize) / delta for i in range(3): if exists(f'{filename}{i}'): remove(f'{filename}{i}') unsort.append( {'IP': proxy_ip, 'SIZE': filesizeM, 'TIME': delta, 'SPEED': int(speed), 'top3c': part[6]} ) sort = self.sort_Type(unsort, showL=False) sortLL = len(sort) if sortLL >= 3: for t in range(sortLL): if t < 3: if sort[t]['SPEED'] != 0: if not sort[t]['IP'] in astTop3: sort[t]['top3c'] += 1 astTop3.append(sort[t]['IP']) else: for i in range(len(astTop3)): if sort[t]['IP'] == astTop3[i]: # print(i) astTop3.pop(i) sort[t]['top3c'] -= 1 break self.show_List(sort) self.save_UpdateDB(sort) self.totalpb.put(1) roundC = c # return True self.save_UpdateDB(sort) # print(roundC) # print(self.root.ids.totalpb.value) roundC += 1 while True: if self.root.ids.totalpb.value == roundC: self.upScreen.cancel() break self.root.ids.start_stop.text = "Start" self.theme_cls.primary_palette = "LightBlue" self.root.ids.start_stop.md_bg_color = self.theme_cls.primary_color if platform == "android": self._statusBarColor() while not self.running.empty(): self.running.get_nowait() Logger.info("Scan : Finished!") def sort_Change(self, inst, ckid): if ckid and inst.active: self.sort_Type(self.data_lists, mode=inst.text, reverse=False) inst.active = False elif ckid and inst.active == False: self.sort_Type(self.data_lists, mode=inst.text, reverse=True) inst.active = True def sort_Type(self, unsort, mode='SPEED', reverse=True, showL=True): if mode == 'SERVER': mode = 'IP' if mode == 'TOP3-%':mode = 'top3c' sort = sorted(unsort, key=lambda x: x[mode], reverse=reverse) if showL: self.show_List(sort) return sort def show_List(self, data=[]): # if not self.root.ids.backdrop_front_layer.data: # print(data) # print(len(self.root.ids.backdrop_front_layer.data)) totalP = len(self.configs['proxys']) ddict = { "viewclass": "ProxyShowList", "text": "", "text1": "", "text2": "", "text3": "", "text4": "", "on_release": lambda: toast("empty!") } if not data: self.root.ids.backdrop_front_layer.data = [] for i in range(totalP): self.root.ids.backdrop_front_layer.data.append(ddict) else: for i in range(totalP): try: _ = data[i] self.root.ids.backdrop_front_layer.data[i] = { "viewclass": "ProxyShowList", "text": data[i]['IP'], "text1": f"{round((data[i]['top3c']/self.configs['totalScan'])*100)} %", "text2": f"{data[i]['SIZE']} MB", "text3": sec_to_mins(float(data[i]['TIME'])), "text4": f"{size(data[i]['SPEED'], system=alternative)}/s", "on_release": lambda x=data[i]['IP']: self.copy_proxyip(x), } except IndexError: self.root.ids.backdrop_front_layer.data[i] = ddict self.data_lists = data def copy_proxyip(self, data): toast(f"Copied: {data}") Clipboard.copy(data) def speedcal(self): speed = 0 try: while not self.currentSpeed.empty(): speed += self.currentSpeed.get_nowait() except Empty: pass if speed != 0: self.root.ids.top_text.text = f"{size(speed, system=alternative)}/s"
def syncDatabaseButton(self): if self.manager.pg_con is None: self.cursor.execute( "SELECT remote_database, db_name, db_user, db_pass, db_host, db_port FROM options" ) pg_data = self.cursor.fetchone() self.manager.connectRemoteDatabase(pg_data) pg_con = self.manager.pg_con pg_cursor = self.manager.pg_cursor if pg_con is None: toast("Something went wrong") return pg_cursor.execute("SELECT * FROM accounts") remote_data = pg_cursor.fetchall() self.cursor.execute("SELECT * FROM accounts") local_data = self.cursor.fetchall() pg_cursor.execute("SELECT master_password, salt FROM options") remote_options = pg_cursor.fetchone() self.cursor.execute("SELECT master_password, salt FROM options") local_options = self.cursor.fetchone() if remote_data and local_data: toast("Please, Delete 'accounts' table in the PostgreSQL database") # TODO user can select remote or local database for sync elif local_data: def insert_data_to_remote_database(): pg_cursor.execute("INSERT INTO options VALUES(%s, %s)", local_options) for account in local_data: pg_cursor.execute( "INSERT INTO accounts VALUES(%s, %s, %s, %s, %s)", account) pg_con.commit() toast("Sync Completed") toast("Please wait until Sync is Complete") Thread(target=insert_data_to_remote_database).start() elif remote_data: def syncWithRemoteDatabase(password): encrypted, salt = map(bytes.fromhex, remote_options) cipher = self.manager.createCipher(password, salt) try: result = cipher.decrypt(encrypted[:16], encrypted[16:], None) if result.decode() == password: sync = True except: sync = False if sync: dialog.dismiss() toast("Please wait until Sync is Complete") self.cursor.execute( "UPDATE options SET master_password = ?, salt = ? WHERE master_password = ? AND salt = ?", (*remote_options, *local_options), ) for account in remote_data: self.cursor.execute( "INSERT INTO accounts VALUES(?,?,?,?,?)", account) self.con.commit() self.manager.cipher = cipher toast("Sync Completed") else: toast("Wrong Password") dialog = MDDialog( title="Password of the Remote Backup", type="custom", content_cls=DatabasePasswordDialogContent( hint_text="Password of the Remote Backup"), buttons=[ MDFlatButton(text="Cancel", on_press=lambda x: dialog.dismiss()), MDFlatButton( text="Okay", on_press=lambda x: syncWithRemoteDatabase( dialog.content_cls.ids.password_field.text), ), ], ) dialog.open()
class MainScreen(Screen): # pass # isShownLabel = BooleanProperty(False) def add_plot(self): try: self.matrix(0,0) # self.fig1 = gcf() # return self.fig1 except Exception: self.dialog = None if not self.dialog: self.dialog = MDDialog( text="Oops! Talvez devesse importar os dados antes!", radius=[20, 7, 20, 7], ) self.dialog.open() def add_plot2(self): try: self.matrix(0,1) # self.fig2 = gcf() # return self.fig2 except Exception: self.dialog = None if not self.dialog: self.dialog = MDDialog( text="Oops! Talvez devesse importar os dados antes!", radius=[20, 7, 20, 7], ) self.dialog.open() def add_plot3(self): try: self.g_bar() except Exception: self.dialog = None if not self.dialog: self.dialog = MDDialog( text="Oops! Talvez devesse importar os dados antes!", radius=[20, 7, 20, 7], ) self.dialog.open() def Update3(self, dialog): self.dialog.dismiss() self.box1.clear_widgets() MainScreen.add_plot3(self) self.fig3 = Image(source = 'pizza.png') self.fig3.size_hint_y = 1.05 self.box1.add_widget(self.fig3) def Update(self, dialog): self.dialog.dismiss() # cla() self.box3.clear_widgets() # self.fig1 = MainScreen.add_plot(self) MainScreen.add_plot(self) self.fig1 = Image(source = 'teste1.png') # self.fig1.allow_stretch = True # self.fig1.keep_ratio = False # self.fig1.width = self.width self.fig1.size_hint_x = 1.62 self.box3.padding = 15 # self.fig1.pos = (100, 50) self.box3.add_widget(self.fig1) # self.box3.add_widget(FigureCanvasKivyAgg(self.fig1,size_hint=(1,1),pos_hint={"top":1.025})) # self.box3.add_widget(FigureCanvasAgg(self.fig1)) # canvas = self.fig1.canvas # canvas.draw() # self.box3.add_widget(canvas) # graph = Graph(xlabel='X', ylabel='Y', x_ticks_minor=5, # x_ticks_major=25, y_ticks_major=1, # y_grid_label=True, x_grid_label=True, padding=5, # x_grid=True, y_grid=True, xmin=-0, xmax=100, ymin=-1, ymax=1) # plot = MeshLinePlot(color=[1, 0, 0, 1]) # plot.points = [(x, sin(x / 10.)) for x in range(0, 101)] # graph.add_plot(plot) # self.box3.add_widget(graph) def Update2(self,dialog): self.dialog.dismiss() # cla() self.box4.clear_widgets() # self.fig2 = MainScreen.add_plot2(self) # self.box4.add_widget(FigureCanvasAgg(self.fig2,size_hint=(1,1),pos_hint={"top":1})) # canvas = self.fig2.canvas MainScreen.add_plot2(self) self.fig2 = Image(source = 'barra1.png') self.fig2.size_hint_y = 1.25 self.box4.padding = 35 self.box4.add_widget(self.fig2) def Limpar(self): self.box1.clear_widgets() def Cancelar(self, arg): self.dialog.dismiss() def Cancelar_(self, arg): self.screen_manager.current = "Scr_2" Clock.schedule_interval(self.animate, 0.01) def animate(self, dt): circProgressBar = self.manager.get_screen('main_screen').ids.cp if circProgressBar.value<80: circProgressBar.set_value(circProgressBar.value+1) else: circProgressBar.set_value(0) def tread_nick(self,arg): # adquirir a variavel de texto for obj in self.dialog.content_cls.children: self.nick = (obj.text) # create the thread to invoke other_func with arguments (2, 5) t = Thread(target=self.chess_initt) # set daemon to true so the thread dies when app is closed t.daemon = True # start the thread t.start() if self.dialog: self.dialog.dismiss() self.screen_manager.current = "Scr_2" self.event = Clock.schedule_interval(self.animate, 0.01) # Clock.schedule_once(self.animate) Clock.schedule_interval(partial(self.disable, t),0.1) # self.g_bar() def disable(self, t, what): if not t.isAlive(): Clock.unschedule(self.event) self.screen_manager.current = "Scr_1" # self.add_plot3() return False def my_elo(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( title="Atualizar dados?", text="Isso irá importar os dados e poderá levar alguns instantes.", size_hint=(0.8,1), buttons=[ MDFlatButton( text="CANCELAR", # text_color=self.box.theme_cls.primary_color, on_release=self.Cancelar ), MDFlatButton( text="ATUALIZAR?", # text_color=self.box.theme_cls.primary_color, on_release= self.Update ), ], ) self.dialog.open() def left_menu(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( # title="Atualizar dados?", type="simple", size_hint=(0.4,0.6), pos_hint= {'center_x': .75, 'center_y': .8}, items=[ Item(text="*****@*****.**", source="user-1.png"), Item(text="*****@*****.**", source="user-2.png"), Item(text="Add account", source="add-icon.png"), ], ) self.dialog.open() def nickname(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( title="Chess.com", type="custom", content_cls=Content(), size_hint=(0.8,0.6), buttons=[ MDFlatButton( text="CANCEL", on_release=self.Cancelar ), MDFlatButton( text="OK", on_release= self.tread_nick ), ], ) self.dialog.open() def country(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( title="Atualizar dados?", text="Isso irá importar os dados e poderá levar alguns instantes.", size_hint=(0.8,1), buttons=[ MDFlatButton( text="CANCELAR", # text_color=self.box.theme_cls.primary_color, on_release=self.Cancelar ), MDFlatButton( text="ATUALIZAR?", # text_color=self.box.theme_cls.primary_color, on_release= self.Update2 ), ], ) self.dialog.open() def barra_box1(self): self.dialog = None if not self.dialog: self.dialog = MDDialog( title="Atualizar dados?", text="Isso irá importar os dados e poderá levar alguns instantes.", size_hint=(0.8,1), buttons=[ MDFlatButton( text="CANCELAR", # text_color=self.box.theme_cls.primary_color, on_release=self.Cancelar ), MDFlatButton( text="ATUALIZAR?", # text_color=self.box.theme_cls.primary_color, on_release= self.Update3 ), ], ) self.dialog.open() # def table_(self): # self.data_tables = MDDataTable( # size_hint=(0.8, 0.6), # use_pagination=False, # check=True, # column_data=[ # ("No.", dp(30)), # ("Column 1", dp(30)), # ("Column 2", dp(30)), # ], # row_data=[ # (f"{i + 1}", "2.23", "3.65") # for i in range(50) # ], # ) # self.data_tables.open() # -------------------------------------------------------------------------------- ''' Ajeitar.. o comando está demorando.. Isso já é notificado pela documentação. porém não estou conseguindo fazer da maneira certa. A função init nao reconhece a screen e isso pode estar relacionado com ela não foi inicializada ainda e por isso não reconhece... ''' def tres_pontos(self): menu_labels = [ {"viewclass": "MDMenuItem", "text": "Label1"}, {"viewclass": "MDMenuItem", "text": "Label2"}, ] caller = self.manager.get_screen('main_screen').ids.botao self.dropdown = MDDropdownMenu(caller=caller, items=menu_labels, width_mult=4) # self.dropdown.open() def drop(self): self.tres_pontos() self.dropdown.open() # -------------------------------------------------------------------------------- def chess_initt(self): try: results = [] moves = [] dates = [] speed = [] games = [] my_elo = [] my_color = [] opponent_elo = [] opponent_country = [] opponent_name = [] # self.nick = nick # nick = """heru007""" chesscom = """https://www.chess.com/games/archive/""" + self.nick + """? gameOwner=other_game&gameTypes%5B0%5D=chess960 &gameTypes%5B1%5D=daily&gameType=live&page={}""" # print(chesscom) for i in range(1,5): # Get the page text = get(chesscom.format(i)).text # Soupifyd b = BeautifulSoup(text, 'html.parser') # Collect results results += pull_results(b) moves += pull_moves(b) dates += pull_dates(b) speed += pull_speed(b) games += pull_game_links(b) my_elo += pull_player_stats(b)[0] opponent_elo += pull_player_stats(b)[1] opponent_country += pull_player_stats(b)[2] opponent_name += pull_player_stats(b)[3] my_color += pull_player_stats(b)[4] # Check progress # print(i) # Make Df d = {'date': dates, 'result': results, 'moves': moves, 'speed': speed, 'link': games, 'my_elo': my_elo, 'opponent_elo': opponent_elo, 'opponent_country': opponent_country, 'opponent_name': opponent_name, 'color': my_color } games_df = DataFrame(d) # Escreve as partidas em arquivo .csv games_df.to_csv(path_or_buf='chess_games.csv') except Exception: self.dialog = None if not self.dialog: self.dialog = MDDialog( text="Oops! Algo pode ter dado errado", radius=[20, 7, 20, 7], ) self.dialog.open() def matrix(self,importar, plott): if importar == 1: self.chess_initt if plott == 0: self.games_df = read_csv('chess_games.csv', index_col=0) self.games_df.set_index(self.games_df.index[::-1], drop=True, inplace=True) self.games_df['date'] = to_datetime(self.games_df['date']) speed_games = self.games_df[self.games_df.speed=='10 min'] speed_games.reset_index(drop=True, inplace=True) speed_games.set_index(speed_games.index[::-1], drop=True, inplace=True) speed_games['my_elo_ma'] = speed_games['my_elo'][::-1].rolling(window=30).mean() speed_games['result'] = Series(where(speed_games.result.values == 'win', 1, 0), speed_games.index) # set_style("whitegrid") # figure(figsize=(13, 7)) # lineplot(y='my_elo', # x=speed_games.index, # data=speed_games, # color='darkslategray') # lineplot(y='my_elo_ma', # x=speed_games.index, # data=speed_games, # color='red') # xlabel('Number of Games', fontsize=11) # ylabel('My Elo', fontsize=13) # title('My Elo Over Time', fontsize=13) # xlim(-20) # legend(['elo', '30-day MA']) # style.context('dark_background') figure(figsize=(13, 7)) plot(speed_games.index,speed_games['my_elo'],'darkslategray',speed_games.index,speed_games['my_elo_ma'],'red') grid(True) xlabel('Number of Games', fontsize=20) ylabel('My Elo', fontsize=20) title('My Elo Over Time', fontsize=24) xlim(-20) legend(['elo', '30-day MA'],fontsize=20) subplots_adjust(bottom=0.14) xticks(fontsize=24) yticks(fontsize=24) savefig('teste1.png') elif plott == 1: self.games_df = read_csv('chess_games.csv', index_col=0) self.games_df.set_index(self.games_df.index[::-1], drop=True, inplace=True) self.games_df['date'] = to_datetime(self.games_df['date']) speed_games = self.games_df[self.games_df.speed=='10 min'] speed_games.reset_index(drop=True, inplace=True) speed_games.set_index(speed_games.index[::-1], drop=True, inplace=True) speed_games['my_elo_ma'] = speed_games['my_elo'][::-1].rolling(window=30).mean() speed_games['result'] = Series(where(speed_games.result.values == 'win', 1, 0), speed_games.index) figure(figsize=(13, 7)) quant = speed_games['opponent_country'].value_counts() quant.iloc[0:10].sort_values().plot(kind = 'barh') xlabel('Country', fontsize=24) ylabel('Number of Games', fontsize=24) title('Games against Different Countries', fontsize=26) subplots_adjust(left=0.3) xticks(fontsize=24) yticks(fontsize=24) savefig('barra1.png') def g_bar(self): # self.box1.clear_widgets() self.games_df = read_csv('chess_games.csv', index_col=0) w = Counter(self.games_df['color'])['white'] b = Counter(self.games_df['color'])['black'] # figure(figsize=(13, 17)) self.fig3, ax = subplots() size = 0.3 vals = array([[w], [b]]) cmap = get_cmap("tab20c") outer_colors = cmap(arange(3)*4) ax.pie(vals.sum(axis=1), radius=1.5, colors=outer_colors, shadow=True, wedgeprops=dict(width=size, edgecolor='w'),startangle=90) # ax.set(aspect="equal", title='Partidas Jogadas') sizes = vals/sum(vals)*100 labels = [r'Brancas', r'Pretas'] legend( loc = 'center', labels=['%s, %1.1f %%' % (l, s) for l, s in zip(labels, sizes)], title=('Partidas Jogadas'),fontsize=20, title_fontsize=20) title("Rondan1000", x=0.5,y=0.7,fontsize=28) # self.box1.add_widget(FigureCanvasKivyAgg(self.fig3,size_hint=(1.8,1),pos_hint={"top":0.98})) # self.box1.add_widget(FigureCanvasAgg(self.fig3)) # canvas = self.fig3.canvas # canvas.draw() savefig('pizza.png') # self.fig3 = Image(source = 'pizza.jpg') # self.fig3.size_hint_y = 1.06 # self.box1.add_widget(self.fig3) # aa = self.manager.get_screen('main_screen').ids.label1.opacity # print(aa) # aa = 0
class TextSubMenu(Screen): text_progress = None delete_dialog = None text_position = None text_length = None def __init__(self, text_id=None, **kwargs): super().__init__(**kwargs) Window.bind(on_keyboard=self.android_back_button) if text_id: self.text_id = text_id self.custom_on_enter() def custom_on_enter(self): connection = sqlite3.connect(os.path.join(getattr(MDApp.get_running_app(), 'user_data_dir'), 'read_runner.db')) cursor = connection.cursor() cursor.execute('SELECT * from texts WHERE text_id = ?', (self.text_id,)) text_data = cursor.fetchone() self.text_position = text_data[1] self.text_progress = text_data[2] self.text_length = len(str(text_data[6]).split()) def delete_selected_text(self): self.delete_dialog = MDDialog( title='[color=ff0000]WARNING![/color]', text='Are you sure that you want to delete this text?', pos_hint={'center_x': 0.5, 'center_y': 0.5}, size_hint=(0.9, 0.8), buttons=[MDFlatButton(text="YES, delete it!", on_release=self.confirm_deletion), MDFlatButton(text="NO, take me back!", on_release=self.close_delete_dialog)]) self.delete_dialog.open() def close_delete_dialog(self, obj=None): self.delete_dialog.dismiss() def close_text_sub_menu_dialog(self, obj=None): connection = sqlite3.connect(os.path.join(getattr(MDApp.get_running_app(), 'user_data_dir'), 'read_runner.db')) cursor = connection.cursor() cursor.execute('UPDATE texts SET text_progress = ? WHERE text_id = ?', (self.text_progress, self.text_id)) cursor.execute('UPDATE texts SET text_position = ? WHERE text_id = ?', (int(self.text_position), self.text_id)) connection.commit() MDApp.get_running_app().root.get_screen('mainscreen').custom_on_enter() MDApp.get_running_app().root.get_screen('mainscreen').text_sub_menu_dialog.dismiss() def confirm_deletion(self, obj): connection = sqlite3.connect(os.path.join(getattr(MDApp.get_running_app(), 'user_data_dir'), 'read_runner.db')) cursor = connection.cursor() cursor.execute('DELETE FROM texts WHERE text_id = ?', (self.text_id, )) connection.commit() MDApp.get_running_app().root.get_screen('mainscreen').custom_on_enter() MDApp.get_running_app().root.get_screen('mainscreen').text_sub_menu_dialog.dismiss() self.close_delete_dialog() def move_progress_backward(self): if self.text_progress >= 11: self.text_progress -= 10 self.text_position -= self.text_length/10 self.update_text_progress_label() def move_progress_forward(self): if self.text_progress <= 89: self.text_progress += 10 self.text_position += self.text_length / 10 self.update_text_progress_label() def set_progress_as_completed(self): self.text_progress = 100 self.text_position = self.text_length - 1 self.update_text_progress_label() def set_progress_as_zero(self): self.text_progress = 0 self.text_position = 1 self.update_text_progress_label() def update_text_progress_label(self): MDApp.get_running_app().root.get_screen('mainscreen').textsubmenu.ids.progress_text.text = str( f'You changed your progress to {self.text_progress}% !') def android_back_button(self, window, key, *largs): if key == 27: self.close_text_sub_menu_dialog() return True
class AppearanceOptionsScreen(Screen): sort_options = { "a_to_z": "Alphabetically (A to Z)", "z_to_a": "Alphabetically (Z to A)", "first_to_last": "Date (First to Last)", "last_to_first": "Date (Last to First)", } dialog = None sort_by = None list_subtitles_options = None def __init__(self, **kwargs): super().__init__(name=kwargs.get("name")) self.con = kwargs.get("con") self.cursor = kwargs.get("cursor") self.theme_cls = ThemeManager() self.getOptions() self.setOptions() def getOptions(self): self.cursor.execute( "SELECT sort_by, list_subtitles, animation_options FROM options") options = self.cursor.fetchall()[0] self.sort_by = options[0] self.list_subtitles_options = [ bool(int(o)) for o in options[1].split(",") ] self.animation_options = [bool(int(o)) for o in options[2].split(",")] def setOptions(self): self.ids.sort_by_item.secondary_text = self.sort_options.get( self.sort_by) self.setListSubtitlesText() self.ids.transition_animation_switch.active = self.animation_options[0] self.ids.bottomsheet_animation_switch.active = self.animation_options[ 1] def sortByButton(self): def is_current(code): return code == self.sort_by items = [] SortSelectionItem.screen = self for code, text in self.sort_options.items(): items.append(SortSelectionItem(text=text, active=is_current(code))) self.dialog = MDDialog( title="Sort By", type="confirmation", items=items, buttons=[ MDFlatButton( text="Cancel", text_color=self.theme_cls.primary_color, on_press=self.closeDialog, ), ], ) self.dialog.open() def setSortByOption(self, text): self.sort_by = list(self.sort_options.keys())[list( self.sort_options.values()).index(text)] self.cursor.execute("UPDATE options SET sort_by = ?", (self.sort_by, )) self.con.commit() self.ids.sort_by_item.secondary_text = text self.closeDialog() def listSubtitlesButton(self): self.dialog = MDDialog( title="List Subtitles", type="confirmation", items=[ SubtitlesSelectionItem(text="EMail", active=self.list_subtitles_options[0]), SubtitlesSelectionItem(text="Username", active=self.list_subtitles_options[1]), ], buttons=[ MDFlatButton( text="Cancel", text_color=self.theme_cls.primary_color, on_press=self.closeDialog, ), MDRaisedButton(text="Okay", on_press=self.getChecked), ], ) self.dialog.open() def getChecked(self, button): self.list_subtitles_options = [ item.ids.check.active for item in self.dialog.items ] new_status = ",".join( [str(int(b)) for b in self.list_subtitles_options]) self.cursor.execute("UPDATE options SET list_subtitles = ?", (new_status, )) self.con.commit() self.setListSubtitlesText() self.closeDialog() def setListSubtitlesText(self): if all(self.list_subtitles_options): text = "EMail and Username" elif self.list_subtitles_options[0]: text = "EMail" elif self.list_subtitles_options[1]: text = "Username" else: text = "No" self.ids.list_subtitles_item.secondary_text = text def animationFunctions(self): options = [] options.append( "1" if self.ids.transition_animation_switch.active else "0") options.append( "1" if self.ids.bottomsheet_animation_switch.active else "0") o = ",".join(options) self.cursor.execute("UPDATE options SET animation_options = ?", (o, )) self.con.commit() def closeDialog(self, button=None): self.dialog.dismiss() def goBackBtn(self): self.manager.setOptionsScreen()
class CoronaParfumApp(MDApp): birinci_miqdar = '10ML' ikinci_miqdar = '20ML' ucuncu_miqdar = '30ML' dorduncu_miqdar = '50ML' def __init__(self, **kwargs): super().__init__(**kwargs) self.screen = Builder.load_file('lesson.kv') Window.bind(on_keyboard=self.on_key) self.milli = '' self.profile = False self.ml = 'ML' self.idd = '' self.dictt = {} self.siyahi9 = [] self.get = requests.get('http://167.86.115.50/product/') self.new = json.loads(self.get.text) self.qiymet10_son = '' self.qiymet20_son = '' self.qiymet30_son = '' self.qiymet50_son = '' for i in self.new: self.siyahi9.append(str(i["name"]).lower().capitalize()) """ for d in self.new: self.dictt["name"] = str(d["name"]).lower().capitalize() self.dictt["image"] = d["image"] self.dictt["descrption"] = d["descrption"] self.dictt["gender"] = d["gender"] self.dictt["price_10_ml"] = d["price_10_ml"] self.dictt["price_20_ml"] = d["price_20_ml"] self.dictt["price_30_ml"] = d["price_30_ml"] self.dictt["price_50_ml"] = d["price_50_ml"] self.siyahi9.append(str(self.dictt)) self.dictt.clear() """ self.deyishken = True self.adi = '' self.cinsi = '' self.terkibi = '' self.qiymet10 = '' self.qiymet20 = '' self.qiymet30 = '' self.qiymet50 = '' for i in self.new: self.card = MDCard(orientation='horizontal') self.image = AsyncImage(source=f'{i["image"]}') self.label1 = MDLabel(text=f'{str(i["name"]).lower().capitalize()}') self.label2 = MDLabel(text=f'{str(i["gender"]).capitalize()}', font_size='14sp') self.desc = str(i["descrption"]) self.label3 = MDLabel( text=f'10ml-{i["price_10_ml"][:3] if len(i["price_10_ml"]) == 5 else i["price_10_ml"][:2]}₼\n20ml-{i["price_20_ml"][:3] if len(i["price_20_ml"]) == 5 else i["price_20_ml"][:2]}₼\n30ml-{i["price_30_ml"][:3] if len(i["price_30_ml"]) == 5 else i["price_30_ml"][:2]}₼\n50ml-{i["price_50_ml"][:3] if len(i["price_50_ml"]) == 5 else i["price_50_ml"][:2]}₼') self.qiymet10 = f'{i["price_10_ml"][:3] if len(i["price_10_ml"]) == 5 else i["price_10_ml"][:2]}' self.qiymet20 = f'{i["price_20_ml"][:3] if len(i["price_20_ml"]) == 5 else i["price_20_ml"][:2]}' self.qiymet30 = f'{i["price_30_ml"][:3] if len(i["price_30_ml"]) == 5 else i["price_30_ml"][:2]}' self.qiymet50 = f'{i["price_50_ml"][:3] if len(i["price_50_ml"]) == 5 else i["price_50_ml"][:2]}' self.card.add_widget(self.image) self.card.add_widget(self.label1) self.card.add_widget(self.label2) self.card.add_widget(self.label3) self.screen.get_screen('etirler').ids.crsl9.add_widget(self.card) self.card.bind( on_release=partial(self.etrin_seklin_ve_adin_goster, self.label1.text, self.label2.text, self.desc, self.image.source)) def yeniden(self): self.root.current = 'loadingscreen' self.on_start() def etrin_seklin_ve_adin_goster(self, etrinadi, etrincinsi, etrinterkibi, etrinsekli, value): self.deyishken = False if self.deyishken == False: self.screen.get_screen('parfumepage').ids.geriduymesi.on_release = self.rtetirler self.screen.get_screen('parfumepage').ids.etiretrafli.on_press = self.etrafli self.screen.get_screen('sifaris').ids.sifariset.on_release = self.sonsifaris self.root.current = 'parfumepage' self.screen.get_screen('parfumepage').ids.parfumephoto.source = etrinsekli self.screen.get_screen('parfumepage').ids.etrinadiyazilacaqlabel.text = str(etrinadi) self.adi = etrinadi self.cinsi = etrincinsi self.terkibi = etrinterkibi def sonsifaris(self): self.root.current = 'sonsifaris' def etrafli(self): self.root.current = 'etirmelumat' self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text = self.adi self.screen.get_screen('etirmelumat').ids.terkibi.text = self.terkibi self.screen.get_screen('etirmelumat').ids.cinsi.text = self.cinsi def rtetirler(self): self.root.current = 'etirler' def on_start(self): self.net = False try: requests.get('https://www.google.com') self.net = True self.root.current = 'menu' except ConnectionError: self.root.current = 'errorscreen' def on_key(self, window, key, *args): if key == 27: if self.root.current_screen.name != 'menu': self.root.current = 'menu' return True elif self.root.current_screen.name == 'menu': return False def profile_kecid(self): self.root.current = 'profil' def build(self): self.connect = s3.connect('user.db') self.cursor = self.connect.cursor() self.cursor.execute( """CREATE TABLE IF NOT EXISTS users(ad,soyad,dogum_tarixi,mail,nomre,sifre,istifadeci_adi,id INTEGER primary key autoincrement)""") self.connect.commit() self.connect.close() self.sm = ScreenManager() self.sm.add_widget(QabSecimi(name='qabsecimi')) self.sm.add_widget(IdIste(name='idiste')) self.sm.add_widget(SonSifaris(name='sonsifaris')) self.sm.add_widget(SifarisSehifesi(name='sifaris')) self.sm.add_widget(EtirMelumat(name='etirmelumat')) self.sm.add_widget(ParfumePage(name='parfumepage')) self.sm.add_widget(Profile(name='profil')) self.sm.add_widget(NewName(name='newname')) self.sm.add_widget(IscidiYaYox(name='iscidiyayox')) self.sm.add_widget(QabKodu(name='qabkodu')) self.sm.add_widget(MenuScreen(name='menu')) self.sm.add_widget(Etirler(name='etirler')) self.sm.add_widget(Axtaris(name='axtaris')) self.sm.add_widget(Huquqlar(name='huquqlar')) self.sm.add_widget(BizimBrendimiz(name='bizimbrendimiz')) self.sm.add_widget(BizimleElaqe(name='bizimleelaqe')) self.sm.add_widget(MarketinqVeQaydalar(name='marketinqveqaydalar')) self.sm.add_widget(GirisVeQeydiyyat(name='girisveqeydiyyat')) self.sm.add_widget(Giris(name='giris')) self.sm.add_widget(Qeydiyyat(name='qeydiyyat')) self.sm.add_widget(QeydiyyatNumEmailPassword(name='qnmp')) self.sm.add_widget(QeydiyyatAuthenticator(name='qa')) self.sm.add_widget(ErrorScreen(name='errorscreen')) self.sm.add_widget(LoadingScreen(name='loadingscreen')) self.sm.add_widget(ForgetPassword(name='forgetpassword')) self.sm.add_widget(ForgetAuthenticationCode(name='forgetauthenticationcode')) self.sm.add_widget(SifreDeyis(name='sifredeyismeyeri')) self.title = 'Korona Parfum' self.image_name_list = [] self.parfume_name_list = [] self.dict2 = {} self.s1 = 0 # ####################################################################################################################### ####################################################################################################################### return self.screen def axtar_goster(self): self.root.current = 'axtaris' self.dialog2 = MDDialog( text="Axtardığınız ətri tapmadığınız halda baş hərfini böyük hərflə yazın.", size_hint=(.7, .5), buttons=[ MDFlatButton( text="Ok", on_release=self.dialogu_dagit2 ) ] ) self.dialog2.open() def back_from_forget(self): self.root.current = 'forgetpassword' def qeydiyyatdan_kec(self): self.number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '+'] self.mail = self.screen.get_screen('qnmp').ids.email.text self.number = self.screen.get_screen('qnmp').ids.number.text self.password_new = self.screen.get_screen('qnmp').ids.password_new.text self.password_new2 = self.screen.get_screen('qnmp').ids.password_new2.text self.username = self.screen.get_screen('qnmp').ids.username.text self.a = True if not self.mail: self.sn = Snackbar(text='Email boş ola bilməz.') self.sn.show() self.a = False elif not self.number: self.sn = Snackbar(text='Nömrə boş ola bilməz.') self.sn.show() self.a = False elif not self.password_new: self.sn = Snackbar(text='Şifrə boş ola bilməz.') self.sn.show() self.a = False elif not self.password_new2: self.sn = Snackbar(text='Şifrəni təkrarlayın.') self.sn.show() self.a = False elif not self.username: self.sn = Snackbar(text='İstifadəçi adı boşdur') self.sn.show() self.a = False elif '@' not in self.mail: self.sn = Snackbar(text='Email düzgün yazılmayıb.') self.sn.show() self.a = False elif '.' not in self.mail: self.sn = Snackbar(text='Email düzgün yazılmayıb.') self.sn.show() self.a = False elif len(self.password_new) < 8: self.sn = Snackbar(text='Şifrə uzunluğu 8 deyil.') self.sn.show() self.a = False elif self.password_new != self.password_new2: self.sn = Snackbar(text='Şifrələr eyni deyil.') self.sn.show() self.a = False else: if self.a == True: self.root.current = 'qa' self.authentication_code = random.randint(111111, 999999) self.mail_content = str(self.authentication_code) self.server = slib.SMTP('64.233.184.108', 587) self.server.ehlo() self.server.starttls() self.server.login("*****@*****.**", "10bk572275") try: self.server.sendmail("*****@*****.**", str(self.mail), self.mail_content) except: pass def forget_check_username(self): self.forget_username = str(self.screen.get_screen('forgetpassword').ids.forgetusername.text) if not self.forget_username: self.sn = Snackbar(text='İstifadəçi adınzı yazın').show() self.connect = s3.connect('user.db') self.cursor = self.connect.cursor() self.username_for_check = self.screen.get_screen('forgetpassword').ids.forgetusername.text self.cursor.execute(f"""SELECT istifadeci_adi FROM users WHERE istifadeci_adi='{self.username_for_check}'""") self.connect.commit() if not self.cursor.fetchone(): self.sn = Snackbar(text="Profil mövcud deyil").show() self.connect.close() else: self.authentication_code = random.randint(111111, 999999) self.mail_content000 = str(self.authentication_code) self.connect = s3.connect('user.db') self.cursor = self.connect.cursor() self.cursor.execute(f"""SELECT mail FROM users WHERE istifadeci_adi='{self.username_for_check}' """) self.server = slib.SMTP('64.233.184.108', 587) self.server.ehlo() self.server.starttls() self.server.login("*****@*****.**", "harley572275") try: for i in self.cursor.fetchone(): self.server.sendmail("*****@*****.**", str(i), self.mail_content000) break self.dialog = MDDialog( text=("Mail adresinizə identifikasiya kodu göndərildi."), size_hint_x='.7', buttons=[ MDFlatButton( text="OK", text_color=self.theme_cls.primary_color, on_release=self.forget_authentication_code_sehifesine_kecid, ) ] ) self.dialog.open() self.connect.commit() self.connect.close() except: self.dialog = MDDialog( text=("Mail adresinizə identifikasiya kodu göndərildi."), size_hint_x='.7', buttons=[ MDFlatButton( text="OK", text_color=self.theme_cls.primary_color, on_release=self.forget_authentication_code_sehifesine_kecid, ) ] ) self.dialog.open() self.connect.commit() self.connect.close() def forget_authentication_code_sehifesine_kecid(self, value): self.dialog.dismiss() self.root.current = 'forgetauthenticationcode' def forget_password(self): self.root.current = 'forgetpassword' def etirlerkechid(self): self.root.current = 'etirler' def resend_code(self): self.authentication_code = random.randint(111111, 999999) self.mail_content = str(self.authentication_code) self.server = slib.SMTP('64.233.184.108', 587) self.server.ehlo() self.server.starttls() self.server.login("*****@*****.**", "harley572275") try: self.server.sendmail("*****@*****.**", str(self.mail), self.mail_content) self.sn5 = Snackbar( text='Kod göndərildi.' ) self.sn5.show() except: self.sn5 = Snackbar( text='Kod göndərildi.' ) self.sn5.show() def idyoxla(self): self.idfield = self.screen.get_screen('idiste').ids.sifarisciidsi.text if not self.idfield: toast("Zəhmət olmasa İD yazın") else: self.id = self.screen.get_screen('idiste').ids.sifarisciidsi.text url = 'http://167.86.115.50/api/register/' data = { "username": f"{str(self.username1.strip())}", "password": f"{self.password_new1}", "last_name": f"{str(self.soyad.strip())}", "first_name": f"{str(self.ad1.strip())}", "invite_id": f"{self.id}", "email": f"{self.email1.strip()}" } post = requests.post(url, data) self.new = json.loads(post.text) with open('username.txt', 'w+', encoding='utf-8') as file1: file1.write(str(self.new['username'])) with open('email.txt', 'w+', encoding='utf-8') as file2: file2.write(str(self.new['email'])) with open('id.txt', 'w+', encoding='utf-8') as file3: file3.write(str(self.new['id'])) if self.new['username'] == ["A user with that username already exists."]: toast('İstifadəçi adını dəyişin') self.root.current = 'qnmp' elif self.new['email'] == ['Enter a valid email address.']: toast('Email düzgün yazılmayıb') self.root.current = 'qnmp' else: toast('Qeydiyyat tamamlandı.Giriş edin.') self.root.current = 'giris' def LogIn(self): self.istifadechi_adi = self.screen.get_screen('giris').ids.istifadeciadi.text self.password = self.screen.get_screen('giris').ids.sifre.text if not self.istifadechi_adi: toast('Məlumatlar boş ola bilməz') if not self.password: toast('Məlumatlar boş ola bilməz') data = { "username": f"{str(self.istifadechi_adi).strip()}", "password": f"{str(self.password).strip()}" } post = requests.post('http://167.86.115.50/auth/token/login', data=data) new = json.loads(post.text) if 'auth_token' in str(post.text): self.profile = True self.root.current = 'menu' girish.append("entered") with open('username.txt', 'r+') as file1: self.screen.get_screen('profil').ids.labelforusername.text = file1.read() with open('email.txt', 'r+') as file2: self.screen.get_screen('profil').ids.labelformail.text = file2.read() with open('id.txt', 'r+') as file3: self.screen.get_screen('profil').ids.labelforid.text = file3.read() self.deyismeli_button = self.screen.get_screen('menu').ids.button_for_login_and_signup self.deyismeli_button.text = 'Profil' else: toast('İstifadəçi adı yaxud parol səhvdir') def qacmenuya(self): url = 'http://167.86.115.50/api/register/' data = { "username": f"{str(self.username1.strip())}", "password": f"{self.password_new1}", "last_name": f"{str(self.soyad.strip())}", "first_name": f"{str(self.ad1.strip())}", "invite_id": "0", "email": f"{self.email1.strip()}" } post = requests.post(url, data) self.new = json.loads(post.text) with open('username.txt', 'w+', encoding='utf-8') as file1: file1.write(str(self.new['username'])) with open('email.txt', 'w+', encoding='utf-8') as file2: file2.write(str(self.new['email'])) with open('id.txt', 'w+', encoding='utf-8') as file3: file3.write(str(self.new['id'])) if self.new['username'] == ["A user with that username already exists."]: toast('İstifadəçi adını dəyişin') self.root.current = 'qnmp' elif self.new['email'] == ['Enter a valid email address.']: toast('Email düzgün yazılmayıb') self.root.current = 'qnmp' else: toast('Qeydiyyat tamamlandı.Giriş edin.') self.root.current = 'giris' def check_authentication_code(self): self.authentication_text = self.screen.get_screen('qa').ids.authcode.text if str(self.authentication_text) == str(self.authentication_code): self.root.current = 'idiste' girish.append("entered") self.ad1 = self.screen.get_screen('qeydiyyat').ids.ad.text self.soyad1 = self.screen.get_screen('qeydiyyat').ids.soyad.text self.email1 = self.screen.get_screen('qnmp').ids.email.text self.number1 = self.screen.get_screen('qnmp').ids.number.text self.password_new1 = self.screen.get_screen('qnmp').ids.password_new.text self.username1 = self.screen.get_screen('qnmp').ids.username.text self.ad1 = str(self.ad1.strip()) self.soyad1 = str(self.soyad1.strip()) self.email1 = str(self.email1.strip()) self.number1 = str(self.number1.strip()) self.password_new1 = str(self.password_new1.strip()) self.username1 = str(self.username1.strip()) else: toast('Kod düzgün deyil') def forget_check_authentication_code(self): self.forget_authentication_code_textfield_text = self.screen.get_screen( 'forgetauthenticationcode').ids.forgetauthenticationcode.text if not self.forget_authentication_code_textfield_text: self.sn = Snackbar( text='Kodu daxil edin.' ).show() elif str(self.forget_authentication_code_textfield_text) != self.mail_content000: self.sn = Snackbar( text='Kod düzgün deyil.' ).show() elif str(self.forget_authentication_code_textfield_text) == self.mail_content000: self.root.current = 'sifredeyismeyeri' def check_new_password(self): self.new_password = str(self.screen.get_screen('sifredeyismeyeri').ids.newpassword.text) self.new_password2 = str(self.screen.get_screen('sifredeyismeyeri').ids.newpasswordagain.text) self.pass_text_list = [] for i in str(self.new_password): self.pass_text_list.append(i) if len(self.pass_text_list) < 8: self.sn = Snackbar( text="Şifrə uzunluğu 8 deyil." ) self.sn.show() if not self.new_password: self.sn = Snackbar( text="Şifrəni daxil edin." ).show() if not self.new_password2: self.sn = Snackbar( text="Şifrəni təkrarlayın." ).show() if self.new_password != self.new_password2: self.sn = Snackbar( text="Şifrələr eyni deyil." ).show() self.connect = s3.connect('user.db') self.cursor = self.connect.cursor() self.cursor.execute( f"""UPDATE users SET sifre='{self.new_password}' WHERE istifadeci_adi='{self.forget_username}'""") self.dialog2 = MDDialog( text='Şifrəniz dəyişdirildi.', size_hint_x='.7', buttons=[MDRaisedButton(text='OK', on_release=self.kecmenyuya2)] ).open() self.connect.commit() self.connect.close() def forget_resend_authentication_code(self): self.authentication_code = random.randint(111111, 999999) self.mail_content000 = str(self.authentication_code) self.connect = s3.connect('user.db') self.cursor = self.connect.cursor() self.cursor.execute(f"""SELECT mail FROM users WHERE istifadeci_adi='{self.username_for_check}' """) self.server = slib.SMTP('64.233.184.108', 587) self.server.ehlo() self.server.starttls() self.server.login("*****@*****.**", "harley572275") try: for i in self.cursor.fetchone(): self.server.sendmail("*****@*****.**", str(i), self.mail_content000) self.dialog = MDDialog( size_hint_x='.7', text=("Mail adresinizə identifikasiya kodu göndərildi."), buttons=[ MDFlatButton( text="OK", text_color=self.theme_cls.primary_color, on_release=self.forget_authentication_code_sehifesine_kecid, ) ] ) self.dialog.open() self.connect.commit() self.connect.close() except: self.dialog = MDDialog( text=("Mail adresinizə identifikasiya kodu göndərildi."), buttons=[ MDFlatButton( text="OK", text_color=self.theme_cls.primary_color, on_release=self.forget_authentication_code_sehifesine_kecid, ) ] ) self.dialog.open() self.connect.commit() self.connect.close() def first_sign_check(self): self.ad = self.screen.get_screen('qeydiyyat').ids.ad.text self.soyad = self.screen.get_screen('qeydiyyat').ids.soyad.text self.dtarixi_text = self.screen.get_screen('qeydiyyat').ids.dogumbutton.text if self.dtarixi_text == 'Doğum tarixi' or not self.ad or not self.soyad: toast('Məlumatlarınızı düzgün qeyd edin') else: self.root.current = 'qnmp' def show_date(self): self.picker = MDDatePicker(callback=self.got_date, year=2000, month=1, day=1) self.picker.open() def got_date(self, the_date): self.screen.get_screen('qeydiyyat').ids.dogumbutton.text = str(the_date) self.birthday = str(the_date) def deyismeli(self): if str(self.screen.get_screen('menu').ids.button_for_login_and_signup.text) == 'Profil': self.root.current = 'profil' else: self.root.current = 'girisveqeydiyyat' def sqy10(self): self.milli = '10ML' for i in self.new: if i["name"] == str(self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text): self.qiymet10_son = str(i["price_10_ml"]) self.qiymet20_son = str(i["price_20_ml"]) self.qiymet30_son = str(i["price_30_ml"]) self.qiymet50_son = str(i["price_50_ml"]) self.ad_sifaris = self.screen.get_screen('sonsifaris').ids['adsoyadsifaris'].text self.nomre_sifaris = str(self.screen.get_screen('sonsifaris').ids.nomresifaris.text) self.unvan_sifaris = str(self.screen.get_screen('sonsifaris').ids.unvansifaris.text) self.content1 = f"{self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text}\n" \ "10ML\n" \ f"{self.ad_sifaris}\n" \ f"{self.nomre_sifaris}\n" \ f"{self.unvan_sifaris}" if not self.ad_sifaris: toast('Məlumatları düzgün qeyd edin') elif not self.nomre_sifaris: toast('Məlumatları düzgün qeyd edin') elif not self.unvan_sifaris: toast('Məlumatları düzgün qeyd edin') else: self.root.current = 'iscidiyayox' self.milli = '10ML' self.qiymet = f'{self.qiymet10_son}' def sqy20(self): self.milli = '20ML' for i in self.new: if i["name"] == str(self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text): self.qiymet10_son = str(i["price_10_ml"]) self.qiymet20_son = str(i["price_20_ml"]) self.qiymet30_son = str(i["price_30_ml"]) self.qiymet50_son = str(i["price_50_ml"]) self.ad_field = str(self.screen.get_screen('sonsifaris').ids.adsoyadsifaris.text) self.nomre_field = str(self.screen.get_screen('sonsifaris').ids.nomresifaris.text) self.unvan_field = str(self.screen.get_screen('sonsifaris').ids.unvansifaris.text) self.content1 = f"{self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text}\n" \ "20ML\n" \ f"{self.ad_field}\n" \ f"{self.nomre_field}\n" \ f"{self.unvan_field}" if not self.ad_field: toast('Məlumatları düzgün qeyd edin') elif not self.nomre_field: toast('Məlumatları düzgün qeyd edin') elif not self.unvan_field: toast('Məlumatları düzgün qeyd edin') else: self.root.current = 'iscidiyayox' self.milli = '20ML' self.qiymet = f'{self.qiymet20_son}' def sqy30(self): self.milli = '30ML' for i in self.new: if i["name"] == str(self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text): self.qiymet10_son = str(i["price_10_ml"]) self.qiymet20_son = str(i["price_20_ml"]) self.qiymet30_son = str(i["price_30_ml"]) self.qiymet50_son = str(i["price_50_ml"]) self.ad_field = str(self.screen.get_screen('sonsifaris').ids.adsoyadsifaris.text) self.nomre_field = str(self.screen.get_screen('sonsifaris').ids.nomresifaris.text) self.unvan_field = str(self.screen.get_screen('sonsifaris').ids.unvansifaris.text) self.content1 = f"{self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text}\n" \ "30ML\n" \ f"{self.ad_field}\n" \ f"{self.nomre_field}\n" \ f"{self.unvan_field}" if not self.ad_field: toast('Məlumatları düzgün qeyd edin') elif not self.nomre_field: toast('Məlumatları düzgün qeyd edin') elif not self.unvan_field: toast('Məlumatları düzgün qeyd edin') else: self.root.current = 'iscidiyayox' self.milli = '30ML' self.qiymet = f'{self.qiymet30_son}' def sqy50(self): self.milli = '50ML' for i in self.new: if i["name"] == str(self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text): self.qiymet10_son = str(i["price_10_ml"]) self.qiymet20_son = str(i["price_20_ml"]) self.qiymet30_son = str(i["price_30_ml"]) self.qiymet50_son = str(i["price_50_ml"]) self.ad_field = str(self.screen.get_screen('sonsifaris').ids.adsoyadsifaris.text) self.nomre_field = str(self.screen.get_screen('sonsifaris').ids.nomresifaris.text) self.unvan_field = str(self.screen.get_screen('sonsifaris').ids.unvansifaris.text) self.content1 = f"{self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text}\n" \ "MIQDAR: 50ML\n" \ f"AD VE SOYAD: {self.ad_field}\n" \ f"ELAQE NOMRESI: {self.nomre_field}\n" \ f"UNVAN: {self.unvan_field}" if not self.ad_field: toast('Məlumatları düzgün qeyd edin') elif not self.nomre_field: toast('Məlumatları düzgün qeyd edin') elif not self.unvan_field: toast('Məlumatları düzgün qeyd edin') else: self.root.current = 'iscidiyayox' self.milli = '50ML' self.qiymet = f'{self.qiymet50_son}' def gonder(self): self.server = slib.SMTP('64.233.184.108', 587) self.server.ehlo() self.server.starttls() self.server.login("*****@*****.**", "harley572275") self.server.sendmail("*****@*****.**", "*****@*****.**", self.content1) self.root.current = 'menu' self.dialog56 = MDDialog( text="Sifarişiniz üçün təşəkkürlər.Sizinlə 24 saat ərzində əlaqə saxlanılacaq.", size_hint_y=.7, buttons=[ MDFlatButton(text="Ok", on_release=self.dismis56) ] ) self.dialog56.open() def sifariset(self): for i in self.new: if i["name"] == str(self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text): self.screen.get_screen('sifaris').ids.ml10.text = str(i["price_10_ml"]) self.screen.get_screen('sifaris').ids.ml20.text = str(i["price_20_ml"]) self.screen.get_screen('sifaris').ids.ml30.text = str(i["price_30_ml"]) self.screen.get_screen('sifaris').ids.ml50.text = str(i["price_50_ml"]) self.root.current = 'sonsifaris' def dismis56(self, value): self.dialog56.dismiss() def sifarisekecid(self): self.sonsifaris() def etir_haqqinda_melumat(self): for i in self.new: if i["name"] == self.adad.upper(): self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text = str( i["name"]).lower().capitalize() self.screen.get_screen('etirmelumat').ids.terkibi.text = str(i["descrption"]) self.screen.get_screen('etirmelumat').ids.cinsi.text = str(i["gender"]).capitalize() self.root.current = 'etirmelumat' """ self.screen.get_screen('etirmelumat').ids.qiymet10ml.text = f'{self.lazimli_list[2]}{self.lazimli_list[3]}AZN' self.screen.get_screen('etirmelumat').ids.qiymet20ml.text = f'{self.lazimli_list[6]}{self.lazimli_list[7]}AZN' self.screen.get_screen('etirmelumat').ids.qiymet30ml.text = f'{self.lazimli_list[10]}{self.lazimli_list[11]}AZN' if len(self.lazimli_list) == 17: self.screen.get_screen('etirmelumat').ids.qiymet50ml.text = f'{self.lazimli_list[14]}{self.lazimli_list[15]}{self.lazimli_list[16]}AZN' else: self.screen.get_screen( 'etirmelumat').ids.qiymet50ml.text = f'{self.lazimli_list[14]}{self.lazimli_list[15]}AZN' self.root.current = 'etirmelumat' """ ####################################################################################################################################################### def on_stop(self): girish.clear() def sifre_deyisme_legv_et(self): self.dialog = MDDialog( text=("Ləğv etmək istədiyinizdən əminsinizmi?"), size_hint_x='.7', buttons=[ MDFlatButton( text="Geri", text_color=self.theme_cls.primary_color, on_release=self.dialogu_dagit, ), MDRaisedButton( text="OK", text_color=self.theme_cls.primary_color, on_release=self.kecmenyuya ) ] ) self.dialog.open() def kecmenyuya(self, value): self.dialog.dismiss() self.root.current = 'menu' def kecmenyuya2(self, value): self.root.current = 'menu' def dialogu_dagit2(self, value): self.dialog2.dismiss(force=True) def dialogu_dagit(self, value): self.dialog.dismiss() def yazdir(self, name): self.adad = str(name) self.screen.get_screen('parfumepage').ids.etrinadiyazilacaqlabel.text = str(name) for i in self.new: if i["name"] == str(name).upper(): self.screen.get_screen('parfumepage').ids.parfumephoto.source = i["image"] else: pass self.root.current = 'parfumepage' def set_list_md_icons(self, text="", search=False): '''Builds a list of icons for the screen MDIcons.''' """ self.current = os.getcwd() self.dict1 = {} try: self.book = load_workbook('duxusiyahi.xlsx') except: os.chdir('..') self.book = load_workbook('duxusiyahi.xlsx') self.duxu_adlari = [] self.sheet = self.book['sheet'] for row in self.sheet.rows: if str(row[1].value) == 'None': pass else: self.duxu_adlari.append(str(row[1].value).lower().capitalize()) self.sekil_adlari = [] try: if os.getcwd().endswith('_files'): os.chdir('..') for i in os.listdir(os.chdir('allimages_files')): self.sekil_adlari.append(str(i)) else: for i in os.listdir(os.chdir('allimages_files')): self.sekil_adlari.append(str(i)) except: os.chdir('..') for i in os.listdir(os.chdir('allimages_files')): self.sekil_adlari.append(str(i)) self.s = 0 for t in self.duxu_adlari: self.dict1[f'{t}'] = self.sekil_adlari[self.s] self.s += 1 """ def add_icon_item(name_icon): self.screen.get_screen('axtaris').ids.rv.data.append( { "viewclass": "CustomOneLineIconListItem", "icon": 'atom', "text": name_icon, "on_press": partial(self.yazdir, name_icon) } ) self.screen.get_screen('axtaris').ids.rv.data = [] for name_icon in self.siyahi9: if search: if text in name_icon: add_icon_item(name_icon) else: add_icon_item(name_icon) def idyazildi(self): self.idd = str(self.screen.get_screen('iscidiyayox').ids.sifarisbitdiid.text) self.qabsecimi() def qabsecimi(self): self.nm = '' self.root.current = 'qabsecimi' self.siyahi = {'eight.jpg30': '#101', 'eleven.jpg50': '#102', 'fifteen.jpg50': '#103', 'five.jpg30': '#104', 'four.jpg50': '#105', 'fourteen.jpg10': '#106', 'nine.jpg50': '#107', 'nineteen.jpg50': '#108', 'seven.jpg50': '#109', 'six.jpg30': '#110', 'sixteen.jpg30': '#111', 'ten.jpg30': "#112", 'thirteen.jpg50': "#113", 'three.jpg50': "#114", 'twelve.jpg30': "#115", 'twenty.jpg30': "#116", 'twentyeight.jpg20': "#117", 'twentyfive.jpg50': "#118", 'twentyfour.jpg30': "#119", 'twentynine.jpg30': "#120", 'twentyone.jpg30': "#121", 'twentyseven.jpg50': "#122", 'twentysix.jpg50': "#123", 'twentythree.jpg20': "#124", 'twentytwo.jpg50': "#125", 'two.jpg10': "#126" } for qab in self.siyahi.keys(): a, b = os.path.splitext(qab) self.label = MDLabel(text=f'{b[4:]} ML Kod-{self.siyahi[f"{qab}"]}', halign='center', size_hint_y=.1) self.image = Image(source=f'{a}.jpg', size_hint_y=.9) self.card = MDCard(orientation='vertical', on_release=self.yaz) self.card.add_widget(self.label ) self.card.add_widget( self.image ) self.screen.get_screen('qabsecimi').ids.crsl1.add_widget(self.card) def qabsecimioldu(self): self.qiymet = '' self.kod_field = self.screen.get_screen('qabkodu').ids.kod.text if not self.kod_field: toast('Zəhmət olmasa qabın kodunu yazın') else: for i in self.new: if i["name"] == str(self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text).upper(): self.qiymet10_son = str(i["price_10_ml"]) self.qiymet20_son = str(i["price_20_ml"]) self.qiymet30_son = str(i["price_30_ml"]) self.qiymet50_son = str(i["price_50_ml"]) if self.milli == '10ML': self.qiymet = self.qiymet10_son elif self.milli == '20ML': self.qiymet = self.qiymet20_son elif self.milli == '30ML': self.qiymet = self.qiymet30_son elif self.milli == '50ML': self.qiymet = self.qiymet50_son for i in self.siyahi.keys(): if self.siyahi[str(i)] == str(self.kod_field): toast('Sifarişiniz qəbul olundu.') a, b = os.path.splitext(f'{i}') msg = MIMEMultipart() msg['Subject'] = "Yeni Sifariş" msg['From'] = '*****@*****.**' msg['To'] = '*****@*****.**' self.ad_str = self.screen.get_screen('sonsifaris').ids.adsoyadsifaris.text self.nomre_str = self.screen.get_screen('sonsifaris').ids.nomresifaris.text self.unvan_str = self.screen.get_screen('sonsifaris').ids.unvansifaris.text self.etrin_adi = self.screen.get_screen('etirmelumat').ids.etrinadisifarissehifesi.text try: self.content999 = MIMEText( f'SIFARİŞ HAQQINDA MƏLUMAT\n{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day} {datetime.datetime.now().hour}:{datetime.datetime.now().minute}\nƏTRİN ADI - {self.etrin_adi}\nQİYMƏTİ - {self.qiymet} AZN\nMİQDARI - {self.milli}\n' f'QABIN KODU - {self.kod_field}\n\nSİFARİŞÇİ HAQQINDA MƏLUMAT\nADI - {self.ad_str}\n' f'TELEFON NÖMRƏSİ - {self.nomre_str}\nÜNVANI - {self.unvan_str}\n' f'SİFARİŞÇİNİN İD KODU - {self.idd}') msg.attach(self.content999) server = smtplib.SMTP('64.233.184.108', 587) server.ehlo() server.starttls() server.login('*****@*****.**', password='******') server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) server.quit() self.root.current = 'menu' except: self.content999 = MIMEText( f'SIFARİŞ HAQQINDA MƏLUMAT\n{datetime.datetime.now().year}-{datetime.datetime.now().month}-{datetime.datetime.now().day} {datetime.datetime.now().hour}:{datetime.datetime.now().minute}\nƏTRİN ADI - {self.etrin_adi}\nQİYMƏTİ - {self.qiymet} AZN\nMİQDARI - {self.milli}\n' f'QABIN KODU - {self.kod_field}\n\nSİFARİŞÇİ HAQQINDA MƏLUMAT\nADI - {self.ad_str}\n' f'TELEFON NÖMRƏSİ - {self.nomre_str}\nÜNVANI - {self.unvan_str}\n') msg.attach(self.content999) server = smtplib.SMTP('64.233.184.108', 587) server.ehlo() server.starttls() server.login('*****@*****.**', password='******') server.sendmail('*****@*****.**', '*****@*****.**', msg.as_string()) server.quit() self.root.current = 'menu' else: toast('Sifarişiniz qəbul olundu.') def yaz(self, value): self.root.current = 'qabkodu'
class RightMenuIconButtonHabit(IRightBodyTouch, MDIconButton): habit_instance = ObjectProperty() def __init__(self, **kwargs): super().__init__(**kwargs) # content for menu habit_menu_items = [{ "text": 'edit', }, { 'text': 'delete', }] # created menu as dropdown menu self.habit_menu = MDDropdownMenu( caller=self, items=habit_menu_items, width_mult=2, selected_color=self.theme_cls.primary_dark_hue, ) # pressing triggeres habit_menu_call self.habit_menu.bind(on_release=self.habit_menu_call) def habit_menu_call(self, instance_menu, instance_menu_item, *args): # for easier referencing of Habit (for delition, editing, ...) habit_instance = self.parent.parent habit_list_instance = self.parent.parent.parent # click delete if instance_menu_item.text == 'delete': self.habit_menu_delete(instance_menu, habit_instance, habit_list_instance) # click edit elif instance_menu_item.text == 'edit': self.edit_habit_menu(instance_menu, habit_instance) def habit_menu_delete(self, menu_instance, habit_instance, habit_list_instance, *args): habit_list_instance.remove_widget(habit_instance) menu_instance.dismiss() def edit_habit_menu(self, menu_instance, habit_instance, *args): # task_instance needs to be parsed to self.change_habit (parsed function) self.show_habit_template(title='Change Habit', habit_instance=habit_instance, function=lambda *args: self.change_habit( habit_instance, template, priority_dict=priority_translation)) # reference to content of MDDialog template = self.dialog.content_cls # dictionary for convertion of priority as int (in Habit) and HabitTemplate.MDBoxLayout.priority_choice priority_translation = { '0': 'low', '1': 'normal', '2': 'high', '3': 'very high' } priority_key = str(len(habit_instance.ids.priority_id.text)) # set habit attributes in HabitTemplate Widgets template.ids.habit_description.text = habit_instance.text # set priority chooser to value of priority in Habit template.ids.priority_choice.text = priority_translation[str( priority_key)] # set value for reminder days to value habit.secondary_text if not empty downed_keys = [ item for item in habit_instance.secondary_text.split(', ') if item not in [None, '', ' '] ] for key in downed_keys: template.habit_repetition[str(key)] = 'down' # sets value for repetition times per day repetition = int(habit_instance.done_counter_max) template.ids.times_repetition.text = str(repetition) # set value for reminder days to value habit.tertiary_text if not empty times = [ item for item in habit_instance.tertiary_text.split(', ') if item not in [None, '', ' '] ] for time in times: template.ids.reminder_list.add_widget( template.Reminder(text=time)) # close HabitTemplate menu_instance.dismiss() def show_habit_template(self, title, habit_instance=None, function=None): self.dialog = None if not self.dialog: self.dialog = MDDialog( title=str(title) + ':', type="custom", content_cls=HabitTemplate(habit_instance=habit_instance), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_release=self.close_habit_template), MDFlatButton(text="SAVE", text_color=self.theme_cls.primary_color, on_release=(lambda *args: function())), ], ) # deactivated due to visible, not focused background after self.task_menu.dismiss() # self.dialog.set_normal_height() self.dialog.open() def close_habit_template(self, *args): self.dialog.dismiss() def change_habit(self, habit_instance, template, priority_dict, *args): # collect date from template description = template.ids.habit_description.text reminder_days = ', '.join([ key for key, value in template.habit_repetition.items() if value == 'down' ]) reminder_times = ', '.join( sorted( set([ child.text for child in template.ids.reminder_list.children ]))) new_priority = [ key for key, value in priority_dict.items() if value == template.ids.priority_choice.text ] repetition_times = int(template.ids.times_repetition.text) # update values of habit_instance habit_instance.text = str(description) habit_instance.secondary_text = str(reminder_days) habit_instance.tertiary_text = str(reminder_times) habit_instance.priority = str(new_priority[0]) habit_instance.done_counter_max = int(repetition_times) # close HabitTemplate self.dialog.dismiss()
class NewActivityWindow(Screen): def load_nav_drawer(self): ContentNavigationDrawer.populateNavDrawerValues(self) #Load menu items disaster_list = get_disasters() self.menu = MDDropdownMenu(caller=self.ids['drop_item'], position="center", width_mult=5, callback=self.set_item) for i in disaster_list: self.menu.items.append({"text": str(i)}) def cancel_act_creation(self): self.manager.current = 'activity_window' self.manager.transition.direction = 'right' def set_item(self, instance): self.ids['drop_item'].set_item(instance.text) self.menu.dismiss() def create_activity(self, actname, loc, drop_item, target): actname = actname.text loc = loc.text disaster = drop_item.current_item target = target.text valid_str = "" if actname == "": valid_str = "Name is blank" elif loc == "": valid_str = "Location is blank" elif target == "": valid_str = "Target Amount is blank" if valid_str != "": ok_button = MDFlatButton(text='OK', on_release=self.dialog_close) self.dialog = MDDialog(title='Alert !', text=valid_str, size_hint=(0.7, 1), buttons=[ok_button]) self.dialog.open() else: status = "Y" query1 = f'''INSERT INTO ACTIVITY(ORG_ID, NAME, LOCATION, DISASTER, TARGET_AMT, STATUS) VALUES ({globalvariables.var_org_id},UPPER('{actname}'),'{loc}','{disaster}',{target}, '{status}')''' # run direct SQL stmt = ibm_db.exec_immediate(connection.conn, query1) if ibm_db.num_rows(stmt) > 0: self.ids[ 'actname'].text = "" #Setting the values to NULL after sucessfull registration self.ids['loc'].text = "" self.ids['drop_item'].text = "" self.ids['target'].text = "" ok_button = MDFlatButton(text='OK', on_release=self.dialog_close) self.dialog = MDDialog(title='Activity Created', text="Lets start helping!", size_hint=(0.7, 1), buttons=[ok_button]) self.dialog.open() self.manager.transition.direction = 'left' self.manager.current = 'activity_window' self.manager.get_screen('activity_window').load_activity_page() def dialog_close(self, obj): self.dialog.dismiss()
class NewApp(MDApp): def build(self): self.title = "E-Medicare" self.theme_cls.primary_palette = "Green" self.theme_cls.primary_hue = "A700" self.theme_cls.theme_style = "Dark" self.strng = Builder.load_string(helpstr) return self.strng def check_username(self): self.username_text = self.strng.get_screen( 'usernamescreen').ids.username_text_fied.text self.password_text = self.strng.get_screen( 'usernamescreen').ids.password_text_fied.text username_check_false = True try: int(self.username_text) except: username_check_false = False if username_check_false or self.username_text.split() == []: cancel_btn_username_dialogue = MDFlatButton( text='Retry', on_release=self.close_username_dialogue) self.dialog = MDDialog(title='Invalid Username', text="Please input a valid username", size_hint=(0.7, 0.2), buttons=[cancel_btn_username_dialogue]) self.dialog.open() else: self.strng.get_screen( 'usernamescreen').ids.disabled_button.disabled = False def close_username_dialogue(self, obj): self.dialog.dismiss() def show_date_picker(self): date_dialog = MDDatePicker( callback=self.get_date, year=1999, month=1, day=1, ) date_dialog.open() def get_date(self, date): self.dob = date self.strng.get_screen('dob').ids.date_picker.text = str(self.dob) self.strng.get_screen('dob').ids.second_disabled.disabled = False # Storing of DATA self.store.put('UserInfo', name=self.username_text, password=self.password_text, dob=str(self.dob)) self.username_changer() def username_changer(self): self.strng.get_screen( 'mainscreen' ).ids.profile_name.text = f"Welcome {self.store.get('UserInfo')['name']}" def on_start(self): self.store = JsonStore("userProfile.json") try: if self.store.get('UserInfo')['name'] != "": self.username_changer() self.strng.get_screen( 'mainscreen').manager.current = 'mainscreen' except KeyError: self.strng.get_screen( 'welcomescreen').manager.current = 'welcomescreen'
class DefaultScreen(Screen): class NFCListener(CardListener): def __init__(self, default_screen: "DefaultScreen"): self.default_screen = default_screen def card_is_presented(self, uid=None) -> None: self.default_screen.nfc_card_presented(uid) def __init__(self, **kwargs): # Call to super (Screen class) super(DefaultScreen, self).__init__(**kwargs) self.nfc_listener = DefaultScreen.NFCListener(self) # Create a session to maintain cookie data for this instance self.event_loop: AbstractEventLoop = App.get_running_app().loop # Store the dialog that we use to select an active user self.user_select_dialog: MDDialog = None # Store a list of users we want to be able to select self.users_to_select = [] # Add extra information to footer text self.ids.copyright.text = self.ids.copyright.text.replace("%year%", str(datetime.datetime.now().year)) \ .replace("%date%", str(datetime.datetime.now().strftime("%Y/%m/%d @ %H:%M:%S"))) def register_card_listener(self, card_connection_manager: "CardConnectionManager"): card_connection_manager.register_listener(self.nfc_listener) # # restarts the card listener upon reentry of the screen # def on_enter(self, *args): # Reset active user, because we are back at this screen. App.get_running_app().active_user = None self.ids.spinner.active = False # Start loading user data. self.event_loop.call_soon_threadsafe(self.load_user_data) def to_credits(self): self.manager.transition = SlideTransition(direction='left') self.manager.current = Screens.CREDITS_SCREEN.value # # gets called when the 'NFC kaart vergeten button' is pressed # Shows a dialog to select a user. # def on_no_nfc(self): # Check if the dialog has been opened before (or whether the data has been loaded properly) if not self.user_select_dialog or len(self.user_select_dialog.items) < 1: # If not, create a dialog once. self.user_select_dialog = MDDialog( type="confirmation", items=self.users_to_select ) # Open the dialog once it's been created. self.user_select_dialog.open() def load_user_data(self, callback: Optional[Callable] = None): if len(App.get_running_app().user_mapping) > 0: Logger.debug("StellaPayUI: Not loading user data again") return user_data = App.get_running_app().session_manager.do_get_request(url=Connections.get_users()) Logger.debug("StellaPayUI: Loaded user data") App.get_running_app().user_mapping = {} if user_data and user_data.ok: # convert to json user_json = user_data.json() print(f"StellaPayUI: Loading user mapping on thread {threading.current_thread().name}") # append json to list and sort the list for user in user_json: # store all emails adressed in the sheet_menu App.get_running_app().user_mapping[user["name"]] = user["email"] # Sort items App.get_running_app().user_mapping = OrderedDict( sorted(App.get_running_app().user_mapping.items(), key=lambda x: x[0])) # Create dialog and its items on the main thread self.create_user_select_dialog(callback=callback) else: Logger.critical("StellaPayUI: Error: addresses could not be fetched from server") os._exit(1) @mainthread def create_user_select_dialog(self, callback: Optional[Callable] = None): # Load usernames into user select dialog if len(self.users_to_select) < 1: for user_name, user_email in App.get_running_app().user_mapping.items(): # store all users in a list of items that we will open with a dialog self.users_to_select.append( SelectUserItem(user_email=user_email, callback=self.selected_active_user, text=user_name)) # Add a callback so we know when a user has been selected # Create user dialog so we open it later. self.user_select_dialog = MDDialog( type="confirmation", items=self.users_to_select ) # If we have a callback, call it. if callback is not None: callback() # An active user is selected via the dialog def selected_active_user(self, item): # Close the user dialog self.user_select_dialog.dismiss() # Set member variables, these are required for making a purchase later user_name = item.text self.manager.transition = SlideTransition(direction='left') App.get_running_app().active_user = user_name # Go to the next screen self.manager.current = Screens.PRODUCT_SCREEN.value def on_leave(self, *args): # Hide the spinner self.ids.spinner.active = False # Dismiss the dialog if it was open if self.user_select_dialog: self.user_select_dialog.dismiss() def nfc_card_presented(self, uid: str): Logger.debug("StellaPayUI: Read NFC card with uid" + uid) # If we are currently making a transaction, ignore the card reading. if App.get_running_app().active_user is not None: Logger.debug("StellaPayUI: Ignoring NFC card as we are currently making a transaction.") return # Show the spinner self.ids.spinner.active = True # Request user info for the specific UID to validate person response = App.get_running_app().session_manager.do_get_request(url=Connections.request_user_info() + uid) # Check response code to validate whether this user existed already. If so, proceed # to the productScreen, else proceed to the registerUID screen if response and response.ok: # store result in JSON query_json = response.json() # Move to WelcomeScreen self.manager.transition = SlideTransition(direction='left') # store user-mail for payment confirmation later user_mail = query_json["owner"]["email"] user_name = query_json["owner"]["name"] App.get_running_app().active_user = user_name # Go to the product screen self.manager.current = Screens.PRODUCT_SCREEN.value else: # User was not found, proceed to registerUID file self.manager.get_screen(Screens.REGISTER_UID_SCREEN.value).nfc_id = uid self.manager.current = Screens.REGISTER_UID_SCREEN.value def on_select_guest(self): self.select_special_user("Gast Account") def on_select_beheer(self): self.select_special_user("Beheer Algemeen") def on_select_onderhoud(self): self.select_special_user("Beheer Onderhoud") def select_special_user(self, user: str): # Close the user dialog self.user_select_dialog.dismiss() self.manager.transition = SlideTransition(direction='left') App.get_running_app().active_user = user # Go to the next screen self.manager.current = Screens.PRODUCT_SCREEN.value
class AuthenticationDeviceStoreScreen(Screen): filesystem_key_storage_pool = ObjectProperty(None) def __init__(self, *args, **kwargs): self.selected_authentication_device_uids = [] self.register_event_type('on_selected_authentication_devices_changed') super().__init__(*args, **kwargs) def on_selected_authentication_devices_changed(self, *args): pass print("I am dispatched on_selected_authentication_devices_changed", args) def import_keys(self): """ loop through the “authentication_devices” present, and for those who are initialize, copy (with different KeyStorage for each folder) their content in a <KEYS_ROOT> / <device_uid> / folder (taking the device_uid from metadata.json) """ # list_devices = list_available_authentication_devices() # print(list_devices) # for index, authentication_device in enumerate(list_devices): #print(">>>>>>>>>> import_keys started") authentication_devices = list_available_authentication_devices() print("DETECTED AUTH DEVICES", authentication_devices) if not authentication_devices: msg = "No connected authentication devices found" else: authentication_devices_initialized = [ x for x in authentication_devices if x["is_initialized"] ] if not authentication_devices_initialized: msg = "No initialized authentication devices found" else: for authentication_device in authentication_devices_initialized: #print(">>>>>>>>>> importing,", authentication_device) key_storage_folder_path = _get_key_storage_folder_path( authentication_device) # FIXME make it public? try: self.filesystem_key_storage_pool.import_key_storage_from_folder( key_storage_folder_path) except KeyStorageAlreadyExists: pass # We tried anyway, since some "update" mevhanics might be setup one day msg = "%d authentication device(s) updated" % len( authentication_devices_initialized) display_info_toast(msg) # update the display of authentication_device saved in the local folder .keys_storage_ward self.list_imported_key_devices() def delete_keys(self): device_uids = self.selected_authentication_device_uids if not device_uids: msg = "Please select authentication devices to delete" else: # TODO move this to WACRYPTOLIB! for device_uid in device_uids: path = self.filesystem_key_storage_pool._get_imported_key_storage_path( device_uid) try: shutil.rmtree(path) except OSError as exc: logging.error( "Failed deletion of imported authentication device %s: %r", device_uid, exc) msg = "Selected imported authentication devices were deleted" display_info_toast(msg) self.list_imported_key_devices() def list_imported_key_devices(self): """ loop through the KEYS_ROOT / files, and read their metadata.json, to display in the interface their USER and the start of their UUID KEYS_ROOT = “~/.keys_storage_ward/” """ print(">> we refresh auth devices panel") Keys_page_ids = self.ids # FIXME rename this Keys_page_ids.device_table.clear_widgets() # FIXME naming key_storage_metadata = self.filesystem_key_storage_pool.list_imported_key_storage_metadata( ) if not key_storage_metadata: self.display_message_no_device_found() return self.chbx_lbls = {} # FIXME: lbls ? self.btn_lbls = {} # FIXME: lbls ? for (index, (device_uid, metadata)) in enumerate(sorted(key_storage_metadata.items()), start=1): uuid_suffix = str(device_uid).split("-")[-1] #print("COMPARING", str(device_uid), self.selected_authentication_device_uids) my_check_box = CheckBox( active=(str(device_uid) in self.selected_authentication_device_uids), size_hint=(0.15, None), on_release=self.check_box_authentication_device_checked, height=40, ) my_check_btn = Button( text="Key n°%s, User %s, Uid %s" % (index, metadata["user"], uuid_suffix), size_hint=(0.85, None), background_color=(0, 1, 1, 0.1), on_release=functools.partial(self.info_keys_stored, device_uid=device_uid, user=metadata["user"]), height=40, ) self.chbx_lbls[my_check_box] = str(device_uid) self.btn_lbls[my_check_btn] = str(device_uid) # device_row = BoxLayout( # orientation="horizontal", #pos_hint={"center": 1, "top": 1}, #padding=[20, 0], #) Keys_page_ids.device_table.add_widget(my_check_box) Keys_page_ids.device_table.add_widget(my_check_btn) #Keys_page_ids.device_table.add_widget(device_row) """ file_metadata = Path(dir_key_sorage).joinpath(".metadata.json") if file_metadata.exists(): metadata = load_from_json_file(file_metadata) device_uid = str(metadata["device_uid"]) uuid = device_uid.split("-") start_of_uuid = uuid[0].lstrip() start_of_UUID = start_of_uuid.rstrip() my_check_box = CheckBox(#start active=False, size_hint=(0.2, 0.2), on_release=self.check_box_authentication_device_checked, ) my_check_btn = Button( text=" key N°: %s User: %s | UUID device: %s " % ((str(index + 1)), str(metadata["user"]), start_of_UUID), size_hint=(0.8, 0.2), background_color=(1, 1, 1, 0.01), on_press=self.info_keys_stored, ) self.chbx_lbls[my_check_box] = str(metadata["device_uid"]) self.btn_lbls[my_check_btn] = str(metadata["device_uid"]) layout = BoxLayout( orientation="horizontal", pos_hint={"center": 1, "top": 1}, padding=[140, 0] ) layout.add_widget(my_check_box) layout.add_widget(my_check_btn) Keys_page_ids.table.add_widget(layout) index += 1 else: self.display_message_no_device_found() """ def display_message_no_device_found(self): keys_page_ids = self.ids devices_display = Button( text="No imported autentication device found ", background_color=(1, 0, 0, 0.01), font_size="20sp", color=[0, 1, 0, 1], ) keys_page_ids.device_table.clear_widgets() Display_layout = BoxLayout(orientation="horizontal", padding=[140, 0]) Display_layout.add_widget(devices_display) keys_page_ids.device_table.add_widget(Display_layout) def check_box_authentication_device_checked(self, check_box_checked): """ Display the device checked """ if self.chbx_lbls[ check_box_checked] in self.selected_authentication_device_uids: self.selected_authentication_device_uids.remove( self.chbx_lbls[check_box_checked]) else: self.selected_authentication_device_uids.append( self.chbx_lbls[check_box_checked]) self.dispatch('on_selected_authentication_devices_changed', self.selected_authentication_device_uids) print("self.selected_authentication_device_uids", self.selected_authentication_device_uids) def info_keys_stored(self, btn_selected, device_uid, user): """ display the information of the keys stored in the selected usb """ imported_key_storage = self.filesystem_key_storage_pool.get_imported_key_storage( key_storage_uid=device_uid) keypair_identifiers = imported_key_storage.list_keypair_identifiers() message = "" for index, keypair_identifier in enumerate(keypair_identifiers, start=1): private_key_present_str = "Yes" if keypair_identifier[ "private_key_present"] else "No" uuid_suffix = str( keypair_identifier["keychain_uid"]).split("-")[-1] message += ( " Key n° %s, Uid: ...%s, type: %s\n" #, has_private_key: %s\n" % ( index, uuid_suffix, keypair_identifier["key_type"], #private_key_present_str, )) self.open_dialog_display_keys_in_authentication_device(message, user=user) def open_dialog_display_keys_in_authentication_device(self, message, user): self.dialog = MDDialog( title="Imported authentication device of user %s" % user, text=message, size_hint=(0.8, 1), buttons=[MDFlatButton(text="Close", on_release=self.close_dialog)], ) self.dialog.open() def close_dialog(self, *args, **kwargs): self.dialog.dismiss()
class MainApp(MDApp): #Assign the data for the quick actions button data = { 'folder-plus': 'New Folder', 'rename-box': 'Rename', 'content-cut': 'Cut', 'content-copy': 'Copy', 'delete': 'Delete' } #The main app building process def build(self): Builder.load_file("file_explorer.kv") #Add the login screen and main screen to the screen manager sm.add_widget(LoginScreen(name='login_screen')) sm.add_widget(MainScreen(name='main_screen')) return sm # return our screen Manager #This function is called when you want to create a new folder def show_new_folder(self): self.folder_name = MDTextField( hint_text = "Enter A valid Folder name", required = True) self.dialog = MDDialog( title="New Folder", type="custom", content_cls=self.folder_name, radius = (30,30,30,30), buttons=[ MDFlatButton( text="Create",on_press=lambda a:MainApp.create_folder(self), ), ], ) self.dialog.open() return self.folder_name #Actually creates the new folder def create_folder(self): self.dialog.dismiss() MainScreenvar =sm.get_screen('main_screen') try: os.mkdir(os.path.join(MainScreenvar.ids.filechooser_icon.path, self.folder_name.text)) MainScreenvar.ids.filechooser_icon._update_files() except: Errors.folder_cannot_be_created(self) def show_rename_element(self): MainScreenvar = sm.get_screen('main_screen') self.element_name = MDTextField( hint_text = "Enter A valid new name", required = True) self.dialog = MDDialog( title="Rename", type="custom", content_cls=self.element_name, radius = (30,30,30,30), buttons=[ MDFlatButton( text="Rename",on_press=lambda a:MainApp.rename_element(self), ), ], ) if len(MainScreenvar.ids.filechooser_icon.selection) == 1: self.dialog.open() return self.element_name else: Errors.select_to_rename(self) #This function is called whenever an element needs to be renamed def rename_element(self): try: MainScreenvar = sm.get_screen('main_screen') self.dialog.dismiss() self.from_location = MainScreenvar.ids.filechooser_icon.selection[0] self.to_location = os.path.join(os.path.split(self.from_location)[0], self.element_name.text) self.to_location_with_ext = self.to_location + os.path.splitext(self.from_location)[1] os.rename(self.from_location, self.to_location_with_ext) MainScreenvar.ids.filechooser_icon._update_files() except: Errors().element_cannot_be_renamed(self)
class Alerte_Anti_Arnaqueurs(MDApp): print(SERVER) client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(ADDR) def build(self): #Build root widget, that is the core application or interface self.theme_cls.primary_palette = 'Green' screen = Screen() #Create a screen variable and add elements to the Screen to display them btn_num = MDRectangleFlatButton(text='Enter', pos_hint={'center_x': 0.5, 'center_y': 0.65}, on_release=self.get_data_num) screen.add_widget(btn_num) btn_sms = MDRectangleFlatButton(text='Enter', pos_hint={'center_x': 0.5, 'center_y': 0.45}, on_release=self.get_data_sms) screen.add_widget(btn_sms) icon_record = MDFloatingActionButton(icon='microphone', pos_hint={'center_x': 0.5, 'center_y': 0.25}, size_hint_x=None, on_press=self.get_voice) screen.add_widget(icon_record) self.num = Builder.load_string(num_helper) screen.add_widget(self.num) self.sms = Builder.load_string(sms_helper) screen.add_widget(self.sms) return screen #functions that activate on button release/ on button press def get_data_num(self, obj): if self.num.text == "": self.response = "Please enter a number" else: self.send(obj=(self.num.text + '1')) print(self.response, self.response[-4:]) if self.response[-4:]=="#123": self.response = self.response[:-4] close1_btn = MDFlatButton(text='Close', on_release=self.close_dialog) add_btn = MDRaisedButton(text='Mark as spam', on_release=self.add) self.dialog = MDDialog(title='Verification', text=self.response + '\n' + 'Do you want to mark this number as spam?', size_hint=(0.7, 1), buttons=[close1_btn, add_btn]) else: close1_btn = MDFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog(title='Verification', text=self.response, size_hint=(0.7, 1), buttons=[close1_btn]) self.dialog.open() def add(self, obj): self.send(obj=(self.num.text + 'A')) self.dialog.dismiss() def get_data_sms(self, obj): if self.sms.text == "": check_string = "Please enter the message" close_btn = MDFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog(title='Verification', text=check_string, size_hint=(0.7, 1), buttons=[close_btn]) else: self.send(obj=(self.sms.text + '2')) self.verdict = self.client.recv(HEADER).decode(FORMAT) self.list = self.response.split('-') self.showit = str(self.list[0]) + '\n' + str(self.list[1]) print(self.response, 'next', self.verdict) close_btn = MDFlatButton(text='Close', on_release=self.close_dialog) yes_btn = MDRaisedButton(text='Yes', on_release=self.yes) no_btn = MDRaisedButton(text='No', on_release=self.no) self.dialog = MDDialog(title='Verification', text=self.showit+'\n'+ 'Was the message correctly interpreted?', size_hint=(0.7, 1), buttons=[close_btn,yes_btn,no_btn]) self.dialog.open() def yes(self, obj): self.send(obj=(self.verdict + 'a')) self.send(obj=(self.sms.text)) self.dialog.dismiss() def no(self, obj): self.send(obj=(self.verdict + 'u')) self.send(obj=(self.sms.text)) self.dialog.dismiss() def get_voice(self, obj): close1_btn = MDFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog(title='Error', text='Function currently not available.', size_hint=(0.7, 1), buttons=[close1_btn]) self.dialog.open() def send(self, obj): message = obj.encode(FORMAT) msg_length = len(message) send_length = str(msg_length).encode(FORMAT) send_length += b' ' * (HEADER - (len(send_length))) self.client.send(send_length) self.client.send(message) self.response = self.client.recv(HEADER).decode(FORMAT) return self.response def close_dialog(self, obj): self.dialog.dismiss()
class Order(MDScreen): def __init__(self, **kw): super().__init__(**kw) self.add_request_dialog = None self.content = None # Data self.first_name = None self.place = None self.hour = None self.contact = int self.service = None def on_pre_enter(self, *args): self.add_request_button.bind(on_release=self.show_add_request_dialog) def show_add_request_dialog(self, instance_button): if not self.add_request_dialog: self.add_request_dialog = MDDialog( size_hint=(.8, .7), type="custom", content_cls=AddRequestDialog(hour_picker=self.show_time_picker, date_picker=self.show_date_picker), buttons=[ MDFlatButton( text="CANCELAR", text_color=APP.theme_cls.primary_color, on_release=self.close_dialog ), MDFlatButton( text="MARCAR", text_color=APP.theme_cls.primary_color, on_release=self.add_request ), ], ) self.content = self.add_request_dialog.ids.spacer_top_box.children[0] self.add_request_dialog.open() def show_date_picker(self): date_dialog = MDDatePicker(callback=self.get_date) date_dialog.open() def get_date(self, date): self.content.ids.date_label.color = APP.theme_cls.primary_color self.content.ids.date_label.text = date.strftime("%d/%m/%Y") def show_time_picker(self): """Open time picker dialog.""" time_dialog = MDTimePicker() time_dialog.bind(time=self.get_time) time_dialog.open() def get_time(self, instance, time): self.content.ids.hour_label.color = APP.theme_cls.primary_color self.content.ids.hour_label.text = time.strftime("%H:%M") def add_request(self, button): self.first_name = self.content.ids.first_name.text self.place = self.content.ids.place.text self.service = self.content.ids.service.text self.date = self.content.ids.date_label.text self.hour = self.content.ids.hour_label.text self.contact = self.content.ids.contact.text if (self.first_name and self.place and self.contact != "" and self.date != "Data" and self.hour != "Hora" and self.service != ""): DATABASE.add_order( self.first_name, self.place, self.date, self.hour, self.contact, self.service, ) self.close_dialog("") else: print("Deves completar todos os dados") def close_dialog(self, button): self.add_request_dialog.dismiss() self.add_request_dialog = None
class SmartBricksApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) Window.bind(on_keyboard=self.events) self.manager_open = False self.file_manager = MDFileManager(exit_manager=self.exit_manager, select_path=self.select_path, previous=True, ext=['jpeg', 'png', 'jpg']) #self.menu_2 = self.create_menu("Button dots", self.root.ids.toolbar.ids.button_2) #print('HEREEEEEEE!!!!', self.root) #cm = CustomToolbar try: request_permissions([ Permission.WRITE_EXTERNAL_STORAGE, Permission.READ_EXTERNAL_STORAGE ]) except NameError: pass def dropdown(self, id): self.menu_2 = self.create_menu("Button dots", id) self.menu_2.open() def create_menu(self, instance): menu_items = [ { "right_content_cls": RightContentCls( #text=f"R", icon="apple-keyboard-command", ), "icon": "apple-keyboard-command", "text": text, } for text in ('RENAME', 'DELETE') ] return MDDropdownMenu(caller=instance, items=menu_items, width_mult=4) def build(self): #Window.bind(on_keyboard=self.key_input) self.screen = Builder.load_file("main.kv") return self.screen def on_pause(self): return True #def key_input(self, window, key, scancode, codepoint, modifier): # if key == 27: # return True # override the default behaviour # else: # the key now does nothing # return False #settings_path = app_storage_path() path = os.getcwd() df = pd.read_csv('%s/legoKeys.cvs' % (path), sep='\t') try: SD_CARD = primary_external_storage_path() + '/' + 'DCIM/Camera' out_dir = '%s/smartbricks_outputs/' % (primary_external_storage_path()) print('ANDROID mmodules loaded...') except NameError: print('ANDROID modules failed...') SD_CARD = '/home/omar/Pictures' out_dir = '%s/myproj_out/' % (path) pass isdir = os.path.isdir(out_dir) def plist(self): if self.isdir: plist_ = os.listdir(self.out_dir) else: os.mkdir(self.out_dir) plist_ = None return plist_ custom_sheet = None def callback_for_menu_items(self, *args): toast(args[0]) def openScreen(self, itemdrawer): self.openScreenName(itemdrawer.target) self.root.ids.nav_drawer.set_state("close") def openScreenName(self, screenName): self.root.ids.screen_manager.current = screenName def ifproject(self): print('PLIST!!!!!!!!!', self.plist()) print('PLIST TYPE!!!!!!!!!', type(self.plist())) if ((self.isdir) & (self.plist() is not None)): #clear widgets if any previously load to avoid staking of color palettes between projects self.root.ids.grid_list.clear_widgets() #self.root.ids.grid_list.remove_widget(self.root.ids.grid_list) self.openScreenName('projects') #if ((self.isdir) & (self.plist is not None)): for dir_ in self.plist(): self.root.ids.grid_list.add_widget( CustomSmartTileWithLabel( source=self.out_dir + dir_ + '/all.jpeg', text="[size=32]%s[/size]" % (dir_))) else: self.callback_for_menu_items( 'No projects saved yet. Select START to start a new project.') def chooseproject(self, img_source): #clear widgets if any previously load to avoid staking of color palettes between projects self.root.ids.content_drawer.ids.md_list.clear_widgets() self.root.ids.image.source = img_source self.openScreenName('main') self.img_path = os.path.dirname(img_source) tab = np.load(self.img_path + '/table.npz') self.tab = tab['data'] row_data = [] n2x2, n2x1, n1x1 = 0, 0, 0 for num, i in enumerate(self.tab.T[0][:-1]): if i == '0.0_0.0_0.0': continue R, G, B = i.split("_") R, G, B = [np.int(np.float(j)) for j in [R, G, B]] mask = (self.df['R'] == R) & (self.df['G'] == G) & (self.df['B'] == B) Nbrick, color_name = self.df['LEGO No.'][mask].item( ), self.df['Color'][mask].item() #print(R,G,B, Nbrick, color_name) # self.root.ids.content_drawer.ids.md_list.add_widget( CustomMDIconButton(color=(R / 256, G / 256, B / 256, 1), text=color_name, text_color=(1, 0, 0, 1), icon='checkbox-blank-circle-outline')) n2x2 += int(self.tab.T[1][num]) n2x1 += int(self.tab.T[2][num]) n1x1 += int(self.tab.T[3][num]) row_data.append( (color_name, self.tab.T[1][num], self.tab.T[2][num], self.tab.T[3][num], int(self.tab.T[1][num]) + int(self.tab.T[2][num]) + int(self.tab.T[3][num]))) row_data.append(('Total', n2x2, n2x1, n1x1, n2x2 + n2x1 + n1x1)) #if len(row_data) > 10: pagination = True #else: pagination = False self.data_tables = MDDataTable( size_hint=(0.9, 0.6), rows_num=20, use_pagination=True if len(row_data) > 20 else False, check=False, column_data=[("Color", dp(40)), ("2x2", dp(10)), ("2x1", dp(10)), ("1x1", dp(10)), ("All", dp(10))], row_data=row_data, ) self.root.ids.content_drawer.ids.md_list.add_widget( CustomMDIconButton( color=self.theme_cls.primary_color, text='All', icon='checkbox-blank-circle-outline', #text_color=(R/256,G/256,B/256,1), #icon='checkbox-marked-circle' )) self.root.ids.content_drawer.ids.md_list.add_widget( CustomMDIconButton(color=self.theme_cls.primary_color, text='Original', icon='')) keep = self.tab.T[0] == 'total' b2x2 = self.root.ids.brick_2x2 b2x1 = self.root.ids.brick_2x1 b1x1 = self.root.ids.brick_1x1 for num, brick, brickLab in zip([1, 2, 3], [b2x2, b2x1, b1x1], ['2x2', '2x1', '1x1']): brick.text = brickLab + ': ' + self.tab.T[num][keep][0] def choose_palette(self, img_bg_color, text, id): self.root.ids.palette_toolbar.md_bg_color = img_bg_color self.img_path = os.path.dirname(self.root.ids.image.source) #R,G,B = np.float(img_bg_color[0]*256), np.float(img_bg_color[1]*256), np.float(img_bg_color[2]*256) R, G, B = np.int(img_bg_color[0] * 256), np.int( img_bg_color[1] * 256), np.int(img_bg_color[2] * 256) mean = np.mean([R, G, B]) #print(R,G,B) #self.root.ids.image.parent.remove_widget(self.root.ids.image) if text not in ['All', 'Original']: self.root.ids.image.clear_widgets() self.root.ids.image.source = self.img_path + '/%s_%s_%s.zip' % ( str(R), str(G), str(B)) else: self.root.ids.image.source = self.img_path + '/%s.jpeg' % ( text.lower()) print('SOURCE!!!!!!!', self.root.ids.image.source) print('TEXT!!!!!!!', text) id.icon = 'checkbox-marked-circle' #Get bricks counts tab = np.load(self.img_path + '/table.npz') self.tab = tab['data'] if text not in ['All', 'Original']: keep = self.tab.T[0] == '%s_%s_%s' % (str(R), str(G), str(B)) else: keep = self.tab.T[0] == 'total' b2x2 = self.root.ids.brick_2x2 b2x1 = self.root.ids.brick_2x1 b1x1 = self.root.ids.brick_1x1 if mean > 180: test_color = [0, 0, 0, 1] #black invert = False else: test_color = [1, 1, 1, 1] #withe invert = True id.text_color = test_color for num, brick, brickLab in zip([1, 2, 3], [b2x2, b2x1, b1x1], ['2x2', '2x1', '1x1']): brick.text = brickLab + ': ' + self.tab.T[num][keep][0] brick.text_color = test_color #print(brick.text_color) b2x2_i = self.root.ids.brick_2x2_icon b2x1_i = self.root.ids.brick_2x1_icon b1x1_i = self.root.ids.brick_1x1_icon for num, brick, brickLab in zip([1, 2, 3], [b2x2_i, b2x1_i, b1x1_i], ['2x2', '2x1', '1x1']): #print('MAIN PATH:', self.path) if invert: brick.icon = "%s/images/%s_invert.jpg" % (self.path, brickLab) else: brick.icon = "%s/images/%s.jpg" % (self.path, brickLab) #self.root.ids.brick_2x2.text = '2x2: '+self.tab.T[1][keep][0] #self.root.ids.brick_2x1.text = '2x1: '+self.tab.T[2][keep][0] #self.root.ids.brick_1x1.text = '1x1: '+self.tab.T[3][keep][0] #print(mean, test_color, self.root.ids.brick_2x2.text_color) #self.root.ids.brick_2x2.text_color=test_color #if invert: self.root.ids.brick_2x2_icon.icon="/home/omar/myproj/SmartBricks/2x2_invert.jpg" #else: self.root.ids.brick_2x2_icon.icon="/home/omar/myproj/SmartBricks/2x2.jpg" #print(self.root.ids.brick_2x2.text_color) #def test(self, R, G, B): # return R,G,B,1 def callback_mosaic_size(self, instance, value): toast('mosaic size: %s' % (value)) self.mosaic_size_val = value def callback_mosaic_color(self, instance, value): toast('mosaic colors: %s' % (value)) self.mosaic_color_val = value def callback_mosaic_name(self, instance, value): toast('mosaic name: %s' % (value)) self.mosaic_name = value def show_alert_dialog(self, name): if not self.dialog: self.dialog = MDDialog( title="Replace existing project?", text= "Project '%s' already exists. Do you want to replace existing project?" % (name), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()), MDFlatButton( text="ACCEPT", text_color=self.theme_cls.primary_color, on_press=lambda x: self.show_dialog_progress()), ], ) else: self.dialog.dismiss() self.dialog.open() def create_mosaic(self): print('LOWSIZE --------', type(self.mosaic_size_val)) print('NCOLORS --------', type(self.mosaic_color_val)) print('OUTDIR --------', type(self.root.ids.project_name.text)) if (self.mosaic_size_val is None) or (self.mosaic_color_val is None) or (self.root.ids.project_name.text == ''): ttext = 'Define mosaic input values' if (self.mosaic_size_val is None): ttext += ', lower size' if (self.mosaic_color_val is None): ttext += ', colors' if (self.root.ids.project_name.text == ''): ttext += ', project name' print('TEXT ------ ', ttext) toast(ttext) #elif #elif (if not self.root.ids.project_name.text): # toast('Choose a project name first') else: #print(self.root.ids.setup_image.source) #print(int(self.mosaic_size_val)) #print(int(self.mosaic_color_val)) #print(self.root.ids.project_name.text) #print(self.out_dir+self.root.ids.project_name.text) self.imgpath = str(self.root.ids.setup_image.source) self.Ncolors = np.int(self.mosaic_color_val) self.lowsize = np.int(self.mosaic_size_val) self.outdir = str(self.out_dir + self.root.ids.project_name.text) for i in [self.imgpath, self.Ncolors, self.lowsize, self.outdir]: print(i, type(i)) if (self.plist() is not None): if (self.root.ids.project_name.text in self.plist()): print('project name already exist...') self.show_alert_dialog( name=self.root.ids.project_name.text) else: self.show_dialog_progress() else: self.show_dialog_progress() def show_dialog_progress(self): #if not self.dialog2: self.dialog2 = MDDialog( title="Creating mosaic. Please wait.", type="custom", #text="Creating mosaic. Please wait.", content_cls=progress_bar(), #self.pb, on_open=self.run_mosaic #on_open=self.puopen) #on_open=self.run_mosaic(imgpath=imgpath, Ncolors=Ncolors, lowsize=lowsize, outdir=outdir) ) self.dialog2.open() if self.dialog: self.dialog.dismiss() #self.dialog2.bind(on_open=self.run_mosaic) #self.run_mosaic #def run_mosaic(self, imgpath=None, Ncolors=None, lowsize=None, outdir=None): def run_mosaic(self, instance): #clear widgets if any previously load to avoid staking of color palettes between projects #self.pb.load_bar.clear_widgets() self.pb = progress_bar() #self.pb.load_bar.parent.remove_widget(self.pb.load_bar) self.pb.load_bar.value = 0 #print(self.pb.load_bar.value) #Nmax = np.int(self.mosaic_color_val) #+ 3 start = time.time() SB = SmartBricks(imgpath=self.imgpath, Ncolors=self.Ncolors, lowsize=self.lowsize, outdir=self.outdir) #print(SB.img) #print(SB.res1x1) #SB.saveProj() end = time.time() print('Total run time #1: %f sec' % (end - start)) print('point size', SB.size) import matplotlib.pyplot as plt ispathdir = os.path.isdir(self.outdir) if not ispathdir: os.makedirs(self.outdir, exist_ok=True) else: files = os.listdir(self.outdir) #print(self.outdir) for f in files: os.remove(self.outdir + '/' + f) start = time.time() #lmax = 10 if SB.w > SB.h: x_size, y_size = SB.lmax, SB.h * SB.lmax / SB.w else: x_size, y_size = SB.w * SB.lmax / SB.h, SB.lmax fig = plt.figure(figsize=(x_size, y_size)) #fig = plt.figure(figsize=(12,12)) ax = plt.gca() SB.bricksCanvas(img=SB.img, fig=fig, ax=ax, RGB=None, res2x2=SB.res2x2, res2x1=SB.res2x1, res1x1=SB.res1x1) figcvs = fig figall = fig #figoriginal = fig.copy #paletteLego = SB.palette(SB.img) #palette_flat = SB.imgFlat(paletteLego) Nmax = len(SB.palette_flat) self.pb.load_bar.max = Nmax table = [] #for num, pal in enumerate(palette_flat): for i in range(Nmax): print(self.pb.load_bar.value) pal = SB.palette_flat[i] N2x2, N2x1, N1x1 = SB.makeGiff( img=SB.img, RGB=pal, idxs=[SB.res2x2[2], SB.res2x1[2], SB.res1x1[2]], pathdir=self.outdir, fig=figcvs, ax=ax) r, g, b = pal color = '%s_%s_%s' % (r, g, b) table.append([color, N2x2, N2x1, N1x1]) self.pb.load_bar.value = i + 1 #self.value99 = i+1 t = np.array(table) N2x2total = np.sum(t[:, 1].astype(int)) N2x1total = np.sum(t[:, 2].astype(int)) N1x1total = np.sum(t[:, 3].astype(int)) table.append(['total', N2x2total, N2x1total, N1x1total]) end = time.time() print('Total run time #2: %f sec' % (end - start)) start = time.time() figall.subplots_adjust(left=SB.left, bottom=SB.bottom, right=SB.right, top=SB.top, wspace=None, hspace=None) ax = figall.add_subplot(111) ax.imshow(SB.img) #True if testing App from PC. if SB.frompc: figall.savefig('%s/all.jpeg' % (self.outdir), bbox_inches='tight', pad_inches=0) else: buffer = io.BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) pil_image.save('%s/all.jpeg' % (self.outdir), 'JPEG') fig0 = plt.figure(figsize=(x_size, y_size)) fig0.subplots_adjust(left=SB.left, bottom=SB.bottom, right=SB.right, top=SB.top, wspace=None, hspace=None) ax = plt.gca() ax = fig0.add_subplot(111) ax.imshow(SB.img_original) if SB.frompc: fig0.savefig('%s/original.jpeg' % (self.outdir), bbox_inches='tight', pad_inches=0) else: buffer = io.BytesIO() canvas = plt.get_current_fig_manager().canvas canvas.draw() pil_image = PIL.Image.frombytes('RGB', canvas.get_width_height(), canvas.tostring_rgb()) pil_image.save('%s/original.jpeg' % (self.outdir), 'JPEG') #ax = figall.add_subplot(111) #ax.imshow(SB.img) #figall.savefig('%s/all.jpeg' %(self.outdir), bbox_inches = 'tight', pad_inches = 0) #fig0 = plt.figure(figsize=(12,12)) #ax = fig0.add_subplot(111) #plt.imshow(SB.img_original) #fig0.savefig('%s/original.jpeg' %(self.outdir), bbox_inches = 'tight', pad_inches = 0) np.savez_compressed('%s/table' % (self.outdir), data=table) end = time.time() print('Total run time #3: %f sec' % (end - start)) if Nmax == self.pb.load_bar.value: self.dialog2.dismiss() #SmartBricks(imgpath=self.imgpath, Ncolors=self.Ncolors, lowsize=self.lowsize, outdir=self.outdir).saveProj(self.pb.load_bar.value) self.chooseproject(self.outdir + '/all.jpeg') def next(self, dt): #if self.times == 0: #self.run_mosaic # SmartBricks(imgpath=self.imgpath, Ncolors=self.Ncolors, lowsize=self.lowsize, outdir=self.outdir).saveProj() # self.times = 1 if os.path.exists(self.outdir): #self.value99 += 1 print(self.pb.load_bar.value) Nmax = np.int(self.mosaic_color_val) + 3 self.pb.load_bar.max = Nmax Ncurrent = len( os.listdir(str(self.out_dir + self.root.ids.project_name.text))) print(self.pb.load_bar.value, self.pb.load_bar.max, Ncurrent) #print(self.pb.load_bar.value, self.pb.load_bar.max) if self.pb.load_bar.value >= Nmax: return False else: self.pb.load_bar.value = Ncurrent #self.pb.load_bar.value = self.value99 else: print('PATH DOES NOT EXIST YET!') #print(self.times) def puopen(self, instance): #self.times = 0 Clock.schedule_interval(self.next, 1 / 25) #self.run_mosaic def on_start(self): self.imgpath = None self.Ncolors = None self.lowsize = None self.outdir = None self.mosaic_size_val = None self.mosaic_color_val = None self.mosaic_name = None self.dialog = None self.dialog2 = None self.value99 = 0 #self.pb = progress_bar() self.menu_2 = self.create_menu(self.root.ids.toolbar) self.root.ids.avatar.source = '%s/images/logo.zip' % (self.path) self.root.ids.brick_2x2_icon.icon = "%s/images/%s.jpg" % (self.path, '2x2') self.root.ids.brick_2x1_icon.icon = "%s/images/%s.jpg" % (self.path, '2x1') self.root.ids.brick_1x1_icon.icon = "%s/images/%s.jpg" % (self.path, '1x1') for i in np.arange(8, 72, 8): self.root.ids.mosaic_size.add_widget( CustomMDChip(label='%s' % (str(i)), cb=self.callback_mosaic_size, icon='grid')) for i in np.arange(2, 18, 2): self.root.ids.mosaic_colors.add_widget( CustomMDChip(label=str(i), cb=self.callback_mosaic_color, icon='palette')) #print(self.custbutt.palette.md_bg_color) #self.root.ids.content_drawer.ids.palette.md_bg_color = (i/100,i/10,0,1) #md_bg_color=(1,0,0,1) # # self.root.ids.content_drawer.ids.md_list.add_widget( # ItemDrawer(target="screen1", text="Screen 1", # icon="home-circle-outline", # on_release=self.openScreen) # ) # self.root.ids.content_drawer.ids.md_list.add_widget( # ItemDrawer(target="screen2", text="Screen 2", # icon="settings-outline", # on_release=self.openScreen) # ) def custom_bottom_sheet(self): self.custom_sheet = MDCustomBottomSheet( screen=Factory.ContentCustomSheet()) self.custom_sheet.open() def show_gallery(self): self.openScreenName('camera') types = ('*.png', '*.jpeg', '*.jpg') # the tuple of file types files_grabbed = [] for files in types: files_grabbed.extend(glob.glob(os.path.join(self.SD_CARD, files))) files_grabbed.sort(key=os.path.getmtime) files_grabbed.reverse() for file in files_grabbed[:20]: self.root.ids.grid_list_camera.add_widget( CustomSmartTileWithLabelGallery(source=file, text="[size=18]%s[/size]" % (os.path.basename(file)))) def file_manager_open(self): #self.file_manager.show('/home/omar/Pictures') # output manager to the screen #self.file_manager.show(self.settings_path) self.file_manager.show(self.SD_CARD) self.manager_open = True def select_path(self, path): '''It will be called when you click on the file name or the catalog selection button. :type path: str; :param path: path to the selected directory or file; ''' try: self.exit_manager() except: pass self.openScreenName('setup') self.root.ids.setup_image.source = path toast(path) def exit_manager(self, *args): '''Called when the user reaches the root of the directory tree.''' self.manager_open = False self.file_manager.close() def show_dialog_eddit(self): if self.dialog: self.dialog.dismiss() #if not self.dialog2: self.dialog = MDDialog( title="Eddit project?", text="Make a new project with same image.", buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()), MDFlatButton(text="ACCEPT", text_color=self.theme_cls.primary_color, on_press=lambda x: self.eddit_project()), ]) self.dialog.open() def eddit_project(self): #self.img_path = os.path.dirname(self.root.ids.image.source) img_path = self.img_path + '/original.jpeg' self.openScreenName('setup') if self.dialog: self.dialog.dismiss() self.root.ids.setup_image.source = img_path toast(img_path) def events(self, instance, keyboard, keycode, text, modifiers): '''Called when buttons are pressed on the mobile device.''' if keyboard in (1001, 27): if self.manager_open: self.file_manager.back() return True def goto_table(self): #self.openScreenName('mosaic_details') self.data_tables.open(self.root.ids.details) def back_main(self): self.data_tables.dismiss() self.openScreenName('main') def show_dialog_buy(self): if self.dialog: self.dialog.dismiss() #if not self.dialog2: self.dialog = MDDialog( title="Cooming Soon", text= "Apologies, SmartBricks does not deliver yet. We are working to deliver your favourite mosaic to you. Are you interested in buying? ", buttons=[ MDFlatButton(text="NO", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()), MDFlatButton(text="YES", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()), ]) self.dialog.open() def show_dialog_empty(self): if self.dialog: self.dialog.dismiss() #if not self.dialog2: self.dialog = MDDialog( title="Cooming Soon", text="This option is not yet available.", buttons=[ MDFlatButton(text="Cancel", text_color=self.theme_cls.primary_color, on_press=lambda x: self.dialog.dismiss()) ]) self.dialog.open()
class Bookcrossing(MDApp): """Основной класс приложения.""" current_book_id = "" text_dialog = None dialog = None def show_book_dialog(self): """Открытие модальных окон книг.""" user = App.get_running_app().email book_id = App.get_running_app().current_book_id if book_id == "" or book_id is None: return None book = modalview(book_id) if book is None: return None if bookOnStation(book_id, type="book_id"): actionButton = MDRaisedButton( text="Взять книгу", on_release=lambda x: take_book(book_id, user)) else: actionButton = MDRaisedButton( text="Сдать книгу", on_release=lambda x: App.get_running_app( ).show_station_text_dialog()) self.dialog = MDDialog(title=book[4], type="custom", text=generateModalTextBook(book), buttons=[ actionButton, MDFlatButton(text="OK", on_press=self.close_dlg) ], size_hint=(0.7, 0.5)) self.dialog.open() def show_dialog(self, text, size=0.5): """Открытие модальных окон.""" self.dialog = MDDialog(title=text, buttons=[ MDFlatButton( text="OK", text_color=self.theme_cls.primary_color, on_release=self.close_dlg) ], size_hint_x=size) self.dialog.open() def show_station_text_dialog(self): """Открытие модальных окон станции.""" OKButton = MDRaisedButton( text="OK", on_release=lambda x: Clock.schedule_once( lambda x: give_book(book=App.get_running_app().current_book_id, station=self.text_dialog.content_cls. text_field.text), .1)) cancelButton = MDFlatButton(text="ОТМЕНА", on_release=self.close_station_text_dialog) self.text_dialog = MDDialog(title="Код станции:", type="custom", content_cls=TextDialogContent(), size_hint=(0.7, 0.4), buttons=[cancelButton, OKButton]) self.text_dialog.open() def close_dlg(self, instance): """Закрытие модальных окон.""" if self.dialog: self.dialog.dismiss() def close_station_text_dialog(self, instance): """Закрытие модальных окон.""" if self.text_dialog: self.text_dialog.dismiss() def build(self): """Создание App.""" self.m = Screens(transition=NoTransition()) return self.m def toApp(self, dt): """Домашний экран.""" self.m.current = "MyBooks"
class Window2(Screen): #Main List Window -- CHANGE NAME LATER #class variable definitions data = { 'emoticon-angry': "WILL, I'LL END YOUR BLOODLINE", 'database-plus': 'Add all checked to Pantry', 'delete': 'Delete all checked', 'plus': 'Add item to list', } bufferDate = None container = ObjectProperty() quantity = ObjectProperty() alreadyCheck = False alreadyCheckNav = False localList = [ "", #empty item because the positioning puts it under the nav bar "pizza", "Banana", "Lamb", "Chicky nuggies", "Gogurt", "Cheeze stick", "Cold pasta sauce", "Spam", "Paimon", "Shallot", "Carrot", "Way too many green onions", "Chili", "Paprika", "Flour", "Sugar", "Apples", "Sour patch kids" ] def on_enter(self): icons_item = { #This needs extra items at the bottom to fill out the nav bar "food-apple": "Food", "pasta": "Recipes", "database": "Pantry", "brush": "Theme", #completely unesccesary but would be cool to customize colors of the app #see MDThemePicker https://kivymd.readthedocs.io/en/latest/components/pickers/index.html "logout": "log out", "a":"", "b":"", "c":"", "d":"", } if self.alreadyCheckNav == False: for icon_name in icons_item.keys(): self.ids.content_drawer.add_widget( ItemDrawer(icon=icon_name, text=icons_item[icon_name])) self.alreadyCheckNav = True if self.alreadyCheck == False: for i in self.localList: #prints all the items in user local list self.ids.container.add_widget(SwipeItem(text=i)) self.alreadyCheck = True def remove_item(self, instance): self.ids.container.remove_widget(instance) def JSON_maker(self, food, date, quant): print( food ) #returns the food name, will need to change the variable name of this print("date in JSON maker: " + str(date)) if date != None: print(date) if date != None: exp_bool = True else: exp_bool = False JSON = { "Owner": App.user.username, "Name": food, "Expires": exp_bool, "Exp_date": date, "Quantity": quant, "Type": None } print(JSON) def got_date(self, the_date): self.bufferDate = the_date return (self.bufferDate) def show_date_picker(self): date_dialog = MDDatePicker(callback=self.got_date) date_dialog.open() def add_pantry_item(self, instance): self.bufferDate = None #reset bufferdate back to null when dialog box opens self.food_name = instance.text #this gets the title of the item clicked self.pantry_item_instance = instance #So looks like variables need to use self. to be able to use elsewhere close_button = MDRectangleFlatButton(text='Close', on_release=self.close_dialog) submit_button = MDRectangleFlatButton(text='Submit', on_release=self.submit_dialog) self.dialog = MDDialog( title="Add item to Pantry?", size_hint=(0.8, 1), type="custom", content_cls=dialog_content(), buttons=[submit_button, close_button], ) self.dialog.open() # open thingy that prompts for more info and then creates a food object which is then sent to the food handler def close_dialog(self, instance): self.dialog.dismiss() def submit_dialog(self, instance): #quant = self.dialog.content_cls.ids.quantity.text if App.sm.get_screen("window2").bufferDate: date = App.sm.get_screen("window2").bufferDate else: date = None if self.dialog.content_cls.ids.quantity.text: quant = self.dialog.content_cls.ids.quantity.text else: quant = 1 self.JSON_maker( self.food_name, date, quant) #send collected info to be made into JSON type beat #after submitting, remove the item and close the box self.remove_item( self.pantry_item_instance ) #removes the item from the list when button is pressed self.dialog.dismiss() def call_back(self, instance): self.show_data(self) def show_data(self, obj): close_button = MDRectangleFlatButton(text="Add", pos_hint={ "center_x": 0.5, "center_y": 0.4 }, on_press=self.close_dialog, on_release=self.print_something) self.alreadyCheck = False self.foodItem = MDTextField( hint_text="Enter an item", helper_text="e.g. apples, bananas, orange, etc.", helper_text_mode="on_focus", # icon_right_color = app.theme_cls.primary_color, pos_hint={ "center_x": 0.5, "center_y": 0.5 }, size_hint_x=None, width=500) self.dialog = MDDialog(title="Enter an item:", size_hint=(0.7, 1), buttons=[close_button]) self.dialog.add_widget(self.foodItem) self.dialog.open() def close_dialog(self, obj): self.dialog.dismiss() def print_something(self, obj): self.localList.append(self.foodItem.text) self.ids.container.add_widget(SwipeItem(text=self.foodItem.text))
class TripsAvailableScreen(MDScreen): def __init__(self, **kw): super().__init__(**kw) self.add_trip_dialog = None self.content = None self.hint_text_seats = "Asientos Disponibles" # Data self.city_from = None self.city_to = None self.hour = None self.n_passenger = int def on_pre_enter(self, *args): self.add_trip_button.bind(on_release=self.show_add_trip_dialog) # Charge Trips self.load_data() def load_data(self): trips_data = DATABASE.trips_available("trips_available") self.ids.trips_grid.clear_widgets() self.refresh_available_trips(trips_data) def refresh_available_trips(self, trips_data): try : for trip, data in trips_data.items(): self.ids.trips_grid.add_widget(TripsBanner( kind_dialog="Trip", city_from=data['city_from'], city_to=data['city_to'], name=data['driver'], plate=data['plate'], cel_number=data['cel_number'], date=data['date'], hour=data['hour'], seats=f"{data['seats_available']} Disponibles", trip_id=trip, hint_text_seats=self.hint_text_seats, reload_data=self.load_data )) except : temp = no_trips_message() self.ids.trips_grid.add_widget(temp) def refresh_callback(self, *args): '''A method that updates the state of your application while the spinner remains on the screen.''' def refresh_callback(interval): self.ids.refresh_layout.refresh_done() self.load_data() Clock.schedule_once(refresh_callback, 1.5) def show_add_trip_dialog(self, instance_button): """[summary] Function in charge of initializing a pop-up window in which we can enter a new trip available """ if not self.add_trip_dialog: self.add_trip_dialog = MDDialog( size_hint=(.8, .7), title="Añadir Viaje:", type="custom", content_cls=AddTripLayout(seats=self.hint_text_seats), buttons=[ MDFlatButton( text="CANCEL", text_color=APP.theme_cls.primary_color, on_release=self.close_dialog ), MDFlatButton( text="AÑADIR", text_color=APP.theme_cls.primary_color, on_release=self.add_trip ) ] ) self.content = self.add_trip_dialog.ids.spacer_top_box.children[0] self.add_trip_dialog.open() def add_trip(self, button): """[summary] Collect the data and run the method in myfirebase that creates a new trip in the cloud """ self.city_from = self.content.ids.city_from.text self.city_to = self.content.ids.city_to.text self.date = self.content.ids.date_label.text self.hour = self.content.ids.hour_label.text self.seats_available = self.content.ids.seats.text if (self.city_from and self.city_to and self.seats_available != "" and self.date != "Fecha" and self.hour != "Hora"): # If All fields are completed the add the Trip DATABASE.create_new_trip( APP.data['name'], APP.data['last_name'], self.city_from, self.city_to, self.date, self.hour, self.seats_available, APP.data['cel_number'], APP.data['driver']['plate'] ) self.close_dialog("") self.load_data() else: print("Debes Completar Todos Los Datos") def close_dialog(self, button): """[summary] close and delete the add trip dialog """ self.add_trip_dialog.dismiss() self.add_trip_dialog = None
class AddHabitButton(MDFloatingBottomButton): def show_task_template(self, title): self.dialog = None if not self.dialog: self.dialog = MDDialog( title=str(title) + ':', type="custom", content_cls=HabitTemplate(), buttons=[ MDFlatButton(text="CANCEL", text_color=self.theme_cls.primary_color, on_release=self.close_habit_template), MDFlatButton( text="SAVE", text_color=self.theme_cls.primary_color, on_release=(lambda *args: self.create_habit())), ], ) self.dialog.open() def close_habit_template(self, *args): self.dialog.dismiss() def create_habit(self, *args): # for easier referencing template = self.dialog.content_cls.ids # geting values for new Habit (inserted in HabitTemplate) description = template.habit_description.text reminder_days = ', '.join([ day.text for day in template.reminder_days.children[::-1] if day.state == 'down' ]) repetition = template.times_repetition.text reminder_times = sorted( set([ time.text for time in template.reminder_list.children[::-1] ])) # get priority as text from priority_choice ---> into string of number priority_translation = { '0': 'low', '1': 'normal', '2': 'high', '3': 'very high' } priority = [ key for key, item in priority_translation.items() if item == self.dialog.content_cls.ids.priority_choice.text ][0] # check if any item in list is emplty def items_in_list_empty(list): results = [ True if i not in [None, '', ' '] else False for i in list ] return all(results) # create new habit if items_in_list_empty( [description, reminder_days, reminder_times]): self.parent.add_habit( description=description, week_day=reminder_days, reminder=reminder_times, priority=priority, repetition=repetition, ) # close TaskTemplate self.close_habit_template() else: toast("No Description or reminders?", duration=3.5)
class InfoScreen(Screen): dialog = None def update_info(self): """ Met à jour les informations dans l'onglet "Infos" """ store = JsonStore('info.json') if store.exists('name'): self.ids["name"].secondary_text = store.get("name")["first_name"] self.ids["name"].tertiary_text = store.get("name")["family_name"] if store.exists('birthday'): self.ids["birthday"].secondary_text = datetime.strptime( store.get("birthday")["date"], '%Y:%m:%d').strftime('%d/%m/%Y') if store.exists('class'): self.ids["class"].secondary_text = store.get("class")["value"] def set_birthday(self, date): """ Définis la date d'anniversaire """ JsonStore('info.json').put("birthday", date=date.strftime('%Y:%m:%d')) self.update_info() return date def show_birthday_date_picker(self): """ Ouvre la popup pour choisir la date d'anniversaire """ try: init_date = datetime.strptime( JsonStore('info.json').get("birthday")["date"], '%Y:%m:%d') except KeyError: init_date = datetime.strptime("2000:01:01", '%Y:%m:%d').date() date_dialog = MDDatePicker( callback=self.set_birthday, year=init_date.year, month=init_date.month, day=init_date.day, min_date=datetime.strptime("1990:01:01", '%Y:%m:%d').date(), max_date=datetime.strptime("2010:01:01", '%Y:%m:%d').date()) date_dialog.open() def open_name_popup(self): """ Ouvre une popup pour choisir un nom """ self.dialog = MDDialog(title="Changer de nom:", type="custom", content_cls=NameDialog(), buttons=[ MDFlatButton(text="ANNULER", on_release=self.dialog_close), MDFlatButton(text="OK", on_release=self.set_name), ], size_hint_x=0.8) self.dialog.open() def set_name(self, *args): """ Définis un nouveau nom """ first_name = self.dialog.content_cls.ids[ "first_name_input"].text.capitalize() family_name = self.dialog.content_cls.ids[ "family_name_input"].text.upper() if len(first_name) > 0: JsonStore('info.json').put("name", first_name=first_name, family_name=family_name) self.dialog_close() self.update_info() def open_class_popup(self): """ Ouvre une popup pour changer de classe """ self.dialog = MDDialog(title="Changer de classe:", type="custom", content_cls=ClassDialog(), buttons=[ MDFlatButton(text="ANNULER", on_release=self.dialog_close), MDFlatButton(text="OK", on_release=self.set_class), ], size_hint_x=0.8) self.dialog.open() def set_class(self, *args): """ Définis une nouvelle classe """ JsonStore('info.json').put( "class", value=self.dialog.content_cls.ids["class_input"].text.upper()[0:4]) self.dialog_close() self.update_info() def dialog_close(self, *args): """ Ferme n'importe quel dialogue ouvert """ if self.dialog: self.dialog.dismiss(force=True)
class MainApp(MDApp): Window.size = (380, 680) # main app window = ObjectProperty(None) # id of WindowManager # initializing both units to None unit1 = None unit2 = None def __init__(self, **kwargs): super(MainApp, self).__init__(**kwargs) self.build_app = Builder.load_file( 'strings.kv') # loads the .kv file and stores it in the variable # items in the dropdown list of conversion screen item = [{ 'text': i, "callback": self.callback1 } for i in ('sq ft', 'sq m', 'cent', 'ares')] # dropdown menu of the 'From' button in the conversion screen self.dropdown1 = MDDropdownMenu( width_mult=2.8, caller=self.build_app.window.get_screen('conversion').ids.drop1, items=item, callback=self.callback1) # dropdown menu of the 'To' button in the conversion screen self.dropdown2 = MDDropdownMenu( width_mult=2.8, caller=self.build_app.window.get_screen('conversion').ids.drop2, items=item, callback=self.callback2) def callback1(self, unit): # function called when a list item of the 'From' button is pressed self.root.window.get_screen( 'conversion' ).ids.drop1.text = unit.text # the text in the button is changed self.unit1 = unit.text # the text in the selected menu item is saved self.dropdown1.dismiss( ) # closes the dropdown menu after a menu item is selected def callback2(self, unit): # function called when a list item of the 'To' button is pressed self.root.window.get_screen( 'conversion' ).ids.drop2.text = unit.text # the text in the button is changed self.unit2 = unit.text # the text in the selected menu item is saved self.dropdown2.dismiss( ) # closes the dropdown menu after a menu item is selected def unit_conversion(self): # function called when 'CONVERT' button is pressed if self.unit1 is None or self.unit2 is None: # when no units are chosen, dialog box will appear # close button for the dialog box close = MDFlatButton(text="Close", on_release=self.dialog_close) self.dialog = MDDialog(title="Unit Error", text="Select units", size_hint=(0.7, 1), buttons=[close]) self.dialog.open() else: try: # conversion from one unit to the other value = float( self.root.window.get_screen('conversion').ids.unity.text) # conversion function from the functions module conversion_result = round( functions.conversion(self.unit1, self.unit2, value), 3) self.root.window.get_screen( 'conversion' ).ids.convert.text = f'{str(conversion_result)} {self.unit2}' except Exception: # when the input value is invalid(not a number) dialog box will appear close = MDFlatButton(text="Close", on_release=self.dialog_close) self.dialog = MDDialog(title="Value Error", text="Invalid Input", size_hint=(0.7, 1), buttons=[close]) self.dialog.open() def dialog_close(self, obj): # to close the dialog box when 'Close' button is pressed self.dialog.dismiss() def build(self): return self.build_app # returning the loaded .kv file def to_convert(self): # function to change the screen when the floating action button is pressed self.root.current = 'conversion' self.root.transition.direction = "left" self.root.window.get_screen( 'areawindow').ids.stack_button.close_stack() def to_area(self): # function to change the screen when the floating action button is pressed self.root.current = 'areawindow' self.root.transition.direction = "right" self.unit1 = None self.unit2 = None self.root.window.get_screen('conversion').ids.drop1.text = 'From' self.root.window.get_screen('conversion').ids.drop2.text = 'To'
class BarnsleyFern(MDScreen): def __init__(self, **kwargs): # Текст для Label в разделе теории, список с объектами текстовых полей, содержащих коэффициенты, # номер текущего загружаемого папортника self.labelText = ''' Папоротник Барнсли - фрактал, названный в честь Майкла Барнсли, \ британского математика, который первым описал его в своей книге "Фракталы Повсюду". Является одним из основных \ примеров "самоподобных" множеств, т.е. представляет собой математически генерируемый "шаблон", воспроизводимый при \ любом увеличении или уменьшении количества итераций. Папоротник Барнсли строится при помощи 4-х аффинных преобразований, подобных тому, что представлено на рисунке \ 1. По сути, берутся начальные координаты x, y = (0,0), и затем с определённой вероятностью выбирается одно из этих \ преобразований. С его помощью получаются координаты новой точки и процесс повторяется. Из-за особенностей \ преобразования, чтобы картинка была целой понадобится несколько десятков тысяч операций! Барнсли, в частности, придумал свои 4 преобразования, которые для удобства записал в виде матрицы, в последнем \ столбце которой указал вероятности, с которыми надо выбирать именно это преобразование. Так, коэффициенты в первой строчки матрицы отвечает за отрисовку стебля папоротника, во второй за маленькие \ листочки, а в третьей и четвёртой за большие листья слева и справа от стебля. Изменяя эти коэффициенты и вероятности, \ с которыми выбирается то или иное преобразование, можно получать совершенно различные рисунки. Главное, чтобы не все \ коэффициенты были нулевыми, а сумма вероятностей (последний столбец матрицы с коэффициентами) равнялась единице. Поэкспериментируйте с коэффициентами самостоятельно или загрузите один из предложенных вариантов, нажав на \ кнопку \'Выбор папоротника\'. ''' self.text_fields = list() self.fern_num = 1 super().__init__(**kwargs) self.functions = [self.f1, self.f2, self.f3, self.f4] # Добавление лэйблов и текстовых полей, образующих матрицы с коэффициентами my_widgets = { 'TF1': 0, 'TF2': 0, 'TF3': 0, 'TF4': 0.16, 'TF5': 0, 'TF6': 0, 'TF7': 0.01, 'L11': 'Стебель', 'TF8': 0.85, 'TF9': 0.04, 'TF10': -0.04, 'TF11': 0.85, 'TF12': 0, 'TF13': 1.6, 'TF14': 0.85, 'L13': 'Маленькие листочки', 'TF15': 0.2, 'TF16': -0.26, 'TF17': 0.23, 'TF18': 0.22, 'TF19': 0, 'TF20': 1.6, 'TF21': 0.07, 'L15': 'Большие листочки слева', 'TF22': -0.15, 'TF23': 0.28, 'TF24': 0.26, 'TF25': 0.24, 'TF26': 0, 'TF27': 0.44, 'TF28': 0.07, 'L17': 'Большие листочки справа' } for key in my_widgets: if key[0] == 'L': Lb = MDLabel( text=my_widgets[key], font_style='Caption', text_size=self.size, size_hint=(1.0, 1.0), halign="left", valign="bottom", theme_text_color="Custom", text_color=(1, 1, 1, 1), ) Lb.padding_y = 5 Lb.bind(size=Lb.setter('text_size')) self.ids.settings_layout.add_widget(Lb) else: TF = MyMDTextField(text=str(my_widgets[key]), helper_text_mode="on_focus") TF.helper_text = str(my_widgets[key]) TF.id = key self.ids[key] = TF self.ids.settings_layout.add_widget(TF) self.text_fields.append(TF) # Функции, выпалняющие аффинные преобразования def f1(self, x, y): return self.coef[0] * x + self.coef[1] * y + self.coef[4], \ self.coef[2] * x + self.coef[3] * y + self.coef[5] def f2(self, x, y): return self.coef[7] * x + self.coef[8] * y + self.coef[11], \ self.coef[9] * x + self.coef[10] * y + self.coef[12] def f3(self, x, y): return self.coef[14] * x + self.coef[15] * y + self.coef[18], \ self.coef[16] * x + self.coef[17] * y + self.coef[19] def f4(self, x, y): return self.coef[21] * x + self.coef[22] * y + self.coef[25], \ self.coef[23] * x + self.coef[24] * y + self.coef[26] # Преобразет список координат вида [x1, y1, x2, y2...] под размеры окна def convert(self, xy_list): old_max_x, old_min_x = max(xy_list[::2]), min(xy_list[::2]) old_max_y, old_min_y = max(xy_list[1::2]), min(xy_list[1::2]) old_range = old_max_x - old_min_x, old_max_y - old_min_y newRange = self.ids.draw_SL.width, self.ids.draw_SL.height if old_range[0] == 0 or old_range[1] == 0: self.dialog = MDDialog( text= "При расчёте коэффициентов произошла ошибка! Слишком много нулей " "в таблице данных!", size_hint=(0.4, 0.3), buttons=[ MDFlatButton(text='OK', on_release=self.dialog_close) ]) self.dialog.open() return list() for i, v in enumerate(xy_list): if i % 2 == 0: xy_list[i] = ((v - old_min_x) * newRange[0]) / old_range[0] else: xy_list[i] = ((v - old_min_y) * newRange[1]) / old_range[1] return xy_list # Генерирует координаты по заданным вероятностям и коэффициентам и конвертирует их под размеры окна def generate_convert_xy(self, points): xy_list = list() x, y = 0, 0 probabilities = [ float(self.ids.TF7.text), float(self.ids.TF14.text), float(self.ids.TF21.text), float(self.ids.TF28.text) ] for i in range(points): function = np.random.choice(self.functions, p=probabilities) x, y = function(x, y) xy_list.append(x) xy_list.append(y) return self.convert(xy_list) # Функция, рисующая папоротник def drawing_fern(self, *kw): points = self.ids.slider_p.value self.coef = [float(TF.text) for TF in self.text_fields] # Генерируем координаты точек и преобразовываем их под размеры окна xy_list = self.generate_convert_xy(points) self.ids.draw_SL.content.canvas.after.clear() with self.ids.draw_SL.content.canvas.after: Color(0, 1, 0, mode='rgb') # Класс Point позволяет рисовать только по 32766 точки for i in range(len(xy_list) // 32766): Point(points=xy_list[32766 * i:32766 * (i + 1)], pointsize=1) Point(points=xy_list[32766 * (len(xy_list) // 32766):], pointsize=1) def dialog_close(self, *args): self.dialog.dismiss(force=True) # Проверка значений и запуск рисования папоротника def check_values_and_draw(self): if float(self.ids.TF7.text) + float(self.ids.TF14.text) + float(self.ids.TF21.text) + \ float(self.ids.TF28.text) != 1: self.dialog = MDDialog( text= "Сумма вероятностей (в столбике \'p\') должна равняться 1.00", size_hint=(0.4, 0.3), buttons=[ MDFlatButton(text='OK', on_release=self.dialog_close) ]) self.dialog.open() elif sum([ float(TF.text) for TF in self.text_fields if int(TF.id[2:]) % 7 != 0 ]) == 0: self.dialog = MDDialog( text="Все строки данных не мог быть равны нулю!", size_hint=(0.4, 0.3), buttons=[ MDFlatButton(text='OK', on_release=self.dialog_close) ]) self.dialog.open() else: # Переключаемся на экран с холстом, возвращаем ScatterLayout # в изначальное положение и рисуем новую картинку (рисуем с помощью Clock, чтобы Scatter успел прогрузиться) self.ids.bottom_nav_barnsley.switch_tab('screen 3') trans = Matrix().scale(1, 1, 1) self.ids['draw_SL'].transform = trans Clock.schedule_once(self.drawing_fern) # Выбор другого папортника def fern_selection(self, button): ferns = [[ 'Папоротник Барнсли', [ 0, 0, 0, 0.16, 0, 0, 0.01, 0.85, 0.04, -0.04, 0.85, 0, 1.6, 0.85, 0.2, -0.26, 0.23, 0.22, 0, 1.6, 0.07, -0.15, 0.28, 0.26, 0.24, 0, 0.44, 0.07 ] ], [ 'Папоротник Cyclosorus', [ 0, 0, 0, 0.25, 0, -0.4, 0.02, 0.95, 0.005, -0.005, 0.93, -0.002, 0.5, 0.84, 0.035, -0.2, 0.16, 0.04, -0.09, 0.02, 0.07, -0.04, 0.2, 0.16, 0.04, 0.083, 0.12, 0.07 ] ], [ 'Модиф. Барнсли', [ 0, 0, 0, 0.2, 0, -0.12, 0.01, 0.845, 0.035, -0.035, 0.82, 0, 1.6, 0.85, 0.2, -0.31, 0.255, 0.245, 0, 0.29, 0.07, -0.15, 0.24, 0.25, 0.2, 0, 0.68, 0.07 ] ], [ 'Папоротник Culcita', [ 0, 0, 0, 0.25, 0, -0.14, 0.02, 0.85, 0.02, -0.02, 0.83, 0, 1, 0.84, 0.09, -0.28, 0.3, 0.11, 0, 0.6, 0.07, -0.09, 0.28, 0.3, 0.09, 0, 0.7, 0.07 ] ], [ 'Рыбья кость', [ 0, 0, 0, 0.25, 0, -0.4, 0.02, 0.95, 0.002, -0.002, 0.93, -0.002, 0.5, 0.84, 0.035, -0.11, 0.27, 0.01, -0.05, 0.005, 0.07, -0.04, 0.11, 0.27, 0.01, 0.047, 0.06, 0.07 ] ], [ 'Фрактальное дерево', [ 0, 0, 0, 0.5, 0, 0, 0.05, 0.42, -0.42, 0.42, 0.42, 0, 0.2, 0.4, 0.42, 0.42, -0.42, 0.42, 0, 0.2, 0.4, 0.1, 0, 0, 0.1, 0, 0.2, 0.15 ] ]] button.text = ferns[self.fern_num][0] for i, TF in enumerate(self.text_fields): TF.text = TF.helper_text = str(ferns[self.fern_num][1][i]) # Перейти к следующему папоротнику self.fern_num = (self.fern_num + 1) % 8 if self.fern_num != 5 else 0
class ConvertingApp(MDApp): icons = [] for i in range(33): icons.append( f"Flags\{i}.png" ) #don't forget to write the path of the directory where the Flags file is stored def build(self): self.theme_cls.primary_palette = "Teal" self.theme_cls.primary_hue = "400" self.root = Builder.load_string(KV) return self.root def callback_for_menu_items1(self, *args): """ Is assigns to the first label text the currency name selected by the user.""" self.root.ids.label_item1.text = args[0] def show_example_list_bottom_sheet1(self): """ It shows the list of the currencies together with their flags. If an item from the list is selected the function callback_for_menu_items1(self, *args) is called. i = flag index""" bottom_sheet_menu = MDListBottomSheet() i = 0 for key in exchange_dict: bottom_sheet_menu.add_item( f"{key}", lambda x, y=key: self.callback_for_menu_items1(f"{y}"), icon=self.icons[i]) i += 1 bottom_sheet_menu.open() def callback_for_menu_items2(self, *args): """ It assigns to the second label text the currency name selected by the user.""" self.root.ids.label_item2.text = args[0] def show_example_list_bottom_sheet2(self): """ It shows the list of the currencies together with their flags. If an item from the list is selected the function callback_for_menu_items2(self, *args) is called. i = flag index """ bottom_sheet_menu = MDListBottomSheet() i = 0 for key in exchange_dict: bottom_sheet_menu.add_item( f"{key}", lambda x, y=key: self.callback_for_menu_items2(f"{y}"), icon=self.icons[i]) i += 1 bottom_sheet_menu.open() def convert(self): """ It colects the information submitted by the user and uses the function from the module exchange_oop to make the exchange. It displays the conversion through the result_label.text. If an exception occurs a dialog box is displayed in order to inform the user to introduce an adequate value or to choose the currencies.""" try: converted_currency = Ccy(self.root.ids.label_item1.text, float(self.root.ids.user_input.text)) converted_currency.Converting_Currency( self.root.ids.label_item2.text) self.root.ids.result_label.text = f"{str(converted_currency)}\ {symbols_dict[self.root.ids.label_item2.text]}" except ValueError: self.dialog = MDDialog( title="Atenție!", text="Valoare necorespunzătoare!", type="alert", size_hint=(0.6, 0.5), buttons=[ MDFlatButton(text="OK", text_color=self.theme_cls.primary_color, on_release=self.close_dialog), ], ) self.dialog.open() except Exception: self.dialog = MDDialog( title="Atenție!", text="Selectează moneda!", type="alert", size_hint=(0.6, 0.5), buttons=[ MDFlatButton(text="OK", text_color=self.theme_cls.primary_color, on_release=self.close_dialog), ], ) self.dialog.open() def close_dialog(self, instance): """It closes the dialog box.""" self.dialog.dismiss() def clear_info(self): """ It erases all the inputs from the user and the result of the exchange.""" self.root.ids.label_item1.text = "Monedă" self.root.ids.label_item2.text = "Monedă" self.root.ids.result_label.text = "Rezultat" self.root.ids.user_input.text = ""
class KanjiViewer(ScrollView): 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 showDialog(self, title, text): self.dialog = None if not self.dialog: #self.dialog = MDDialog(title=title,text=text,buttons=[MDFlatButton(text="CLOSE", on_release = lambda *args:self.dialog.dismiss())]) MDApp.get_running_app().dialog_text = text self.dialog = MDDialog( title=title, type="custom", content_cls=DialogContent(), buttons=[ MDFlatButton( text="CLOSE", on_release=lambda *args: self.dialog.dismiss()) ]) #self.dialog = InfoDialog(title=title,text=text) self.dialog.open() def load_new_screen(self): current_screen = self.master.screen_manager.get_screen( self.master.screen_manager.current) current_screen.toolbar.load_new_kanji() # Keyboard methods def _keyboard_closed(self): #print('My keyboard have been closed!') #self._keyboard.unbind(on_key_down=self._on_keyboard_down) #self._keyboard = None pass def _on_keyboard_down(self, keyboard, keycode, text, modifiers): print('The key', keycode, 'have been pressed', ' - text is %r' % text, ' - modifiers are %r' % modifiers, sep="\n") if keycode[1] in ["left", "a"]: self.carousel.load_previous() if keycode[1] in ["right", "d"]: self.carousel.load_next() if keycode[1] == "enter" and not isinstance(self.dialog, MDDialog): self.load_new_screen() #kill_screen("Kanji Viewer",self.master.create_kanji_page) if keycode[1] in ["escape", "enter", 27]: if isinstance(self.dialog, MDDialog): self.dialog.dismiss() # Load new kanji by pressing 'n' if keycode[1] == "n": self.load_new_screen() btn_actions = { "m": self.meanings_btn, "r": self.radicals_btn, "e": self.examples_btn } if keycode[1] in btn_actions: if isinstance(self.dialog, MDDialog): self.dialog.dismiss() btn_actions[keycode[1]].trigger_action(0) # Return True to accept the key. Otherwise, it will be used by the system. return True
class DatabaseOptionsScreen(Screen): def __init__(self, **kwargs): super().__init__(name=kwargs.get("name")) self.con = kwargs.get("con") self.cursor = kwargs.get("cursor") self.getOptions() self.setOptions() self.initUI() def getOptions(self): self.cursor.execute( "SELECT auto_backup, auto_backup_location, remote_database, db_pass, db_user, db_name, db_port, db_host FROM options" ) options = self.cursor.fetchall()[0] self.auto_backup = bool(options[0]) self.auto_backup_location = options[1] self.remote_database = bool(options[2]) self.pg_info = options[3:] def setOptions(self): self.ids.switch.active = self.auto_backup self.ids.location_list_item.secondary_text = self.auto_backup_location self.file_manager_start_path = self.auto_backup_location self.ids.remote_database_switch.active = self.remote_database if all(self.pg_info): for list_item, description in zip( self.ids.remote_database_list.children, self.pg_info): list_item.secondary_text = (description if list_item.text != "Password" else "**********") def initUI(self): data = [ ("Backup Database", "Backup encrypted database"), ("Restore Database", "Restore encrypted database"), ] for text, description in data: self.ids.database_container.add_widget( TwoLineListItem(text=text, secondary_text=description, on_press=self.checkPlatform)) def checkPlatform(self, button): if platform == "android": from android.permissions import ( check_permission, request_permissions, Permission, ) if check_permission("android.permission.WRITE_EXTERNAL_STORAGE"): if isinstance(button, MDSwitch): self.autoBackupFunction(active=button.active) else: self.databaseFunctions(text=button.text) else: if isinstance(button, MDSwitch): if button.active: # request_permissions only run when switch active request_permissions( [ Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, ], partial(self.autoBackupFunction, active=button.active), ) else: request_permissions( [ Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE, ], partial(self.databaseFunctions, text=button.text), ) else: if isinstance(button, MDSwitch): self.autoBackupFunction(active=button.active) else: self.databaseFunctions(text=button.text) def autoBackupFunction(self, permissions=None, grant_result=[True, True], active=False): if not grant_result == [True, True]: self.auto_backup = 0 self.ids.switch.active = False # this line run switch's on_active method # that's why if request_permissions is not run only while switch is active, # request_permissions are run twice self.cursor.execute("UPDATE options SET auto_backup = 0") self.con.commit() toast("Please, Allow Storage Permission") return self.auto_backup = 1 if active else 0 self.cursor.execute("UPDATE options SET auto_backup = ?", (self.auto_backup, )) self.con.commit() if self.auto_backup == 1: shutil.copy2("pass.db", self.auto_backup_location) def autoBackupLocationFunction(self): self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.auto_backup_location_select_path, search="dirs", ) self.file_manager.show(self.file_manager_start_path) self.manager.file_manager_open = True def auto_backup_location_select_path(self, path): if os.path.isdir(path): self.exit_manager() shutil.copy2("pass.db", path) self.cursor.execute("UPDATE options SET auto_backup_location = ?", (path, )) self.con.commit() self.getOptions() self.setOptions() else: toast("Please Select a Directory") def databaseFunctions(self, permissions=None, grant_result=[True, True], text=None): if not grant_result == [True, True]: toast("Please, Allow Storage Permission") return if text == "Backup Database": self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.backup_select_path, search="dirs", ) self.file_manager.show(self.file_manager_start_path) self.manager.file_manager_open = True elif text == "Restore Database": self.file_manager = MDFileManager( exit_manager=self.exit_manager, select_path=self.restore_select_path, ext=[".db"], ) self.file_manager.show(self.file_manager_start_path) self.manager.file_manager_open = True def backup_select_path(self, path): self.exit_manager() shutil.copy2("pass.db", path) toast("Database Backup was Successfully Created") def restore_select_path(self, path): self.openRestoreDatabaseDialog(path) def openRestoreDatabaseDialog(self, path): self.dialog = MDDialog( title="Password of the Database Backup", type="custom", content_cls=DatabasePasswordDialogContent( hint_text="Password of the Database Backup"), buttons=[ MDFlatButton(text="Cancel", on_press=self.dismiss_dialog), MDFlatButton( text="Okay", on_press=lambda x: self.checkBackupPassword( self.dialog.content_cls.ids.password_field.text, path), ), ], ) self.dialog.open() def checkBackupPassword(self, password, path): backup_con = sqlite3.connect(path) backup_cursor = backup_con.cursor() backup_cursor.execute("SELECT master_password, salt FROM options") encrypted, salt = map(bytes.fromhex, backup_cursor.fetchone()) cipher = self.manager.createCipher(password, salt) try: result = cipher.decrypt(encrypted[:16], encrypted[16:], None) if result.decode() == password: restore = True except: restore = False if restore: self.exit_manager() self.dismiss_dialog() shutil.copy2(path, "pass.db") self.manager.cipher = cipher self.getOptions() self.setOptions() toast("Database Successfully Restored") else: toast("Wrong Password") def remoteDatabaseSwitch(self, switch): self.cursor.execute("UPDATE options SET remote_database = ?", (int(switch.active), )) self.con.commit() def remoteDatabaseDialog(self, list_item): content = RemoteDatabaseDialogContent() content.ids.text_field.hint_text = list_item.text self.dialog = MDDialog( title=f"{list_item.text}:", type="custom", content_cls=content, buttons=[ MDFlatButton(text="Cancel", on_press=self.dismiss_dialog), MDRaisedButton( text="Okay", on_press=lambda btn: self.updateRemoteDatabaseOption( list_item, content.ids.text_field.text), ), ], ) self.dialog.open() def updateRemoteDatabaseOption(self, list_item, value): if value.isspace() or value == "": pass else: list_item.secondary_text = (value if list_item.text != "Password" else "**********") text = list_item.text if text == "Database Name": variable_name = "db_name" elif text == "Password": variable_name = "db_pass" else: variable_name = f"db_{text.lower()}" query = f"UPDATE options SET {variable_name} = '{value}'" self.cursor.execute(query) self.con.commit() self.dialog.dismiss() def syncDatabaseButton(self): if self.manager.pg_con is None: self.cursor.execute( "SELECT remote_database, db_name, db_user, db_pass, db_host, db_port FROM options" ) pg_data = self.cursor.fetchone() self.manager.connectRemoteDatabase(pg_data) pg_con = self.manager.pg_con pg_cursor = self.manager.pg_cursor if pg_con is None: toast("Something went wrong") return pg_cursor.execute("SELECT * FROM accounts") remote_data = pg_cursor.fetchall() self.cursor.execute("SELECT * FROM accounts") local_data = self.cursor.fetchall() pg_cursor.execute("SELECT master_password, salt FROM options") remote_options = pg_cursor.fetchone() self.cursor.execute("SELECT master_password, salt FROM options") local_options = self.cursor.fetchone() if remote_data and local_data: toast("Please, Delete 'accounts' table in the PostgreSQL database") # TODO user can select remote or local database for sync elif local_data: def insert_data_to_remote_database(): pg_cursor.execute("INSERT INTO options VALUES(%s, %s)", local_options) for account in local_data: pg_cursor.execute( "INSERT INTO accounts VALUES(%s, %s, %s, %s, %s)", account) pg_con.commit() toast("Sync Completed") toast("Please wait until Sync is Complete") Thread(target=insert_data_to_remote_database).start() elif remote_data: def syncWithRemoteDatabase(password): encrypted, salt = map(bytes.fromhex, remote_options) cipher = self.manager.createCipher(password, salt) try: result = cipher.decrypt(encrypted[:16], encrypted[16:], None) if result.decode() == password: sync = True except: sync = False if sync: dialog.dismiss() toast("Please wait until Sync is Complete") self.cursor.execute( "UPDATE options SET master_password = ?, salt = ? WHERE master_password = ? AND salt = ?", (*remote_options, *local_options), ) for account in remote_data: self.cursor.execute( "INSERT INTO accounts VALUES(?,?,?,?,?)", account) self.con.commit() self.manager.cipher = cipher toast("Sync Completed") else: toast("Wrong Password") dialog = MDDialog( title="Password of the Remote Backup", type="custom", content_cls=DatabasePasswordDialogContent( hint_text="Password of the Remote Backup"), buttons=[ MDFlatButton(text="Cancel", on_press=lambda x: dialog.dismiss()), MDFlatButton( text="Okay", on_press=lambda x: syncWithRemoteDatabase( dialog.content_cls.ids.password_field.text), ), ], ) dialog.open() def exit_manager(self, *args): self.file_manager.close() self.manager.file_manager_open = False def dismiss_dialog(self, btn=None): self.dialog.dismiss() def goBackBtn(self): self.manager.setOptionsScreen()
class sweApp(MDApp): def build(self): self.theme_cls.primary_palette = 'Red' self.theme_cls.theme_style = 'Dark' mainscreen1 = Builder.load_string(nav_widg) self.sensor_refresh = int(mainscreen1.ids.refr_rate_field.text) #handle for this within the imu call and plotting functions self.cop = [] self.height = 0.8636 #height of device, floor to waist of user return mainscreen1 def connect_to_imu(self, obj): if self.root.ids.ipAddr.text is "": handle_ip_empty = "Please enter the Swe IP address" else: pass #self.imu = client_fx() # creates imu connection instance and code runs in background thread close_button = MDFlatButton(text='Ja', on_release=self.close_dialog) self.dialog = MDDialog(title='Connecting...', text='Connection with Swe Initializing...', size_hint=(0.7, 1), buttons=[close_button]) self.dialog.open() def close_dialog(self,obj): self.dialog.dismiss() def navigation_draw(self): print('navigation') def call_imu_data(self): ip_input = self.root.ids.ipAddr.text port_input = int(self.root.ids.portAddr.text) try: self.imu_instance = client_fx(2, ip_input, port_input) Snackbar(text=f'Attempting connection with {ip_input} : {port_input}').show() except: Snackbar(text=f'Cannot connect with {ip_input} : {port_input}... try again later').show() def updatePoints(self, *args): #Pull data from LIFO queue from imu instance instant_imu = self.imu_instance.dq.get() instant_imu = instant_imu[1:5] #try with 4 or 5... odd behabior so debug opp # epoch time since beg 2021 self.c_time = instant_imu[0] - 1609477200 h_vec = [self.height, 0, 0] rr = R.from_quat(instant_imu) s = rr.apply(h_vec) self.cop.append([s[0], -1*s[1]]) if len(self.cop) > 50: self.cop = self.cop[-50:] plot_cop = MeshLinePlot(color=[0, 1, 0, 1]) plot_cop.points = self.cop self.root.ids.graph01.remove_plot(plot_cop) self.root.ids.graph01._clear_buffer(plot_cop) self.root.ids.graph01.add_plot(plot_cop) #self.root.ids.testYawOut.text = f'{instant_imu[1]}-> yaw' #print(f'{instant_imu[0]}') def updateAxis(self, *args): new_time_min = self.c_time - 10 #define an epoch time in seconds that is 10 seconds in the past self.root.ids.graph01.xmin = round(new_time_min) self.root.ids.graph01.xmax = round(self.c_time) def livePlot(self, *args): self.graph_activate = True Clock.schedule_interval(self.updatePoints, 1/self.sensor_refresh) #Clock.schedule_interval(self.updateAxis, 1/self.sensor_refresh) def cancelPlot(self, *args): Clock.unschedule(self.updatePoints)
class DemoApp(MDApp): def __init__(self, **kwargs): super().__init__(**kwargs) # Window.borderless=True theme_colors = [ 'Red', 'Pink', 'Purple', 'DeepPurple', 'Indigo', 'Blue', 'LightBlue', 'Cyan', 'Teal', 'Green', 'LightGreen', 'Lime', 'Yellow', 'Amber', 'Orange', 'DeepOrange', 'Brown', 'Gray', 'x' ] self.theme_cls.primary_palette = "Blue" self.theme_cls.theme_style = "Dark" self.theme_cls.primary_hue = "A700" self.screen = Builder.load_file('mscanner.kv') # Assumptions self.img_to_text_path = '' def build(self): return self.screen def login_fun(self): self.userId = self.screen.get_screen('login').ids.user_id.text self.userpass = self.screen.get_screen('login').ids.password_t.text self.userId = '*****@*****.**' self.userpass = '******' # self.userId = '*****@*****.**' # self.userpass = '******' hasher = pyHash() arrxd = bytes(self.userpass, 'utf-8') hasher.update(arrxd) password = hasher.hexdigest() sql = "SELECT * FROM `user_info` WHERE `Email` = %s" MyCursor.execute(sql, self.userId) self.user_login_data = MyCursor.fetchone() closebtn = MDFlatButton(text='OK', on_release=self.close_dialog1) self.login_flag = 0 if self.user_login_data and self.user_login_data[3] == password: self.login_flag = 1 self.screen.get_screen('login').ids.user_id.text = '' self.screen.get_screen('login').ids.password_t.text = '' MDApp.get_running_app().root.current = "home" MDApp.get_running_app().root.transition.direction = 'left' else: self.screen.get_screen('login').ids.user_id.text = '' self.screen.get_screen('login').ids.password_t.text = '' self.dialog1 = MDDialog( title="Error", text='Invalid user email or password!\nTry again', size_hint=(0.8, 0.5), buttons=[closebtn]) self.dialog1.open() def close_dialog1(self, args): self.dialog1.dismiss() def set_values_after_login(self): if self.login_flag == 1: img_name = self.user_login_data[1].split('@')[0] imgpath = f"D:/Working_dir/Programming/Python/MultiScanner/User_images/{img_name}.jpg" self.screen.get_screen( 'home').ids.main_name_key.text = f"{self.user_login_data[0]}" self.screen.get_screen( 'home').ids.username_email.text = f"{self.user_login_data[1]}" self.screen.get_screen('home').ids.user_image.source = imgpath self.screen.get_screen('profile').ids.profile_img.source = imgpath self.screen.get_screen( 'profile').ids.profile_name.text = f"{self.user_login_data[0]}" self.screen.get_screen( 'profile' ).ids.profile_email.text = f"{self.user_login_data[1]}" # signup functions __________________________________________________________________ def get_registration_values(self): name = self.screen.get_screen('login').ids.user_name_sign.text email = self.screen.get_screen('login').ids.user_email_sign.text img_path = self.screen.get_screen('login').ids.image_path_sign.text password = self.screen.get_screen('login').ids.password_sign.text password2 = self.screen.get_screen('login').ids.password_cnfm_sign.text self.all_value = None flag = 1 erreo_text = '' sql = "SELECT * FROM `user_info` WHERE `Email` = %s" MyCursor.execute(sql, email) data2 = MyCursor.fetchone() if name == '' or email == '' or password == '' or password2 == '': flag = 0 erreo_text = 'Error!!!!!!\nPlease fill up all requirements.' elif password != password2: flag = 0 erreo_text = 'Error!!!!!!\nType same password in both place.' elif len(password) < 6: flag = 0 erreo_text = 'Password is too weak\nMinimum password length 6, containing digits and special character' elif data2: flag = 0 erreo_text = 'Error!!!!!!\nThis email is already registered!!\nTry with other.' if flag == 1: with open(img_path, 'rb') as File_t: binary_img = File_t.read() img_path = binary_img hasher = pyHash() arr = bytes(password, 'utf-8') hasher.update(arr) password = hasher.hexdigest() self.all_value = (name, email, img_path, password) sql = "INSERT INTO `user_info` (`Name`, `Email`, `image`, `Password`) VALUES (%s,%s,%s,%s)" MyCursor.execute(sql, self.all_value) img_name_23 = email.split('@')[0] storeFilePth = f"D:/Working_dir/Programming/Python/MultiScanner/User_images/{img_name_23}.jpg" with open(storeFilePth, 'wb') as img_write: img_write.write(binary_img) img_write.close() conn.commit() o_text = "Congratulation!!\nYour registration is complete\nLogin in your account" closebtn = MDFlatButton(text='OK', on_release=self.close_dialog2) self.dialog2 = MDDialog(title="Congratulation", text=o_text, size_hint=(0.8, 0.5), buttons=[closebtn]) self.dialog2.open() self.screen.get_screen('login').ids.user_name_sign.text = '' self.screen.get_screen('login').ids.user_email_sign.text = '' self.screen.get_screen('login').ids.image_path_sign.text = '' self.screen.get_screen('login').ids.password_sign.text = '' self.screen.get_screen('login').ids.password_cnfm_sign.text = '' else: closebtn = MDFlatButton(text='OK', on_release=self.close_dialog2) self.dialog2 = MDDialog(title="Error", text=erreo_text, size_hint=(0.8, 0.5), buttons=[closebtn]) self.dialog2.open() self.screen.get_screen('login').ids.user_name_sign.text = '' self.screen.get_screen('login').ids.user_email_sign.text = '' self.screen.get_screen('login').ids.image_path_sign.text = '' self.screen.get_screen('login').ids.password_sign.text = '' self.screen.get_screen('login').ids.password_cnfm_sign.text = '' def close_dialog2(self, args): self.dialog2.dismiss() def go_to_home(self): MDApp.get_running_app().root.current = "home" MDApp.get_running_app().root.transition.direction = 'right' def go_to_profile(self): MDApp.get_running_app().root.current = "profile" MDApp.get_running_app().root.transition.direction = 'left' def file_manager_open(self): root = tk.Tk() root.withdraw() path = str(filedialog.askopenfilename(title='Choose a file')) self.screen.get_screen('login').ids.image_path_sign.text = str(path) def logout_fun(self): MDApp.get_running_app().root.current = "login" MDApp.get_running_app().root.transition.direction = 'right' def file_manager_open2(self): root = tk.Tk() root.withdraw() self.img_to_text_path = str( filedialog.askopenfilename(title='Choose a file')) if self.img_to_text_path != '': self.screen.get_screen('home').ids.choose_to_load.text = 'Loaded' self.img_to_text() else: Snackbar(text='No image selected').open() def Show_img(self): from kivy.uix.image import Image if self.img_to_text_path != '': pop = Popup(title='Original image', content=Image(source=self.img_to_text_path), size_hint=(None, None), size=(345, 400)) pop.open() else: Snackbar(text='No Image selected').open() def img_to_text(self): from PIL import Image img = Image.open(self.img_to_text_path) text_extracted = image_to_string(img) text_extracted = text_extracted[:-2] self.screen.get_screen('home').ids.text_extracted.text = text_extracted self.screen.get_screen('home').ids.text_extracted.hint_text = '' Snackbar(text='Image to text conversion successfully done').open() def copy_to_clipboard(self): text_to_copy = self.screen.get_screen('home').ids.text_extracted.text if text_to_copy != '': pc.copy(text_to_copy) Snackbar(text='Text coppied to clipboard').open() else: Snackbar(text='There is nothing to copy').open() def clear1(self): self.screen.get_screen('home').ids.text_extracted.text = '' self.screen.get_screen('home').ids.text_extracted.hint_text = 'Text' def open_camera(self): self.img_to_text_path = '' self.screen.get_screen('home').ids.choose_to_load.text = 'Choose' MDApp.get_running_app().root.current = "cam_scr" MDApp.get_running_app().root.transition.direction = 'left' self.capture = cv2.VideoCapture(0) self.capture.set(10, 70) self.capture.set(10, 75) Clock.schedule_interval(self.load_video, 1.0 / 30.0) def load_video(self, *args): ret, frame = self.capture.read() # frame = cv2.flip(frame,1) # for mirror camera self.image_frame = frame buffer = cv2.flip(frame, 0).tobytes() texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr') texture.blit_buffer(buffer, colorfmt='bgr', bufferfmt='ubyte') self.screen.get_screen('cam_scr').ids.cam_box.texture = texture def save_image(self, *args): img_name = 'D:/Working_dir/Programming/Python/MultiScanner/CaptureImages/test1.png' cv2.imwrite(img_name, self.image_frame) self.go_to_home() self.img_to_text_path = img_name self.img_to_text() def paste_from_clipboard(self): text_to_paste = pc.paste() if text_to_paste != '': self.screen.get_screen( 'home').ids.text_to_speech.text = text_to_paste self.screen.get_screen('home').ids.text_to_speech.hint_text = '' else: Snackbar(text='Clipboard is empty').open() def copy_to_clipboard2(self): text_to_copy = self.screen.get_screen('home').ids.text_to_speech.text if text_to_copy != '': pc.copy(text_to_copy) Snackbar(text='Text coppied to clipboard').open() else: Snackbar(text='There is nothing to copy').open() def clear2(self): self.screen.get_screen('home').ids.text_to_speech.text = '' self.screen.get_screen('home').ids.text_to_speech.hint_text = 'Text' def text_to_speech_fun(self): import pyttsx3 text_to_speech_t = self.screen.get_screen( 'home').ids.text_to_speech.text if text_to_speech_t != '': engine = pyttsx3.init() voices = list(engine.getProperty('voices')) engine.setProperty("rate", 150) engine.setProperty('voice', voices[1].id) engine.say(text_to_speech_t) engine.runAndWait() else: Snackbar(text='There is nothing for speaking').open()
class MainApp(MDApp): client = wolframalpha.Client(appId) speaker = pyttsx3.init() voices = speaker.getProperty('voices') # getting details of current voice speaker.setProperty('voice', voices[1].id) rate = speaker.getProperty( 'rate') # getting details of current speaking rate: 200 speaker.setProperty('rate', 160) # setting up new voice rate speech = sr.Recognizer() # for the app to run def build(self): self.theme_cls.primary_palette = 'Gray' self.theme_cls.theme_style = 'Dark' self.connection_check() screen = Builder.load_string(main_helper) return screen def connection_check(self): conn = hype.HTTPConnection("www.google.com", timeout=5) try: conn.request("HEAD", "/") conn.close() except Exception as e: button = MDFlatButton(text='DISMISS', on_release=self.close_) self.dialog = MDDialog(text='there is no internet connection', size_hint=(0.7, 1), buttons=[button]) self.dialog.open() print(f'there is no internet connection: {e}') conn.close() def close_(self, obj): self.dialog.dismiss() # for typed search def search(self): camp = self.search_result() self.root.current = 'result' self.search_result_label_fill(camp) def search_result(self): var = self.root.ids.main.ids.search.text if var is not '': cap = self.non_search(var) print(cap) return cap else: pass def search_result_label_fill(self, variable): label = MDLabel(text='', halign='left', theme_text_color='Custom', text_color=(1, 1, 1, 1), font_style='Caption') label.text = variable self.root.ids.result.ids.text.add_widget(label) # for voice search def voice(self): print(self.root.current) self.root.current = 'voice' def voice_search(self): try: with sr.Microphone() as source: print('listening..') MainApp.speech.adjust_for_ambient_noise(source) audio = MainApp.speech.listen(source) co = MainApp.speech.recognize_google(audio) print(co) if co == 'end': self.root.current = 'main' print('process has been ended') else: self.non_search(co) except Exception as e: print(f'didn\'t catch that, could you come again? {e}') def create_left(self, variable=''): label = MDLabel( text='', halign='left', theme_text_color='Custom', text_color=(1, 1, 1, 1), font_style='Caption', ) label.text = variable print(label.text) self.root.ids.voice.ids.messages.add_widget(label) def create_right(self, variable): label = MDLabel(text='Hello World', halign='right', theme_text_color='Custom', text_color=(1, 1, 1, 1), font_style='Caption') label.text = variable self.root.ids.voice.ids.messages.add_widget(label) # not used for app building def wolfram_search(self, variable): res = MainApp.client.query(variable) if res['@success'] == 'false': print( 'Question cannot be resolved... you are being redirected to google' ) time.sleep(5) webbrowser.open( f'http://google.com/search?q={variable}') # Go to google.com else: # pod[0] is the question pod0 = res['pod'][0] # pod[1] may contain the answer pod1 = res['pod'][1] if (('definition' in pod1['@title'].lower()) or ('result' in pod1['@title'].lower()) or (pod1.get('@primary', 'false') == 'true')): # extracting result from pod1 result = self.fix_list(pod1['subpod']) question = self.fix_list(pod0['subpod']) question = self.remove_brackets(question) # self.primaryImage(question) return result else: # extracting wolfram question interpretation from pod0 question = self.fix_list(pod0['subpod']) # removing unnecessary parenthesis question = self.remove_brackets(question) # searching for response from wikipedia ret = self.wikipedia_search(question) return ret # self.primaryImage(question) def wikipedia_search(self, variable): # running the query search_results = wikipedia.search(variable) # If there is no result, print no result if not search_results: print( "No result from Wikipedia... you are being redirected to google" ) time.sleep(5) webbrowser.open( f'http://google.com/search?q={variable}') # Go to google.com # Search for page... try block try: page = wikipedia.page(search_results[0]) except (wikipedia.DisambiguationError, error): page = wikipedia.page(error.options[0]) wiki_title = str(page.title.encode('utf-8')) # wiki_summary = str(page.summary.encode('utf-8')) # print(wiki_summary) wiki_2 = str(page.summary) return wiki_2 def remove_brackets(self, variable): return variable.split('(')[0] def fix_list(self, variable): if isinstance(variable, list): return variable[0]['plaintext'] else: return variable['plaintext'] def play_sound(self, variable): MainApp.speaker.say(variable) MainApp.speaker.runAndWait() MainApp.speaker.stop() def primaryImage(self, variable): url = 'http://en.wikipedia.org/w/api.php' data = { 'action': 'query', 'prop': 'pageimages', 'format': 'json', 'piprop': 'original', 'titles': variable } try: res = requests.get(url, params=data) key = res.json()['query']['pages'].keys() for i in key: keys = i if keys == "-1": pass else: imageUrl = res.json( )['query']['pages'][keys]['original']['source'] print(imageUrl) except: print('there was an exception processing the image') def play_n_print(self, variable): statement_1 = variable print(statement_1) self.play_sound(statement_1) def non_search(self, variable): variable.lower() if variable == "what is your name" or variable == "whats your name" or variable == "what's your name": return 'My name is Athena, thanks for asking.' elif variable == "what would you like to call yourself": return 'I would like to be called "The greatest dopest finest virtual beauty there is" but Lord' \ ' psarris says its too much' elif variable == "when were you created": return 'I have no idea. You an ask Lord psarris about that.' elif variable == "who is lord sarris": return 'Lord is my creator, he\'s a really awesome guy' elif variable == "who is jesus": return 'Jesus is the Son of God, who died to redeem us from the curse of the law.' elif variable == "thank you": return 'you are welcome.' exit() elif variable == "thank you that will be all": return 'you are welcome.' exit() else: return self.wolfram_search(variable)
class Diabetes(MDApp): def build(self): screen = MDScreen() label = Builder.load_string(label_helper) self.theme_cls.primary_palette = 'Yellow' self.theme_cls.theme_style = "Dark" self.Pregnancies = Builder.load_string(p_helper) self.Glucose = Builder.load_string(g_helper) self.BloodPressure = Builder.load_string(bp_helper) self.SkinThickness = Builder.load_string(st_helper) self.Insulin = Builder.load_string(i_helper) self.BMI = Builder.load_string(bmi_helper) self.DiabetesPedigreeFunction = Builder.load_string(dp_helper) self.Age = Builder.load_string(age_helper) button = MDRectangleFlatButton(text='Submit', pos_hint={ 'center_x': .5, 'center_y': .04 }, on_release=self.model) screen.add_widget(label) screen.add_widget(self.Pregnancies) screen.add_widget(self.Glucose) screen.add_widget(self.BloodPressure) screen.add_widget(self.SkinThickness) screen.add_widget(self.Insulin) screen.add_widget(self.BMI) screen.add_widget(self.DiabetesPedigreeFunction) screen.add_widget(self.Age) screen.add_widget(button) return screen def model(self, obj): try: pr = float(self.Pregnancies.text) gl = float(self.Glucose.text) bp = float(self.BloodPressure.text) st = float(self.SkinThickness.text) i = float(self.Insulin.text) bmi = float(self.BMI.text) dp = float(self.DiabetesPedigreeFunction.text) age = float(self.Age.text) m = MlModel(pr, gl, bp, st, i, bmi, dp, age) value = m.predict() if value == 0: check_string = 'You have no any sign of Diabetes' else: check_string = 'Consult to doctor you have sign of Diabetes' except Exception as e: check_string = str( e ) + ' ' + 'or try to provide numeric value and provide value for each component listed' close_button = MDRectangleFlatButton(text='Close', on_release=self.close_dialog) self.dialog = MDDialog(title='Result', text=check_string, size_hint=(.7, 1), buttons=[close_button]) self.dialog.open() def close_dialog(self, obj): self.dialog.dismiss()
class HomeScreen(Screen): choose_dialog = None choice = None help_dialog = None def show_ChooseDialog(self): self.choose_dialog = MDDialog( title="Test zameraný pre:", type="confirmation", size_hint=[0.9, 0.5], auto_dismiss=False, items=[ ItemConfirm( text="osobné zlepšenie", on_release=self.next_page_me, on_press=self.close_choose_dialog, ), ItemConfirm( text="prácu v tíme", on_release=self.next_page_team, on_press=self.close_choose_dialog, ), ItemConfirm( text="osobné vzťahy", on_release=self.next_page_we, on_press=self.close_choose_dialog, ) ], ) self.choose_dialog.open() def close_choose_dialog(self, obj): self.choose_dialog.dismiss() print(self.choose_dialog.items) def next_page_me(self, obj): self.manager.current = "motivationme" def next_page_team(self, obj): self.manager.current = "motivationteam" def next_page_we(self, obj): self.manager.current = "motivationwe" def show_HelpDialog(self): ok_button = MDRectangleFlatButton(text="Rozummiem", on_release=self.close_help_dialog) self.help_dialog = MDDialog(title="O čo v teste ide?", text="obkec", size_hint=[0.8, 0.5], auto_dismiss=False, buttons=[ok_button]) self.help_dialog.open() def close_help_dialog(self, obj): self.help_dialog.dismiss() def main_navigate(self, button): if button.icon == "home": self.manager.current = "home" elif button.icon == "lightning-bolt": self.manager.current = "mygoals" elif button.icon == "notebook": self.manager.current = "history"