def deleteFile(): try: self.closeDocument(editorInput) os.remove(editorInput.filename) toast("Delete the file : " + filename) except: log(traceback.format_exc())
def remove_action(self, action): if self._action == action: self._action = None Clock.unschedule(self.on_new_intent) else: # raise ValueError('Action isn\' defined') toast('Action isn\' defined')
def remove_action(self, action): if self._action == action: self._action = None self.nfc_disable_ndef_exchange() else: # raise ValueError('Action isn\' defined') toast('Action isn\' defined')
def save_image(self, size=None): '''Save an image of the superposition texture.''' if size is None: size = self.root.shader_widget.size toast.toast('Saving...') fs = self.root.shader_widget.fs with self.root.canvas: self.fbo = Fbo(size=size) with self.fbo: Color(1, 1, 1, 1) Rectangle(size=(10000, 10000)) self.fbo.shader.fs = fs self.fbo['time'] = 0.0 self.fbo['resolution'] = map(float, self.fbo.size) shader = self.root.shader_widget for wv in shader.wavevectors: number = wv.number current_uniform = 'k{}'.format(number) self.fbo[current_uniform] = [float(wv.kx), float(wv.ky)] Clock.schedule_once(self.finish_save, 0)
def export(self): export_dir = join( self.export_base_dir, datetime.now().strftime('%Y-%m-%d_%H-%M-%S') ) try: mkdir(export_dir) except OSError: pass dump_csv(Session.select(Session.name, Session.date), join(export_dir, 'sessions.csv')) dump_csv(Member.select(Member.tag_id, Member.name), join(export_dir, 'members.csv')) for session in Session.select(): dump_csv( SessionAttendance.select( SessionAttendance.session, SessionAttendance.member ).where( SessionAttendance.session == session.id ), join( export_dir, 'session_{}.csv'.format(session.name.replace(' ', '_')) ) ) toast('Successfully exported to \n{}'.format(export_dir)) self.update_interface()
def delete_session(self, session): try: SessionAttendance.select().where( SessionAttendance.session == session.id ).get().delete_instance() except DoesNotExist: toast('Session does not exist') else: self.ids.session_list.adapter.data.remove(session)
def delete_attendace(self, attendance): try: SessionAttendance.select().where( SessionAttendance.member == attendance.id ).get().delete_instance() except DoesNotExist: toast('Member does not exist') else: self.ids.attendance_list.adapter.data.remove(attendance)
def finish_save(self, *args): # if platform == 'android': # if not os.path.exists('{}/planewaves'.format(pictures_path)): # os.mkdir('{}/planewaves'.format(pictures_path)) filen = self.get_save_filen() self.fbo.texture.save(filen) toast.toast('Saved as {}'.format(filen)) self.root.canvas.remove(self.fbo) self.fbo = None
def send_email(self, *args): addr_from = "*****@*****.**" # Отправитель password = "******" # Пароль msg = MIMEMultipart() # Создаем сообщение msg['From'] = addr_from # Адресат msg['To'] = self.screen.ids.diary.ids.mail_to.text # Получатель msg['Subject'] = self.screen.ids.diary.ids.theme.text # Тема сообщения users_name = self.screen.ids.diary.ids.user_name.text.replace(' ', '_') name = 'diary.xls' filepath = os.path.join(os.getcwd(), name) filename = os.path.basename(filepath) if os.path.isfile(filepath): rb = xlrd.open_workbook(filepath, formatting_info=True) wb = copy(rb) wb.save(users_name+'_diary.xls') os.remove(filepath) name = users_name+'_diary.xls' filepath = os.path.join(os.getcwd(), name) filename = os.path.basename(filepath) body = 'Дневник головной боли:\n\nПациент: '+ self.screen.ids.diary.ids.user_name.text + '\n'+\ 'Комментарий пациента: ' + self.screen.ids.diary.ids.comment.text + '\n\n' +\ 'Адресс для обратной связи: ' + self.screen.ids.diary.ids.add_mail.text # Текст сообщения msg.attach(MIMEText(body, 'plain')) # Добавляем в сообщение текст if os.path.isfile(filepath): # Если файл существует ctype, encoding = mimetypes.guess_type(filepath) # Определяем тип файла на основе его расширения if ctype is None or encoding is not None: # Если тип файла не определяется ctype = 'application/octet-stream' # Будем использовать общий тип maintype, subtype = ctype.split('/', 1) # Получаем тип и подтип with open(filepath, 'rb') as fp: file = MIMEBase(maintype, subtype) # Используем общий MIME-тип file.set_payload(fp.read()) # Добавляем содержимое общего типа (полезную нагрузку) fp.close() encoders.encode_base64(file) # Содержимое должно кодироваться как Base64 file.add_header('Content-Disposition', 'attachment', filename=filename) # Добавляем заголовки msg.attach(file) # Присоединяем файл к сообщению server = smtplib.SMTP_SSL('smtp.yandex.ru', 465) # Создаем объект SMTP server.login(addr_from, password) # Получаем доступ server.send_message(msg) # Отправляем сообщение server.quit() # Выходим rb = xlrd.open_workbook(filepath, formatting_info=True) wb = copy(rb) wb.save(users_name+'_old_diary.xls') self.create_new_table(name) toast(self.translation._('Дневник отправлен')) self.screen.ids.diary.ids.mail_to.text = '' self.screen.ids.diary.ids.theme.text = '' self.screen.ids.diary.ids.comment.text = ''
def dialog_exit(self): def check_interval_press(interval): self.exit_interval += interval if self.exit_interval > 5: self.exit_interval = False Clock.unschedule(check_interval_press) if self.exit_interval: sys.exit(0) Clock.schedule_interval(check_interval_press, 1) toast(self.translation._('Нажмите еще раз для выхода'))
def get_online_data(self): toast('Getting Latest Data from Server') rage_req = UrlRequest( 'http://heroku_app_address.herokuapp.com/get_number_of_rages', on_success=self.rage_request_success, on_failure=self.rage_request_fail, timeout=5.) no_rage_req = UrlRequest( 'http://heroku_app_address.herokuapp.com/get_number_of_tranq', on_success=self.no_rage_request_success, on_failure=self.no_rage_request_fail, timeout=5.)
def dialog_exit(self): def check_interval_press(interval): self.exit_interval += interval if self.exit_interval > 5: self.exit_interval = False Clock.unschedule(check_interval_press) if self.exit_interval: sys.exit(0) Clock.schedule_interval(check_interval_press, 1) toast(self.translation._('Press Back to Exit'))
def on_select(path_to_avatar): self.window_file_manager.dismiss() if os.path.splitext(path_to_avatar)[1] \ not in self.POSSIBLE_FILES[:3]: toast(self.translation._('This is not image!')) else: new_path_to_avatar = \ self.directory + '/data/images/avatar.png' create_previous_portrait(path_to_avatar, new_path_to_avatar) self.set_avatar(new_path_to_avatar) toast(self.translation._('Аватар изменён')) self.nav_drawer.state = 'open'
def create_new_session(self): if not self.ids.session_name.text: toast('Session name can\'t be empty') return try: session = Session.create( name=self.ids.session_name.text, date=datetime.now() ) self.ids.session_list.adapter.data.append(session) except IntegrityError: toast('Session already created')
def tap_on_file_in_filemanager(self, path_to_file): self.window_file_manager.dismiss() self.window_file_manager_open = False path_to_file_folder, name_file = os.path.split(path_to_file) self.write_last_path_manager(path_to_file_folder, path_to_file) if os.path.splitext(name_file)[1] not in self.POSSIBLE_FILES: toast(self.message_about_files_mismatch[self.flag_attach]) else: if self.flag_attach == 'FILE': self.attach_file.append(path_to_file) self.add_preview_attached_file(path_to_file) else: self.attach_image.append(path_to_file) self.add_preview_attached_image(path_to_file)
def loadFile(self, filename): try: # open file f = open(filename, "r") lines = list(f) f.close() self.old_text = self.text = "".join(lines) self.setFilename(filename) self.setDirty(False) toast("Loaded : " + self.parentTap.text) except: toast("Failed to load the file : " + os.path.split(filename)[1]) log(traceback.format_exc()) return False return True
def saveFile(self, force = False): if self.dirty or force: if self.filename: try: f = open(self.filename, "w") f.write(self.text) f.close() self.setDirty(False) # check already opened document then close gEditorLayout.closeSameDocument(self) toast("Saved : " + self.parentTap.text) except: toast("Failed to save the file : " + os.path.split(filename)[1]) log(traceback.format_exc()) else: # untitled.document gEditorLayout.setMode(szFileBrowserSaveAs)
def on_new_intent(self, intent): self.on_new_intenting = True sleep(0.25) while self.resuming: sleep(0.1) if intent.getAction() != NfcAdapter.ACTION_TAG_DISCOVERED: toast('unknow action, avoid.') return tag_id = '' for i in intent.getByteArrayExtra(NfcAdapter.EXTRA_ID).tolist(): tag_id += hex(i & 0xff)[2:] if self._action: self._action(tag_id) self.on_new_intenting = False
def attendance_registered(self, tag_id, *args): try: attendance = Member.get(Member.tag_id == tag_id) SessionAttendance.create(session=self.session_id, member=attendance.id) except IntegrityError: toast('{} has already registered'.format(attendance.name)) except DoesNotExist: toast('There is no member with Tag ID {}'.format(tag_id)) else: self.ids.attendance_list.adapter.data.append(attendance) toast('{} successfully registered'.format(attendance.name))
def check_fields_login_password(self): login, password, group_id = self.get_fields_login_password() if login == '' or login.isspace(): toast(self.translation._('Field Login empty!')) return if password == '' or password.isspace(): toast(self.translation._('Field Password empty!')) return if not group_id.isdigit(): toast(self.translation._('ID group is didgest!')) return self.screen.ids.load_screen.remove_widget(self.password_form) self.screen.ids.load_screen.ids.spinner.active = True self.save_login_password(login, password, group_id)
def register(self): if not self.ids.tag_id.text: toast('You can\'t register without a RFID tag') return if not self.ids.member_name.text: toast('Enter member name') return try: Member( tag_id=self.ids.tag_id.text, name=self.ids.member_name.text ).save() except IntegrityError: toast('Member is already registered') else: toast('{} successfully registered'.format( self.ids.member_name.text )) self.clean_widgets() self.manager.current = 'list_members'
def run(self, payInfo): alipay = PayTask(context) result = alipay.pay(payInfo, True) try: result = dict([v.split('=') for v in result.replace('{', '').replace('}', '').split(';')]) except: result = {} resultStatus = result.get('resultStatus') if resultStatus == '9000': toast('支付成功') elif resultStatus == '8000': toast('支付结果确认中') else: toast('支付失败') return result
def import_(self, directory_name): import_dir = join(self.export_base_dir, directory_name) if not (exists(join(import_dir, 'sessions.csv')) and exists(join(import_dir, 'members.csv'))): toast('Invalid backup') return try: with database_proxy.atomic(): load_csv(Session, join(import_dir, 'sessions.csv'), [ Session.id, Session.name, Session.date ]) load_csv(Member, join(import_dir, 'members.csv')) for session in glob(join(import_dir, 'session_*.csv')): load_csv(SessionAttendance, join(import_dir, session)) except IntegrityError: toast('Data already imported, canceling') else: toast('Data Successfully imported')
def decrement_request_fail(self, day, rtype, req, result): toast('Failed to Upload Data for Day: '+ str( day.parent.day_number), True) day.toggle_button.button_type = rtype self.save_data()
def no_rage_request_fail(self, req, result): self.days_of_tranq = -1 toast('Failed to Access Server', True)
def new_board(self, sgf_model=None, collection_model=None, from_file='', mode='Play', gridsize=19, handicap=0, goto=True): toast('Loading sgf', False) load_from_file = False t1 = time() # Get a collection and collectionsgf to contain and represent the board filen = from_file if sgf_model is not None: sgf = sgf_model if sgf.filename: filen = sgf.filename load_from_file = True elif collection_model is not None: sgf = Sgf() sgf.save() collectionsgf = CollectionSgf(collection=collection_model, sgf=sgf) collectionsgf.save() load_from_file = False if from_file != '': load_from_file = True filen = from_file sgf.filename = filen else: collection = get_default_collection() print 'default collection is', collection sgf = Sgf() sgf.save() print 'made sgf' collectionsgf = CollectionSgf(collection=collection, sgf=sgf) collectionsgf.save() print 'made collectionsgf' load_from_file = False if from_file != '': load_from_file = True filen = from_file sgf.filename = filen t2 = time() print 't2 - t1 is...', t2-t1 if filen == '': sgf.auto_filename() load_from_file = False t3 = time() # Work out what screen name is free to put it in i = 1 while True: if not self.has_screen('Board %d' % i): name = 'Board %d' % i break i += 1 s = Screen(name=name) self.add_widget(s) if goto: self.current = name t4 = time() if self.view_mode[:6] == 'tablet': pbv = TabletBoardView(sgf_model=sgf) else: pbv = PhoneBoardView(sgf_model=sgf) pbv.board.sgf_model = sgf # if platform() == 'android': # #set_board_height(pbv.boardcontainer) # pbv.boardcontainer.set_board_height() if sgf.gridsize: gridsize = sgf.gridsize pbv.board.gridsize = gridsize t5 = time() print ' LOAD FROM FILE!?' if load_from_file: print 'YES' print 'Trying to load from', filen try: pbv.board.load_sgf_from_file('',[filen]) except: print 'Exception occurred, making popup' popup = Popup(content=Label(text= ('Unable to open SGF. Please check' 'the file exists and is a valid SGF.'), title='Error opening file'), size_hint=(0.85, 0.4), title='Error') print 'popup made' popup.open() #self.close_board(name) return False pbv.board.reset_gridsize(gridsize) pbv.board.add_handicap_stones(handicap) pbv.board.time_start() s.add_widget(pbv) pbv.screenname = name pbv.managedby = self pbv.spinner.text = mode pbv.board.touchoffset = self.touchoffset pbv.board.coordinates = self.coordinates pbv.board.board_path = boardname_to_filepath(self.boardtype) pbv.board.display_markers = self.display_markers pbv.board.cache = App.get_running_app().cache pbv.board.get_game_info() self.boards.append(name) if self.view_mode[:6] == 'tablet': 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' t6 = time() print 'timings are' print t6-t1, t6-t5, t5-t4, t4-t3, t3-t2, t2-t1 self.refresh_open_games() self.collectionindex_to_refresh = True if collection_model is not None: if collection_model.name not in self.collections_to_refresh: self.collections_to_refresh.append(collection_model.name) pbv.board.save_sgf() return pbv
def on_press(text_button): # TODO: добавить группу в словарь groups.ini. field.dismiss() toast(str(text_button))
def on_enter(self, *args, **kwargs): super(NewMember, self).on_enter(*args, **kwargs) toast('Put RFID tag near to phone', True) Window.bind(on_keyboard=self.on_key_down) nfc_instance.register_action(self.update_tag_id)
def unschedule(error=False): if error: toast(self.translation._('Данные не получены')) Clock.unschedule(wait_result) self.load_dialog.dismiss()
def download_complete(self, result): self.screen.ids.action_bar.right_action_items = [] if result == 'Done': toast(self.translation._('Загружено')) else: toast(self.translation._('Ошибка загрузки'))
def _toast(self, text, length_long=False): if self.toasty: toast.toast(text, length_long)
def unschedule(): Clock.unschedule(self.show_result_sending_posts) self.result_sending_post = None toast(message) self.clear_box_for_attach(remove_all=True)
def on_enter(self, *args, **kwargs): super(ListAttendance, self).on_enter(*args, **kwargs) toast('Put RFID tag near to phone', True)