def set_leds(self, red, green, blue, white): print "turned off:", self.turned_off App.get_running_app().do_color_change \ ( self.send_coap , self.idx , red, green, blue, white, self.status )
def save_notes(self): App.get_running_app().tog.next() Window.release_all_keyboards() self.data2['user']=self.user.text self.data2['pass']=self.passwor.text Clock.schedule_once(self.login_m,1)
def build_board(self): self.ids.screen_msgs_scroll.clear_widgets() board = PostyBase() post_len = [] for x in range(0, 50, 1): post_len += [self.req2[x]['len']] y = self.post_adjust_height(self.req2[x]['len'], self.ids.first_box.width) header = HeaderPost() if x%2 == 0: header.r = 0.9686 header.g = 0.9529 header.b = 0.8275 else: header.r = 0.9843 header.g = 0.9765 header.b = 0.9137 header.ids.header_name.text = self.req2[x]['name'] header.ids.header_time.text = self.req2[x]['time'] board.add_widget(header) if x%2 == 0: board.add_widget(Posty(text=self.req2[x]['msg'], height=y)) else: board.add_widget(Posty2(text=self.req2[x]['msg'], height=y)) self.ids.screen_msgs_scroll.add_widget(board) self.ids._screen_manager.current = 'msgs' App.get_running_app().loading_end()
def print_data(self): d=App.get_running_app().d l=[] l+=self.date_box.text.split(' '); self.date_box.text=date.today().strftime('%B %d %Y') l+=[str(self.name_box.text.strip())]; self.name_box.text='' l+=[str(self.price_box.text.strip())]; self.price_box.text='' l+=[str(self.cat_box.text.strip()) if str(self.cat_box.text.strip())!='' else 'Misc.']; self.cat_box.text='' try: addComplete(d,l) App.get_running_app().man.get_screen('view').refresh() return True except: pu=MyPopUp(title='Input Error', size_hint=(1,.75), auto_dismiss=False) App.get_running_app().popup=pu label=Label(text_size=pu.size, text='Something seems to be wrong with your input.\nCheck help if you\'re unsure what\'s wrong.', halign='center',valign='middle') label.bind(size=label.setter('text_size')) label.size_hint=(1,1) disBtn=Button(text='OK', size_hint=(1,.4)) disBtn.bind(on_release=lambda disBtn: pu.dismiss(disBtn)) puLO=BoxLayout(orientation='vertical') puLO.add_widget(label); puLO.add_widget(disBtn); pu.content=puLO pu.open() return False
def build(self): self.settings_cls = SettingsWithSidebar game = PlanetGame(do_rotation=False,do_translation=False) # Settings come in as unicode! sunmass = float(App.get_running_app().config.get('planetapp','defaultsunmass')) game.sunmass = sunmass game.gravity = float(App.get_running_app().config.get('planetapp','gravity')) game.planetmass = float(App.get_running_app().config.get('planetapp','planetmass')) game.resetmass = float(App.get_running_app().config.get('planetapp','resetmass')) game.add_planet(True, (100,100), (0,0), sunmass, 10, (1,1,1)) Clock.schedule_interval(game.update, 1.0 / 120.0) self.root = PlanetGameLayout() self.root.add_widget(game) b = Button(text="Reset",size_hint=(.3,.05),pos_hint={'x':.7,'y':0}) b.bind(on_press=self.root.clear_planets) self.root.add_widget(b) b2 = SettingsButton(text="Settings",size_hint=(.3,.05),pos_hint={'x':.4,'y':0}) self.root.add_widget(b2) b3 = Button(text="Next",size_hint=(.3,.05),pos_hint={'x':.1,'y':0}) b3.bind(on_press=self.root.next_trajectory) self.root.add_widget(b3) self.root.reset_game()
def export_sheet(self, options, path, filename): config = App.get_running_app().config gcode = GCodeExport( z_flying = float(config.getdefault('gcode', 'z_flying', 3.0)), feed_flying = float(config.getdefault('gcode', 'feed_flying', 1000)), z_cutting = float(config.getdefault('gcode', 'z_cutting', -0.1)), feed_cutting = float(config.getdefault('gcode', 'feed_cutting', 90)), heater_clearance = float(config.getdefault('gcode', 'heater_clearance', 1.0)), z_drilling = float(config.getdefault('gcode', 'z_drilling', 0.4)), z_pocket = float(config.getdefault('gcode', 'z_pocket', -0.2)), x_offset = float(config.getdefault('gcode', 'x_offset', 0.0)), y_offset = float(config.getdefault('gcode', 'y_offset', 0.0)), z_offset = float(config.getdefault('gcode', 'z_offset', 0.0)), x_backslash = float(config.getdefault('gcode', 'x_backslash', 0.01)), y_backslash = float(config.getdefault('gcode', 'y_backslash', 0.01)), ) data = gcode.from_sheet(self.sheet, visualize=False and (platform=='linux')) app = App.get_running_app() # TODO Save only if you're asked to do it! path = App.get_running_app().user_data_dir with open(os.path.join(path, filename), 'w') as f: f.write("{}\n".format(data)) print "Platform?", platform if platform=='android': # TODO: Set this as an option, True by default!! print "Conecta a bt..." app.do_connect() if app.connected: gcode.send_bt(data, app.recv_stream, app.send_stream) else: pass #gcode.send(data) App.get_running_app().root.current = 'main'
def enter_gallery(self, instance): galleryinfo = [instance.gallery_id, instance.gallery_token, instance.pagecount, instance.gallery_name, instance.gallery_tags, instance.gallery_thumb, instance.filesize] existgallery = db.query(Gallery).filter_by( gallery_id=instance.gallery_id).first() if existgallery: pass else: gallery = Gallery(gallery_id=instance.gallery_id, gallery_token=instance.gallery_token, pagecount=instance.pagecount, gallery_name=instance.gallery_name, gallery_thumb=instance.gallery_thumb, filesize=instance.filesize) db.add(gallery) db.commit() for tag in instance.gallery_tags: gallerytag = GalleryTags(galleryid=gallery.id, tag=tag) db.add(gallerytag) db.commit() preview_screen = App.get_running_app( ).root.ids.sadpanda_screen_manager.get_screen("gallery_preview_screen") preview_screen.gallery_id = instance.gallery_id App.get_running_app().root.next_screen("gallery_preview_screen")
def on_back_pressed( self , *args ) : """ :return: """ App.get_running_app().logger.info( 'on_back' )
def on_touch_down(self, touch): """An override of ScatterPlane's on_touch_down. Used to determine the current selected widget and also emits, on_show_edit event. """ if super(ScatterPlane, self).collide_point(*touch.pos) and not self.keyboard: win = EventLoop.window self.keyboard = win.request_keyboard(self._keyboard_released, self) self.keyboard.bind(on_key_down=self._on_keyboard_down) if super(ScatterPlane, self).collide_point(*touch.pos): if not self.dragging: self.touch = touch Clock.schedule_once(self.start_widget_dragging, 0.5) x, y = self.to_local(*touch.pos) target = self.find_target(x, y, self.root) self.selected_widget = target App.get_running_app().focus_widget(target) self.clicked = True self.dispatch("on_show_edit", Playground) return True if self.parent.collide_point(*touch.pos): super(Playground, self).on_touch_down(touch) return False
def update_file_layout(self): auth_token='S2_xUq0_iNAAAAAAAAAACYNG1zf1GAzKpVWVfmLcZLA-FIiSlGxMvmxBkAtspuWQ' client = dropbox.client.DropboxClient(auth_token) self.clear_widgets() b=BoxLayout(orientation='vertical') file_system = FileSystemLocal() root_dir= App.get_running_app().user_data_dir+'/';result_dir=root_dir+'results' file_list=file_system.listdir(root_dir) # this returns a list of files in dir if os.path.exists(result_dir):file_list.extend(file_system.listdir(App.get_running_app().user_data_dir+'/'+'results'+'/')) file_list=[x for x in file_list if x[-4:]=='.csv'] b.add_widget(Label(text='Select Files to Upload',bold=True,font_size=sp(25),size_hint_y= 0.1)) file_system = FileSystemLocal() file_list=file_system.listdir(App.get_running_app().user_data_dir+'/') # this returns a list of files in dir file_list=[x for x in file_list if x[-4:]=='.csv'] s=ScrollView(size_hint_y=0.75) g=GridLayout(cols=2,size_hint_y=None) for file_1 in file_list: c=CheckBox(active=False) l=Label(bold= True,font_size=sp(20),text=file_1,size_hint_y= None,height=70) self.check_boxes[c]=file_1 g.add_widget(l);g.add_widget(c) g.bind(minimum_height=g.setter('height')) s.add_widget(g) b.add_widget(s) g_options=GridLayout(cols=2,size_hint_y= 0.1,orientation='horizontal') g_options.add_widget(Button(text="Send",on_press=self.upload,font_size=sp(25))) g_options.add_widget(Button(text="Back",on_press=self.return_back,font_size=sp(25))) b.add_widget(g_options) self.add_widget(b)
def _event_filter(self, action): from kivy.app import App if action == 'app_terminating': EventLoop.quit = True self.close() elif action == 'app_lowmemory': self.dispatch('on_memorywarning') elif action == 'app_willenterbackground': from kivy.base import stopTouchApp app = App.get_running_app() if not app: Logger.info('WindowSDL: No running App found, exit.') stopTouchApp() return 0 if not app.dispatch('on_pause'): Logger.info('WindowSDL: App doesn\'t support pause mode, stop.') stopTouchApp() return 0 self._pause_loop = True elif action == 'app_didenterforeground': # on iOS, the did enter foreground is launched at the start # of the application. in our case, we want it only when the app # is resumed if self._pause_loop: self._pause_loop = False app = App.get_running_app() app.dispatch('on_resume') return 0
def do_paste(self): '''Paste the selected widget to the current widget ''' parent = self.selected_widget if parent and self.widget_to_paste: class_rules = App.get_running_app().root.\ project_loader.class_rules root_widget = App.get_running_app().root.\ project_loader.root_rule.widget is_child_custom = False for rule in class_rules: if rule.name == type(parent).__name__: is_child_custom = True break # find appropriate parent to add widget_to_paste while parent: if isinstance(parent, Layout) and (not is_child_custom or root_widget == parent): break parent = parent.parent is_child_custom = False for rule in class_rules: if rule.name == type(parent).__name__: is_child_custom = True break if parent is not None: self.add_widget_to_parent(self.widget_to_paste, parent, kv_str=self._widget_str_to_paste) self.widget_to_paste = None
def on_leave(self): '''write setting to logic and save to file''' for key in self.logic.settings: if key in self.setting_items: self.logic.settings[key] = self.setting_items[key].value self.logic.apply_settings() App.get_running_app().settings.save()
def run(self): con_error_cnt = 0 while self.keep_running: print 'connecting to weather' try: owm_is_online = self.link.is_API_online() except: # api_call_error.APICallError con_error_cnt += 1 print 'connection to OWM API failed' if con_error_cnt < 10: print 'will try again in 2 seconds' time.sleep(2) # wait 2 seconds before trying it again continue else: # quit if connection could not be est. 10 times in a row print 'OWM API seems to be offline, quitting' break con_error_cnt = 0 # reset connection error counter if connection was successful if owm_is_online: obs = self.link.weather_at_place(location_str) App.get_running_app().owm_thread_weather = obs.get_weather() else: App.get_running_app().owm_thread_weather = None print('OWM service is offline') time.sleep(owm_fetch_sleep_time) # should be last statement in while loop
def allowed_target_for(self, target, widget): '''This function is used to determine if widget could be added to target. ''' # stop on complex widget t = target if widget else target.parent if isinstance(t, FileChooserListView): return False if isinstance(t, FileChooserIconView): return False # stop on custom widget but not root widget class_rules = App.get_running_app().root.\ project_loader.class_rules root_widget = App.get_running_app().root.\ project_loader.root_rule.widget # if we don't have widget, always return true if widget is None: return True is_widget_layout = isinstance(widget, Layout) is_target_layout = isinstance(target, Layout) if is_widget_layout and is_target_layout: return True if is_target_layout or isinstance(target, Carousel): return True return False
def __init__(self, **kwargs): if hasattr(App.get_running_app(), 'theme_cls'): self._theme_cls = App.get_running_app().theme_cls else: self._theme_cls = ThemeManager() super(ThemeBehaviour, self).__init__(**kwargs) self._rip_color = self._theme_cls.ripple_color
def on_touch_move(self, touch): if touch.grab_current is not self: return False handled = super(DwellOnScatter, self).on_touch_move(touch) if handled: if self.ignore_dwell is not True: #if self.collide_point(touch.x, touch.y): # check dwell on myself, not the kids (todo: refine?) if self.dwell_started_by_touch != touch: self.dwell_started_counter = 0 if self.dwell_started_by_touch is not None: root = App.get_running_app().root root.canvas.remove_group(self.dwell_started_by_touch.ud['dwell']) self.dwell_started_by_touch = None Clock.unschedule(self.process_dwell) else: # rather than base the calculation on the last touch frame, which means the user might be so slow, that a dwell follows them # base it on the original touch position, with the dwell_jitter_distance essentially mimicing a radius # around which a point can be within for the dwell to not be cancelled out diff = [abs(i-j) for i, j in zip(self.dwell_started_by_touch.opos,self.dwell_started_by_touch.pos)] #if abs(self.dwell_started_by_touch.dx) >= self.dwell_jitter_distance_ignore or abs(self.dwell_started_by_touch.dy) >= self.dwell_jitter_distance_ignore: if diff[0] >= self.dwell_jitter_distance_ignore or diff[1] >= self.dwell_jitter_distance_ignore: self.dwell_started_counter = 0 if self.dwell_started_by_touch is not None: root = App.get_running_app().root root.canvas.remove_group(self.dwell_started_by_touch.ud['dwell']) self.dwell_started_by_touch = None Clock.unschedule(self.process_dwell) else: pass # ignore little movements return handled
def hook_keyboard(self, window, key, *largs): if key == 27: if FlashcardAppManager.s_manager.current != 'menu': FlashcardAppManager.s_manager.current = 'menu' else: App.get_running_app().stop() return True
def logfile_end_and_save(self, temp, pres): t = time.localtime(App.get_running_app().root.ph.processStart)[0:6] t_string = self.get_pretty_print_time(t[3], t[4], t[5], "-") date = self.get_pretty_print_time(t[0], t[1], t[2], ".") profile_name = App.get_running_app().root.ph.profile.name file = open(self.get_log_directory()+"/"+ date + "_" + t_string + "_" + profile_name + ".txt", "w") # put logged data into file when process has finished for entity in self.logdata: file.write(entity) if len(temp) > 0: time_string = "Time: [" temp_string = "Temperature: [" pres_string = "Presssure: [" for i in range(0, len(temp)-1): temp_string = temp_string + str(round(temp[i][1], 2)) + "," pres_string = pres_string + str(round(pres[i][1], 2)) + "," time_string = time_string + str(round(temp[i][0], 2)) + "," temp_string = temp_string + str(temp[-1][1]) + "]" pres_string = pres_string + str(pres[-1][1]) + "]" time_string = time_string + str(temp[-1][0]) + "]" file.write("\n") file.write("Logged Temperature and Pressure Data") file.write("\n") file.write(time_string) file.write("\n") file.write(temp_string) file.write("\n") file.write(pres_string) file.close() # clear logdata self.logdata = [] pass
def on_keyboard_down(self, keyboard, keycode, text, modifiers): key = keycode[1] print 'keyboard screen manager', key, text # general key bindings if key == 'q': App.get_running_app().stop() return True # key binding for the wall elif self.current == 'Wall screen': if ((key == 'up' and self.current_active_post_index > 0) or (key == 'down' and self.current_active_post_index < self.number_of_posts - 1))\ and not self.movement_flag: next_index = self.current_active_post_index + 1 if key == 'down' else self.current_active_post_index - 1 self.ids['pw'].scroll_wall(next_index) return True elif key == 'enter': self.ids['pc'].index = self.current_active_post_index self.current = 'Carousel screen' return True # key bindings for the carousel elif self.current == 'Carousel screen': if key == 'up' and self.current_active_post_index > 0 and not self.movement_flag: self.ids['pc'].load_previous() self.current_active_post_index -= 1 elif key == 'down' and self.current_active_post_index < self.number_of_posts - 1 and not self.movement_flag: self.ids['pc'].load_next() self.current_active_post_index += 1 elif key == 'backspace': self.ids['pw'].move_wall_to_index(self.current_active_post_index) self.current = 'Wall screen' return True
def __init__(self, **kwargs): super(BTCommunicator, self).__init__(**kwargs) self.register_event_type('on__connected') self.register_event_type('on_dis_connected') self.register_event_type('on_command_sent') self.register_event_type('on_response') self.register_event_type('on_error') self.register_event_type('on_unknown') App.get_running_app().bind(on_stop=self.stop_reader_stream) curdir = dirname(__file__) try: with open(join(curdir, 'lang', '{}.json'.format(self.language))) as lang_file: self._lang = json.load(lang_file) except Exception as e: raise BTCommunicatorException("Couldn't load {}/lang/{}.json\nError: {}".format(curdir, self.language, e.message)) if platform == 'android': self.BluetoothAdapter = jnius.autoclass('android.bluetooth.BluetoothAdapter') self.BluetoothDevice = jnius.autoclass('android.bluetooth.BluetoothDevice') self.BluetoothSocket = jnius.autoclass('android.bluetooth.BluetoothSocket') self.InputStreamReader = jnius.autoclass('java.io.InputStreamReader') self.BufferedReader = jnius.autoclass('java.io.BufferedReader') self.IOException = jnius.autoclass('java.io.IOException') self.UUID = jnius.autoclass('java.util.UUID') return
def update_tab_value(self, callback): if self.balance_input.text.isnumeric(): App.get_running_app().man.customer_handler.update_tab_value(self.customer, float(self.balance_input.text)) self.customer_layout.ids.balance_label.text = str(float(self.balance_input.text)) self.dismiss() else: self.info_label.text = "Not valid number"
def run_project(self, project): config = ConfigParser() config.read('config.ini') config.set('Project', 'open_project', project) with open('config.ini', 'wb') as configfile: config.write(configfile) App.get_running_app().stop()
def search_tag(self, instance): tag = instance.text search = Search(searchterm=tag) db.add(search) db.commit() App.get_running_app().root.next_screen("front_screen")
def on_touch_move(self, touch): if touch.grab_current is not self: return touch.push() touch.apply_transform_2d(self.to_local) ud = touch.ud # typecasting-problems during cross-compiling # leads to this ugly construction like in calc_hillbodies foo = App.get_running_app().config.get('planetapp','showtrajectorymode') trajectorylength = int(App.get_running_app().config.get('planetapp', 'trajectorylength')) if foo == u'0': ud['lines'][0].points = (ud['firstpos'][0],ud['firstpos'][1], touch.x,touch.y) else: velocity = ((ud['firstpos'][0] - touch.x) / -50, (ud['firstpos'][1] - touch.y) / - 50) planetpos = (ud['firstpos'][0], ud['firstpos'][1]) sunpos = (self.width/2,self.height/2) trajectory = self.calc_trajectory(planetpos, velocity, self.planetmass, sunpos, self.sunmass, 1, trajectorylength) ud['lines'][0].points = trajectory touch.pop()
def make_board_match_view_mode(self, name): board = self.get_screen(name) if self.view_mode[:6] == 'tablet': if not isinstance(board.children[0], TabletBoardView): print 'REFRESHING -> tbv' board = self.get_screen(name) self.close_board(name) board = board.children[0] board.board.save_sgf() filen = board.board.collectionsgf.filen reconstruction_path = board.board.get_reconstruction() new_pbv = self.new_board(from_file=filen, mode='Navigate') new_pbv.board.reconstruct_from(reconstruction_path) new_pbv.board.comment_pre_text = 'This [b]tablet mode[/b] is currently experimental. It should work fine, but is still being tested and will be subject to change (more efficient layout etc.) and speed optimisation before being finalised.\n-----\n' App.get_running_app().manager.refresh_open_games() else: if not isinstance(board.children[0], PhoneBoardView): print 'REFRESHING -> pbv' board = self.get_screen(name) self.close_board(name) board = board.children[0] board.board.save_sgf() filen = board.board.collectionsgf.filen reconstruction_path = board.board.get_reconstruction() new_pbv = self.new_board(from_file=filen, mode='Navigate') new_pbv.board.reconstruct_from(reconstruction_path) App.get_running_app().manager.refresh_open_games()
def upload_to_drive(): google_client = DriveClient() google_client.upload_file(csv_name) App.get_running_app().settings.update_settings(update_time=time_str) os.remove(csv_name) InformationPopup('File uploaded') Logger.info('CustomerHandler: upload thread finished')
def submitGUI(self): """ Submit the GUI Get all settings, confirm they are valid, save new settings file """ ## Error Check All GUI SETTINGS errorCheckPassed = self.check_GUI_settings() # write GUI settings to file if errorCheckPassed: # Convery the GUI_settings from kivy dictproperty to a regular ol' # python dict (and do some reformatting along the way) allSettings = {} for k in self.GUI_settings.keys(): # convert text inputs to integers if k in ['pynealScannerPort', 'resultsServerPort', 'numTimepts']: allSettings[k] = int(self.GUI_settings[k]) else: allSettings[k] = self.GUI_settings[k] # write the settings as the new config yaml file with open(setupConfigFile, 'w') as outputFile: yaml.dump(allSettings, outputFile, default_flow_style=False) # Close the GUI global submitButtonPressed submitButtonPressed = True App.get_running_app().stop() EventLoop.exit()
def leave_game(self): """ Ends the game by stopping the app :return: """ # Exit the application, clean up App.get_running_app().stop()
def submitGUI(self): """ Submit the GUI Get all settings, confirm they are valid, save new settings file """ # Error check all GUI settings errorCheckPassed = self.check_GUI_settings() # write GUI settings to file if errorCheckPassed: # Convery the GUI_settings from kivy dictproperty to a regular ol' # python dict allSettings = {} for k in self.GUI_settings.keys(): allSettings[k] = self.GUI_settings[k] # write the settings as the new config yaml file with open(createMaskConfigFile, 'w') as outputFile: yaml.dump(allSettings, outputFile, default_flow_style=False) # Close the GUI global submitButtonPressed submitButtonPressed = True App.get_running_app().stop() EventLoop.exit()
def botoes_enter(self, win, key, *args): if key == 13 or key == 271: App.get_running_app().stop() return True
def save_image(self, instance): self.test_type = ApplePenApp.get_running_app().t_type # self.a[-1] user_data_dir = App.get_running_app().user_data_dir name = join(user_data_dir, self.local_time + "_" + str(self.test_type) + ".png") instance.export_as_image().save(name)
def __init__(self, **kwargs): Screen.__init__(self, **kwargs) self.layout = BoxLayout(orientation='vertical') menubar = GridLayout(cols=3, rows=1, size_hint_y=None, spacing=5) content = GridLayout(cols=2, size_hint=(1, 1), spacing=0.2) # Core menu layouts home_button = Label(text='Home', font_size=24, size_hint_x=.3) anal_button = Button(text='Analytics', on_press=self.change_to_analytics, font_size=24, size_hint_x=.3) log_button = Button(text='Log', on_press=self.change_to_log, font_size=24, size_hint_x=.3) quit_button = Button(text="X", font_size=24, pos_hint={ 'x': 0.9, 'y': 0.9 }, size_hint=(0.1, 0.1), background_normal='', background_color=(1, 0, 0, 1)) menubar.add_widget(home_button) menubar.add_widget(anal_button) menubar.add_widget(log_button) # creating welcome label accy = App.get_running_app().actual_name welcome_label = Label(text="Welcome back, {}! ".format(accy), font_name='Lobster-Regular', size_hint=(1, None), font_size=60) # setting up of bluetooth, intrusion, universal unlocking and sms setup, linking them to firebase # instantiate widgets bluetooth_label1 = Label( text="Registered Devices :", font_size=24, halign='right', ) bluetooth_label2 = Label(text=" {}".format(self.bluetooth_display()), font_size=24) intrusion_label = Label(text="Last Intrusion:", font_size=24, halign='right') intrusion_status = Label(text="{}".format(self.check_intrusion()), font_size=24, halign='right') uni_unlock_label = Label(text="Lock :", font_size=24, halign='right') switch_button = Switch(active=self.check_status()[0]) sms_setup = Label(text="Alert mode status :", font_size=24, halign='right') sms_switch = Switch(active=self.check_status()[1]) # add widgets content.add_widget(bluetooth_label1) content.add_widget(bluetooth_label2) content.add_widget(intrusion_label) content.add_widget(intrusion_status) content.add_widget(uni_unlock_label) content.add_widget(switch_button) content.add_widget(sms_setup) content.add_widget(sms_switch) # bind buttons to functions anal_button.bind(on_press=self.change_to_analytics) log_button.bind(on_press=self.change_to_log) quit_button.bind(on_press=self.quit_app) switch_button.bind(active=self.uni_unlock) sms_switch.bind(active=self.change_notif) # add widgets self.layout.add_widget(welcome_label) self.layout.add_widget(content) self.layout.add_widget(menubar) # quit app self.add_widget(quit_button) self.add_widget(self.layout)
def on_parent(self, instance, value): if value: app = App.get_running_app() self._back = _back = partial(self.ids.back.dispatch, 'on_release')
def on_touch_move(self, touch): '''This is responsible for moving the drag element and showing where the widget it contains will be added. ''' if touch.grab_current is self: self.playground.sandbox.error_active = True with self.playground.sandbox: target = None self.center_x = touch.x self.y = touch.y + 20 local = self.playground.to_widget(self.center_x, self.y) if self.is_intersecting_playground(self.center_x, self.y): target = self.playground.try_place_widget( self.child, self.center_x, self.y - 20) else: # self.widgettree.collide_point(self.center_x, self.y) # not working :( # had to use this method if self.is_intersecting_widgettree(self.center_x, self.y): node = self.widgettree.tree.get_node_at_pos( (self.center_x, touch.y)) if node: if node.node == self.child: return True else: while node and \ node.node != self.playground.sandbox: widget = node.node if self.playground.allowed_target_for( widget, self.child): target = widget break node = node.parent_node if widget_contains(self.child, target): return True if self.child.parent: if self.target: if isinstance(self.target, ScreenManager): if isinstance(self.child, Screen): self.target.remove_widget(self.child) self.target.real_remove_widget(self.child) elif not isinstance(self.target, TabbedPanel): self.target.remove_widget(self.child) if self.child.parent: self.child.parent.remove_widget(self.child) if self.drag_type == 'dragndrop': self.can_place = target == self.drag_parent else: self.can_place = target is not None self.child.pos = self.first_pos self.child.size_hint = self.first_size_hint self.child.size = self.first_size if target: if self.can_place and self.drag_type == 'dragndrop': if self.is_intersecting_playground( self.center_x, self.y): x, y = self.playground.to_local(*touch.pos) target2 = self.playground.find_target( x, y, self.playground.root) if target2.parent: _parent = target2.parent target.add_widget( self.child, _parent.children.index(target2)) else: if self.is_intersecting_widgettree( self.center_x, self.y): node = self.widgettree.tree.get_node_at_pos( (self.center_x, touch.y)) if node: target2 = node.node if target2.parent: _parent = target2.parent target.add_widget( self.child, _parent.children.index(target2)) self.show_lines_on_child() elif not self.can_place and self.child.parent != self: self.remove_lines_on_child() self.child.pos = (0, 0) self.child.size_hint = (1, 1) self.add_widget(self.child) elif self.can_place and self.drag_type != 'dragndrop': if isinstance(target, ScreenManager): target.real_add_widget(self.child) else: target.add_widget(self.child) self.show_lines_on_child() App.get_running_app().focus_widget(target) elif not self.can_place and self.child.parent != self: self.remove_lines_on_child() self.child.pos = (0, 0) self.child.size_hint = (1, 1) self.add_widget(self.child) self.target = target return True
def close(self): App.get_running_app().stop()
def leave_room(self): app = App.get_running_app() app.send_message(f"09".encode())
def exitApp(self, *args): App.get_running_app().stop()
def dequeue_upgrade(): root = App.get_running_app().root if isinstance(root.menu_bar, MainActionView): root.menu_bar.remove_notification()
def show_error(self, msg): app = App.get_running_app() Clock.schedule_once(lambda dt: app.show_error(msg))
def on_dismiss(self): app = App.get_running_app() if app.wallet is None and not self._on_release: app.stop()
def on_parent(self, instance, value): if value: app = App.get_running_app() self._back = _back = partial(app.dispatch, 'on_back')
def __init__(self, **kwargs): super(SettingTheme, self).__init__(**kwargs) app = App.get_running_app() self.labelvalue = ', '.join( (_(app.theme_cls.primary_palette), _(app.theme_cls.theme_style)))
def _set_option(self): app = App.get_running_app() self.value = ','.join( (app.theme_cls.primary_palette, app.theme_cls.theme_style)) self.labelvalue = ', '.join( (_(app.theme_cls.primary_palette), _(app.theme_cls.theme_style)))
def loser(self, *args): app = App.get_running_app() app.root.current = "Loser"
def close(self, *_): app = App.get_running_app() app.popup.dismiss()
def exit(self): App.get_running_app().stop()
def exitProgram(self, obj): App.get_running_app().stop() Window.close()
def logout(self): app = App.get_running_app() app.root.transition = NoTransition() app.root.current = 'login_screen' self.resetPages()
def on_enter(self, *args): c = App.get_running_app() # self.cargo_fijo_2.text = c.big_dict["cargo_fijo"] # print(c.big_dict["cargo_fijo"]) print("Gear Secondo")
def SetSSNAfterCreation(self): App.get_running_app().adminCustomer = CurrentAdminCustomer() App.get_running_app().adminCustomer.ssn = self.ids.ssn.text
class AdminScreen(Screen): app = App.get_running_app() activeCustomer = False account_number = "" account_type = "" account_balance = "" account_interest = "" admin_dropdown = "" def change_screen(self, instance): #app = App.get_running_app() self.ids.screen_manager.transition = NoTransition() if instance.text == 'Create Account': if self.ids.screen_manager.current == 'add_user_screen' or self.ids.screen_manager.current == 'add_account_screen': pass else: self.ids.screen_manager.current = 'add_user_screen' elif instance.text == 'Manage Accounts': self.ids.screen_manager.current = 'user_screen' # elif instance.text == 'Delete Account': # self.ids.screen_manager.current = 'delete_account_screen' def SetCurrentCustomer(self): if self.check_is_integer(self.ids.lookup_customer.text) == 0 or self.check_account_length(self.ids.lookup_customer.text) == 0: self.SetStatus("Enter valid SSN", 'Error') self.ids.customerName.text = "Enter valid SSN" self.activeCustomer = False return else: self.activeCustomer = True self.SetStatus("User account found!", 'Valid') App.get_running_app().adminCustomer = CurrentAdminCustomer() App.get_running_app().adminCustomer.ssn = self.ids.lookup_customer.text def SetStatus(self, status, statustype): self.ids.status_text.text = status # if statustype.upper() == "ERROR": # self.canvas.before.clear() # with self.canvas.before: # Color(1, 0, 0, 1) # Rectangle(pos=self.pos, size=self.size) def SetStatusCustomerName(self, first, last): self.ids.current_customer_status_bar.text = first + " " + last self.ids.customerName.text = first + " " + last def GetAccountInfo(self, acct_number): token = App.get_running_app().token sess = App.get_running_app().sess aDict = { # must use dictionary, is requirement of the request library "acct_number": acct_number } hDict = { "Authorization": "Token " + token } r = sess.post('https://localhost/view_customerAcct/', data=aDict, headers=hDict, verify="C:/Users/Adam PC/Desktop/Apache24/certs/Ursus.crt") test = json.loads(r.text) y = json.loads(r.text) App.get_running_app().adminCustomer.first_name = y['acct_infoToBePrinted']['first_name'] App.get_running_app().adminCustomer.last_name = y['acct_infoToBePrinted']['last_name'] #fetched_acct_teller_details = str(y['acct_infoToBePrinted']['acct_number']) + " - " + y['acct_infoToBePrinted']['acct_type'] self.admin_dropdown = str(y['acct_infoToBePrinted']['acct_number']) + " - " + y['acct_infoToBePrinted']['acct_type'] #return fetched_acct_teller_details def GetSelectedAccountInfo(self, acct_number): token = App.get_running_app().token sess = App.get_running_app().sess aDict = { # must use dictionary, is requirement of the request library "acct_number": acct_number } hDict = { "Authorization": "Token " + token } r = sess.post('https://localhost/view_customerAcct/', data=aDict, headers=hDict, verify="C:/Users/Adam PC/Desktop/Apache24/certs/Ursus.crt") test = json.loads(r.text) y = json.loads(r.text) self.account_type = y['acct_infoToBePrinted']['acct_type'] self.account_balance = str(y['acct_infoToBePrinted']['acct_balance']) self.account_interest = str(y['acct_infoToBePrinted']['acct_interest']) def OnSpinnerSelect(self, text): accountNum = self.ids.userAccounts.text.split(' ')[0] self.GetSelectedAccountInfo(accountNum) self.ids.accountNumber.text = accountNum self.ids.accountType.text = self.account_type self.ids.accountBalance.text = self.account_balance self.ids.accountInterest.text = self.account_interest def ResetAccountInfo(self): self.ids.accountType.text = "" self.ids.accountBalance.text = "" self.ids.accountNumber.text = "" self.ids.accountInterest.text = "" self.ids.userAccounts.text = "Click To Select Account" def SearchCustomer(self): if self.activeCustomer == False: return else: token = App.get_running_app().token sess = App.get_running_app().sess print("ssn right before: " + App.get_running_app().adminCustomer.ssn) ssnDict = { # must use dictionary, is requirement of the request library "ss_number": App.get_running_app().adminCustomer.ssn } hDict = { "Authorization": "Token " + token } r = sess.post('https://localhost/find_customerAcct/', data=ssnDict, headers=hDict, verify="C:/Users/Adam PC/Desktop/Apache24/certs/Ursus.crt") test = json.loads(r.text) print(test['acct_numbers']) accounts = [] if test['acct_numbers'] == "Account Number Not Located, Account Does Not Exist!": self.SetStatus("Account Not Found", "ERROR") self.ids.customerName.text = "Account Not Found" else: if test['acct_numbers'] == "" or test['acct_numbers'] == []: self.SetStatus("No Accounts Found", "Error") self.ids.customerName.text = "No Accounts Found" return for acct_number in test['acct_numbers']: self.GetAccountInfo(acct_number) accounts.append(self.admin_dropdown) #print("LENGTH: " + len(accounts)) self.ids.userAccounts.values = accounts self.SetStatusCustomerName(App.get_running_app().adminCustomer.first_name, App.get_running_app().adminCustomer.last_name) def RemoveUser(self): if(self.activeCustomer == False): self.SetStatus("No User Selected", "Error") return token = App.get_running_app().token sess = App.get_running_app().sess dDict = { # must use dictionary, is requirement of the request library "ss_number": App.get_running_app().adminCustomer.ssn, } hDict = { "Authorization": "Token " + token } r = sess.post('https://localhost/delete_User/', data=dDict, headers=hDict,verify="C:/Users/Adam PC/Desktop/Apache24/certs/Ursus.crt") test = json.loads(r.text) self.SetStatus("User Removed", "Valid") #print(test['acct_infoToBePrinted']) self.ResetUserScreen() App.get_running_app().adminCustomer = CurrentAdminCustomer() def RemoveAccount(self): if self.activeCustomer == False or self.CheckIfDropDownIsSelected(self.admin_dropdown) == 0: self.SetStatus("No Account Selected", "Error") return token = App.get_running_app().token sess = App.get_running_app().sess acct_number = self.ids.userAccounts.text.split(' ')[0] dDict = { # must use dictionary, is requirement of the request library "acct_number": acct_number, } hDict = { "Authorization": "Token " + token } r = sess.post('https://localhost/delete_customerAcct/', data=dDict, headers=hDict, verify="C:/Users/Adam PC/Desktop/Apache24/certs/Ursus.crt") test = json.loads(r.text) self.SetStatus("Account Removed", "Valid") self.ResetUserAccountDetails() #self.ResetUserScreen() self.SearchCustomer() def AddInterest(self): if self.activeCustomer == False or self.CheckIfDropDownIsSelected(self.admin_dropdown) == 0: self.SetStatus("No Account Selected", "Error") return token = App.get_running_app().token sess = App.get_running_app().sess acct_number = self.ids.userAccounts.text.split(' ')[0] dDict = { # must use dictionary, is requirement of the request library "acct_number": acct_number, } hDict = { "Authorization": "Token " + token } r = sess.post('https://localhost/apply_Interest/', data=dDict, headers=hDict, verify="C:/Users/Adam PC/Desktop/Apache24/certs/Ursus.crt") test = json.loads(r.text) self.SetStatus(test['acct_infoToBePrinted'], "Valid") self.ResetUserAccountDetails() self.SearchCustomer() def CheckIfDropDownIsSelected(self, dropdown): if dropdown == "Select Account" or dropdown == "Click To Select Account": self.UpdateStatusBar("Account Not Selected", "Error") return 0 else: return 1 def check_is_integer(self, number_to_check): try: val = int(number_to_check) return 1 except ValueError: return 0 def check_account_length(self, num): length_count = len(num) if length_count == 9: return 1 else: return 0 def CheckTextFields(self, text): if text.isalpha(): return 1 else: return 0 def CheckIsNotEmpty(self, text): if text != "": return 1 else: return 0 def CheckIfEmail(self, email): if '@' in email and '.' in email: return 1 else: return 0 def CheckPhoneNumber(self, phone): if len(phone) >= 10: for a in phone: if a.isdigit() or a == '-': return 1 else: return 0 def GoToAddAccountFromUserScreen(self): if(self.activeCustomer == False): self.SetStatus("No Current User", "Error") return else: self.ids.screen_manager.current = 'add_account_screen' def GoToAddAccountFromAddUser(self): self.ids.screen_manager.transition.direction = 'left' self.ids.screen_manager.current = 'add_account_screen' def GoToAddUserScreen(self): self.ids.screen_manager.transition.direction = 'left' self.ids.screen_manager.current = 'add_user_screen' def CheckNewUserDetails(self): #first name if self.CheckTextFields(self.ids.firstName.text) == 0 or self.CheckIsNotEmpty(self.ids.firstName.text) == 0: self.SetStatus("Enter Valid First Name", "Error") return 0 #last name elif self.CheckTextFields(self.ids.lastName.text) == 0 or self.CheckIsNotEmpty(self.ids.lastName.text) == 0: self.SetStatus("Enter Valid Last Name", "Error") return 0 #Address elif self.CheckIsNotEmpty(self.ids.streetAddress.text) == 0: self.SetStatus("Enter Valid Address", "Error") return 0 #City elif self.CheckIsNotEmpty(self.ids.city.text) == 0: self.SetStatus("Enter Valid City", "Error") return 0 #State elif self.CheckIsNotEmpty(self.ids.state.text) == 0 or self.CheckTextFields(self.ids.state.text) == 0: self.SetStatus("Enter Valid State", "Error") return 0 #Zipcode elif self.check_is_integer(self.ids.zipcode.text) == 0: self.SetStatus("Enter Valid Zip Code", "Error") return 0 #Email elif self.CheckIfEmail(self.ids.email.text) == 0: self.SetStatus("Enter Valid Email", "Error") return 0 #Phone Number elif self.CheckPhoneNumber(self.ids.phoneNumber.text) == 0: self.SetStatus("Enter Valid Phone Number", "Error") return 0 #Account Type elif self.ids.accountTypeDropdown.text == "Select Account": self.SetStatus("Select An Account Type", "Error") return 0 #SSN elif self.check_account_length(self.ids.ssn.text) == 0 or self.check_is_integer(self.ids.ssn.text) == 0: self.SetStatus("Enter Valid SSN", "Error") return 0 #Username elif self.CheckIsNotEmpty(self.ids.newUsername.text) == 0: self.SetStatus("Enter Valid Username", "Error") return 0 #Username elif self.CheckIsNotEmpty(self.ids.newPassword.text) == 0: self.SetStatus("Enter Valid Password", "Error") return 0 def FinishAddUser(self): isAdmin = False isTeller = False if self.CheckNewUserDetails() == 0: return token = App.get_running_app().token sess = App.get_running_app().sess if self.ids.accountTypeDropdown.text == 'Teller': isAdmin = False isTeller = True elif self.ids.accountTypeDropdown.text == 'Admin': isAdmin = True isTeller = False firstname = self.ids.firstName.text lastname = self.ids.lastName.text address = self.ids.streetAddress.text city = self.ids.city.text state = self.ids.state.text zipcode = self.ids.zipcode.text email = self.ids.email.text phonenumber = self.ids.phoneNumber.text ssn = self.ids.ssn.text username = self.ids.newUsername.text password = self.ids.newPassword.text cDict = { #must use dictionary, is requirement of the request library "first_name": firstname, "last_name" : lastname, "ss_number": ssn, "street_address": address, "city": city, "state": state, "zip_code": zipcode, "email_address": email, "phone_number": phonenumber, "username" : username, "password" : password, "isAdmin": isAdmin, "isTeller": isTeller, } hDict = { "Authorization": "Token " + token } r = sess.post('https://localhost/create_acct/', data = cDict, headers = hDict, verify="C:/Users/Adam PC/Desktop/Apache24/certs/Ursus.crt") #self.SetCurrentCustomer() self.ids.lookup_customer.text = ssn self.SetSSNAfterCreation() self.ClearDetails() self.SetStatus("New Customer Added", "Valid") self.ids.screen_manager.current = 'add_account_screen' def SetSSNAfterCreation(self): App.get_running_app().adminCustomer = CurrentAdminCustomer() App.get_running_app().adminCustomer.ssn = self.ids.ssn.text #self.adminCustomer = True def AddAccount(self): token = App.get_running_app().token sess = App.get_running_app().sess if App.get_running_app().adminCustomer.ssn == "": print(App.get_running_app().adminCustomer.ssn) pass print("ssn lookup: " + App.get_running_app().adminCustomer.ssn) if self.ids.newAccountType.text == "Select Account": self.SetStatus acct_number = random.randint(0, 999999999) caDict = { "ss_number" : App.get_running_app().adminCustomer.ssn, "acct_type": self.ids.newAccountType.text, "acct_number": acct_number, "acct_balance": self.ids.startingBalance.text, } hDict = { "Authorization": "Token " + token } r = sess.post('https://localhost/create_customerAcct/', data=caDict, headers=hDict, verify="C:/Users/Adam PC/Desktop/Apache24/certs/Ursus.crt") #If error message: # update status #else: test = json.loads(r.text) self.SetStatus(test['acct_infoToBePrinted'], "Valid") self.ResetAddAccountScreen() #def AddAccountPageFinish(self): def ClearDetails(self): self.ids['firstName'].text = "" self.ids['lastName'].text = "" self.ids['streetAddress'].text = "" self.ids['city'].text = "" self.ids['state'].text = "" self.ids['zipcode'].text = "" self.ids['email'].text = "" self.ids['phoneNumber'].text = "" self.ids['accountType'].text = "Select Amount" self.ids['ssn'].text = "" self.ids['newUsername'].text = "" self.ids['newPassword'].text = "" def ResetUserScreen(self): self.ids.accountType.text = "" self.ids.accountNumber.text = "" self.ids.accountBalance.text = "" self.ids.accountInterest.text = "" self.ids.userAccounts.text = "Click To Select Account" self.ids.userAccounts.values = [] self.ids.customerName.text = "" self.ids.lookup_customer.text = "" self.SetStatusCustomerName("", "") def ResetUserAccountDetails(self): self.ids.accountType.text = "" self.ids.accountNumber.text = "" self.ids.accountBalance.text = "" self.ids.accountInterest.text = "" self.ids.userAccounts.values = [] self.ids.userAccounts.text = "Click To Select Account" def ResetAddAccountScreen(self): self.ids.newAccountType.text = "Select Account" self.ids.startingBalance.text = "" def logout(self): app = App.get_running_app() app.root.transition = NoTransition() #self.ids.screen_manager.current == 'add_user_screen' #self.ids.user_toggle.state = 'down' #self.ids.add_account_toggle = 'normal' app.root.current = 'login_screen' self.ResetScreen() def ResetScreen(self): self.ClearDetails() self.ResetUserScreen() self.ResetAddAccountScreen()
def __init__(self, **kwargs): super(MoveButton, self).__init__(**kwargs) self.app = App.get_running_app() self.main_cube = self.app.main_cube
def on_kv_post(self, base_widget): super().on_kv_post(base_widget) gear_list = self.children[0] app = App.get_running_app() gear_list.refill(app.char.mutation.gear)
def close(self): app = App.get_running_app() if self._back in app.navigation_higherarchy: app.navigation_higherarchy.pop() self._back = None super(InitSeedDialog, self).close()
def quit_app(self, value): App.get_running_app().stop()
def save_screen_for_reload(self, screen_name): App.get_running_app().config.set('internal', 'last screen', screen_name) App.get_running_app().save_config() print('should be saved.............................', screen_name)
def get_last_screen(self): last_screen = App.get_running_app().config.get('internal', 'last screen') print('%%%%%%%%%%%%%%%%', last_screen) return last_screen
def do_select_all(self): '''Select All widgets which basically means selecting root widget ''' self.selected_widget = self.root App.get_running_app().focus_widget(self.root)
def events_program(self, instance, keyboard, keycode, text, modifiers): if keyboard in (1001, 27): from kivy.app import App App.get_running_app().main_widget.ids.scr_mngr.current = "previous" App.get_running_app().main_widget.ids.toolbar.height = dp(56)