def button_press(self, lab): #get the button pressed label = lab.GetEventObject().GetLabel() #get the expression to compute computation = self.textbox.GetValue() #Event handling for the computation if label == '=': if not computation: return #if blank expression do nothing #try block for exception handling due to possibility of incorrect UI usage try: result = eval(computation) except SyntaxError as error: wx.LogError( 'Invalid Syntax. Please check your input and try again.'. format(computation)) return except NameError as error: wx.LogError( 'An error occured. Please check your input and try again.'. format(computation)) return except ZeroDivisionError as error: wx.LogError( 'Cannot divide expression by zero. Please check your input and try again' .format(computation)) return self.textbox.SetValue(str(result)) elif label == 'C': self.textbox.SetValue('') #clear values from the display else: self.textbox.SetValue( computation + label) #add the button value to the expression
def OnButtonOneClick(self, evt): openFileDialog = wx.FileDialog(self.Frame, "Open Image file", "", "", "JPG files (*.jpg)|*.jpg", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed idea... # proceed loading the file chosen by the user # this can be done with e.g. wxPython input streams: input_stream = wx.FileInputStream(openFileDialog.GetPath()) if not input_stream.IsOk(): wx.LogError("Cannot open file '%s'." % openFileDialog.GetPath()) return
def OnOpen(self, event): # if self.currentData!=[]: # print("has data!") # return # otherwise ask the user what new file to open with wx.FileDialog(self, "Open .CSV file", wildcard="CSV files (*.csv)|*.csv", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind # Proceed loading the file chosen by the user pathname = fileDialog.GetPath() prefix = pathname[:-4] suffix = ['.csv', '.tiff'] rows = [] try: with open(prefix + suffix[0], 'r') as file: reader = csv.reader(file, delimiter=" ") for r in reader: row = [] for i in r: row.append(np.uint16(i)) rows.append(np.array(row)) except IOError: wx.LogError("Cannot open file ") data = np.array(rows) self.stream = False self.coordsSaved = [] if len(self.savedCrops) > 0: for _ in range(self.index): self.index -= 1 eraseLine(self, self.index) self.savedCrops = [] self.pointTemps = [] self.currentData = np.array(data) self.currentImage = getImage(data) #img = cv2.imread(prefix+suffix[1], cv2.IMREAD_COLOR) img = cv2.cvtColor(self.currentImage, cv2.COLOR_RGB2BGR) width, height = 640, 480 image = wx.Image(width, height) image.SetData(img) self.videobmp.SetBitmap(wx.Bitmap(image)) self.Refresh()
def load_settings(self, event): """ Publisher function that loads a dictionary of settings and updates the GUI to show these. Source: wxpython FileDialog docs """ self.settings = dict() with wx.FileDialog(self, "Open settings file", wildcard="json files (*.json)|*.json", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind # Proceed loading the file chosen by the user pathname = fileDialog.GetPath() try: self.settings = read_settings(pathname) except IOError: wx.LogError("Cannot open file '%s'." % pathname) logger.error("Cannot open file. ", exc_info=True) self.currentDirectory = self.settings['fp'] self.dir_txt.SetValue(self.settings['fp']) self.biom_file = self.settings['biom_file'] self.biom_txt.SetValue('') self.network_path = self.settings['network'] if self.settings['biom_file'] is not None: self.checkfiles('biom') self.biom_txt.SetValue('\n'.join(self.settings['biom_file'])) if self.settings['otu_table'] is not None: self.count_file = self.settings['otu_table'] self.checkfiles('count') self.count_txt.SetValue('\n'.join(self.settings['otu_table'])) if self.settings['tax_table'] is not None: self.tax_file = self.settings['tax_table'] self.checkfiles('tax') self.tax_txt.SetValue('\n'.join(self.settings['tax_table'])) if self.settings['split'] is not None: self.split = self.settings['split'] if self.settings['sample_data'] is not None: self.sample_file = self.settings['sample_data'] self.checkfiles('meta') self.meta_txt.SetValue('\n'.join(self.settings['sample_data'])) if self.settings['network'] is not None: self.net_choice.SetSelection(1) else: self.net_choice.SetSelection(0) pub.sendMessage('load_settings', msg=self.settings) self.send_settings()
def on_changing(self, event): # Trigger page validation before leaving if BULK_ADDING: event.Skip() return index = self.GetSelection() try: if index != -1: self.GetPage(index).validate() except Exception as ex: wx.LogError("Error on page: " + ex.message) event.Veto() return event.Skip()
def OnOpen(self, event): with wx.FileDialog(self, "Open D2S file", wildcard="D2S files |*.d2s", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # load file and run pathname = fileDialog.GetPath() try: open_and_edit(pathname) wx.MessageBox(f"D2S file {os.path.basename(pathname)} edited and saved.", "Result", wx.OK | wx.ICON_INFORMATION) except Exception as e: wx.LogError(f"Error: {e}")
def __open_rom_dialog(self, evt): path = self.view.show_file_dialog() if path: try: with open(path, 'rb') as file: if path.endswith(".nes") or path.endswith(".NES"): self.emu.set_rom(ROM(file, True)) elif path.endswith(".dat") or path.endswith(".DAT"): self.emu.set_rom(ROM(file, False)) self.__refresh_rom() except IOError: wx.LogError("Cannot open file: '%s'." % path) self.__set_code_button(self.emu.has_rom())
def OnDoPrint(self, event): pdd = wx.PrintDialogData() pdd.SetPrintData(self.printData) printer = wx.Printer(pdd) printout = self.createSTCPrintout() if not printer.Print(self.parentFrame, printout): wx.LogError(_('An error occured while printing.')) else: self.printData = wx.PrintData( printer.GetPrintDialogData().GetPrintData()) printout.Destroy() self.EndModal(wx.OK)
def connectToRobot(self, host, port=7799): if self.robotSock is not None: try: self.robotSock.close() except Exception: pass try: self.robotSock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self.robotSock.connect((host,port)) except Exception as e: self.robotSock = None wx.LogError('Failed to connect to robot: ' + str(e))
def OnSaveAs( self, event ): with wx.FileDialog(self, "Save GL Shader Graph file", wildcard="GL Shader Graph files (*.glsg)|*.glsg", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind # save the current contents in the file pathname = fileDialog.GetPath() try: with open(pathname, 'wb') as f: pickle.dump(self.graph, f, 0) except IOError: wx.LogError("Cannot save current data in file '%s'." % pathname)
def edit(self, event): ce = self.companion.designer.showCollectionEditor( self.companion.name, self.name, False) growableRows, growableCols = ce.companion.getGrowables() fgsCompn = ce.companion.parentCompanion numRows, numCols = fgsCompn.getNumRowsCols(ce.companion) if not numRows and not numCols: wx.LogError(_('Rows and Cols may not both be 0')) return if not numRows or not numCols: numItems = len( self.companion.designer.showCollectionEditor( self.companion.name, 'Items', False).companion.textConstrLst) else: numItems = -1 rows, cols = [], [] if not numRows: numRows = numItems / float(numCols) numRows = int(numRows) + (numRows > int(numRows)) for row in range(numRows): rows.append(row in growableRows) if not numCols: numCols = numItems / float(numRows) numCols = int(numCols) + (numCols > int(numCols)) for col in range(numCols): cols.append(col in growableCols) dlg = FlexGridGrowablesDlg(self.parent, rows, cols) try: res = dlg.ShowModal() if res == wx.ID_CANCEL: return if res == wx.ID_YES: ce.show() return rows = dlg.rows cols = dlg.cols finally: dlg.Destroy() ce.companion.setGrowables(rows, cols) ce.companion.recreateSizers()
def OnFileOpen(self, e): with wx.FileDialog(self, "Open Test file", wildcard="Text Files (*.txt)|*.txt", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind # Proceed loading the file chosen by the user filename = fileDialog.GetPath() try: file_content = _get_filecontent(filename) self.doLoadFile(file_content) except IOError: wx.LogError("Cannot open file '%s'." % newfile)
def add_bookmark(self): if self.picture_list is not None: path = self.picture_list.path name = wx.GetTextFromUser(_("Select the name for the bookmark"), _("Add Bookmark"), path) if name != "": try: outfile = open(common.bookmarks_file, 'a') outfile.write(name + '||' + path + '\n') outfile.close() except: wx.LogError(_('Error adding bookmark!')) else: self.load_bookmarks()
def OnToggleReadOnly(self, event): model = self.getModel() if model and model.transport and model.transport.stdAttrs.has_key( 'read-only'): model.transport.updateStdAttrs() ro = model.transport.stdAttrs['read-only'] model.transport.setStdAttr('read-only', not ro) if model.views.has_key('Source'): model.views['Source'].updateFromAttrs() self.editor.updateModuleState(model) else: wx.LogError(_('Read-only not supported on this transport'))
def OnSave(self, e): with wx.FileDialog(self, "Save file", "*.*", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return pathname = fileDialog.GetPath() try: with open(pathname, 'w') as file: self.doSaveData(file) except IOError: wx.LogError("Nu a fost salvata fila '%s'." % pathname)
def select_train(self, event): opendir=wx.DirDialog(self,'Select train directory','',style=wx.DD_DEFAULT_STYLE) try: if opendir.ShowModal()==wx.ID_CANCEL: return path=opendir.GetPath() except Exception: wx.LogError('Failed to select directory') raise finally: opendir.Destroy() if len(path)>0:#train path self.train_path=path self.textrain.SetValue(path)
def getValue(self): if self.editorCtrl: try: value = self.editorCtrl.getValue( ) # wx.GetApp().gns.eval(self.editorCtrl.getValue()) except Exception, mess: wx.LogError('Invalid value: %s' % str(mess)) raise if value == "None": value = "NoImage" # self.value = None # return "NoImage" self.value = wx.GetApp().gns.eval(value + '()') return value
def OnGotoLine(self, event): dlg = wx.TextEntryDialog(self, _('Enter line number:'), _('Goto line'), '') try: if dlg.ShowModal() == wx.ID_OK: if dlg.GetValue(): try: lineNo = int(dlg.GetValue()) - 1 except ValueError: wx.LogError(_('Integer line number required')) else: self.GotoLine(lineNo) finally: dlg.Destroy()
def saveBtnClicked(event): with wx.FileDialog(None, "Save file", wildcard="csv files (*.csv)|*.csv", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return path = fileDialog.GetPath() # ダイヤログからpathを取得 try: filename = text.GetValue() # テキストフィールドからpathを取得 with open(filename, encoding='utf-8') as f: lines = f.readlines() # ファイルの全ての行をstrで格納 newline = [] # 処理後の文字列格納用配列の初期化 data = [] # data格納用配列を初期化 # grain sizeラジオボタンにチェックが入っている場合の動作 if radio_grain.GetValue() == True: headertext = ['grain size', 'area fraction'] data.append(headertext) for i in range(8, len(lines) - 5): rline = lines[i].split( sep='; ') # それぞれの行を'; 'で区切りrlineにリスト形式で格納 rline.pop(2) # 改行コードを削除する floatrline = [float(i) for i in rline] data.append(floatrline) # csvファイルに書き込み with open(path, 'w', encoding='utf-8', newline='\n') as f: writer = csv.writer(f) writer.writerows(data) elif radio_aspect.GetValue() == True: headertext = ['aspect ratio', 'number fraction'] data.append(headertext) for i in range(6, len(lines) - 5): rline = lines[i].split( sep='; ') # それぞれの行を'; 'で区切りrlineにリスト形式で格納 rline.pop(2) # 改行コードを削除する floatrline = [float(i) for i in rline] data.append(floatrline) # csvファイルに書き込み with open(path, 'w', encoding='utf-8', newline='\n') as f: writer = csv.writer(f) writer.writerows(data) except IOError: wx.LogError("Cannot save current file")
def predecirAfrica(self, event): print("predecir Africa") config_africa = africa.BalloonConfig() config_africa = InferenceConfigAfrica() config_africa.display() DATA_DIR = "./Modelo/tfg_notebook/main/dataset" BALLOON_DIR = DATA_DIR dataset_africa = africa.BalloonDataset() with wx.FileDialog(self, "Selecciona una imagen para predecir su clase", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return pathname = fileDialog.GetPath() try: with open(pathname, 'r') as file: print(pathname) dataset_africa.load_balloon(BALLOON_DIR, "val") dataset_africa.prepare() print("Images: {}\nClasses: {}".format( len(dataset_africa.image_ids), dataset_africa.class_names)) config_africa = InferenceConfigAfrica() with tf.device(DEVICE): model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_AFRICA_DIR, config=config_africa) weights_path = model.find_last() model.load_weights(weights_path, by_name=True) image = skimage.io.imread(pathname) plt.figure(figsize=(12, 10)) skimage.io.imshow(image) plt.show() result = model.detect([image], verbose=1) r = result[0] visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], dataset_africa.class_names, r['scores']) except IOError: wx.LogError("ERROR")
def setChoices(self, event): choiceString = self.choiceTextCtrl.GetValue() choices = [c.strip() for c in choiceString.split(',')] if len(choices) < 2: wx.LogError('Page %s: Cannot use less than 2 choices.' % self.name) else: self.pg.choices = choices self.pg.confusion = np.zeros((len(choices), len(choices))) self.pg.pieMenu.setChoices(choices, refresh=False) if len(choices) == 2: self.pg.pieMenu.setRotation(-np.pi / 2.0) else: self.pg.pieMenu.setRotation(np.pi / len(choices) + np.pi / 2.0) self.pg.setTrained(False)
def saveCap(self): cap = self.src.getEEGSecs(self.getSessionTime(), filter=False) saveDialog = wx.FileDialog(self, message='Save EEG data.', wildcard='Pickle (*.pkl)|*.pkl|All Files|*', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) try: if saveDialog.ShowModal() == wx.ID_CANCEL: return cap.saveFile(saveDialog.GetPath()) except Exception: wx.LogError('Save failed!') raise finally: saveDialog.Destroy()
def action(self, event): """ Replay a count number of time. """ toggle_button = event.GetEventObject() count = settings.CONFIG.getint('DEFAULT', 'Repeat Count') infinite = settings.CONFIG.getboolean('DEFAULT', 'Infinite Playback') if toggle_button.Value: if TMP_PATH is None or not os.path.isfile(TMP_PATH): wx.LogError("No capture loaded") toggle_button.Value = False return with open(TMP_PATH, 'r') as f: capture = f.read() if capture == HEADER: wx.LogError("Empty capture") toggle_button.Value = False return if count == 1 and not infinite: play_thread = Thread() play_thread.daemon = True play_thread = Thread(target=self.play, args=(capture, toggle_button,)) play_thread.start() else: i = 1 while i <= count or infinite: play_thread = Thread() play_thread = Thread(target=self.play, args=(capture, toggle_button,)) play_thread.start() play_thread.join() i += 1 else: play_thread._stop() # Can be deprecated toggle_button.Value = False
def on_export(self, e): # Do a validation of current page first index = self.book.GetSelection() try: if index != -1: self.book.GetPage(index).validate() except Exception as ex: wx.LogError("Error on page: " + ex.message) return # Check for hostname conflicts hostnames = [] for existing in range(self.book.GetPageCount()): hostname = self.book.GetPage( existing).fieldgroup[0]['hostname'].get_value() if hostname in hostnames: wx.LogError("Cannot export, duplicate hostname '%s'" % hostname) return # Ignore multiple None hostnames elif hostname: hostnames.append(hostname) self.book.to_xml()
def ToggleMinMax(self, evt): """ toggle min/max size of logger window send cmd to parent splitter window via pubsub """ if self.__isMinimize: self.__isMinimize = False else: self.__isMinimize = True try: self.GetParent().UpdateSplitPosition( name=self.GetName(), size=self._BtMinimize.GetSize() * 5) except: wx.LogError("Error in calling UpdateSplitPosition in parent", exc_info=True)
def __OpenFile(self, filename): if filename == "": return False if os.path.exists(filename) is False: wx.LogError("The file : {} didn't exists".format(filename)) self.__RemoveFileFromHistory(filename) return False if self.m_bookmarkDocument.LoadObject(filename) is True: self.m_fileHistoryMenu.AddFileToHistory(filename) else: self.__RemoveFileFromHistory(filename) pass self.m_bookmarkDocument.SetBookMarksToList(self.m_listCtrl)
def checkUnsavedChanges(self): model = self.model ctx = model.editor.brm_context for path in ctx.brmctx.paths: uri = 'file://' + os.path.abspath(path) if uri in model.editor.modules: try: model.editor.prepareForCloseModule( model.editor.modules[uri], True, _('Save changes before Refactoring operation')) except Editor.CancelClose: wx.LogError(_('Operation aborted.')) return False return True
def LoadFeatures(self, event): with wx.FileDialog(self, "Open Template file", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind pathname = fileDialog.GetPath() try: with open (pathname, 'rb') as fp: self.FeatureDict = pickle.load(fp) #self.FeatureList.Clear() #for key in self.FeatureDict: # self.FeatureList.Append(key) self.LoadFeatureCtrl() except IOError: wx.LogError("Cannot open file '%s'." % newfile)
def on_open(self,event): #the callback function that create a open file dialog with wx.FileDialog(self, "Open XYZ file", wildcard="XYZ files (*.xyz)|*.xyz", style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind # Proceed loading the file chosen by the user pathname = fileDialog.GetPath() try: with open(pathname, 'rb') as file: the_osa.load_from_file(file) except IOError: wx.LogError("Cannot open file '%s'." % pathname)
def OnExport(self,event): with wx.FileDialog(self, "Save Csv File", wildcard="Output File (*.csv)|*.csv", style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) as fileDialog: if fileDialog.ShowModal() == wx.ID_CANCEL: return # the user changed their mind # save the current contents in the file pathname = fileDialog.GetPath() try: input_path = './db/rcslab.txt' with open(input_path, encoding='utf-8') as f: s = f.read() with open(pathname, 'w', encoding='utf-8') as file: file.write(s) except IOError: wx.LogError("Cannot save current data in file '%s'." % pathname)