Esempio n. 1
0
    def update_data(self, load_saved_dvh_data=False):
        wait = wx.BusyCursor()
        tables = ['Plans', 'Rxs', 'Beams']
        if hasattr(self.dvh, 'study_instance_uid'):
            if not load_saved_dvh_data:
                condition_str = "study_instance_uid in ('%s')" % "','".join(
                    self.dvh.study_instance_uid)
                self.data = {
                    key: QuerySQL(key, condition_str)
                    for key in tables
                }
        else:
            self.data = {key: None for key in tables}
        del wait

        if hasattr(self.dvh, 'study_instance_uid'):
            wait = wx.BusyCursor()
            self.stats_data = StatsData(self.dvh, self.data)
            self.regression.stats_data = self.stats_data
            self.control_chart.stats_data = self.stats_data
            try:
                self.regression.update_combo_box_choices()
            except ValueError:
                # TODO: Print error in GUI
                pass
            self.control_chart.update_combo_box_y_choices()
            del wait
    def close_all_instruments(self):
        wait = wx.BusyCursor()
        msg = "Closing all remote connections to instruments"
        busyDlg = wx.BusyInfo(msg, parent=self)

        try:
            print("Closing all possible remote connections to instruments:")
            self.tab_analyzer.da.close_instruments()
            print(
                "\tremote connection to instruments used in distortion analyzer are closed."
            )
            self.tab_multimeter.dmm.close_instruments()
            print(
                "\tremote connection to instruments used in multimeter are closed."
            )
        except ValueError as e:
            error = str(e)
            print(error)
            if error.split()[0] == "VI_ERROR_CONN_LOST":
                print(
                    "[ERROR] Connection was lost before closing remote connection."
                )
                pass
            else:
                raise

        busyDlg = None
        del wait
Esempio n. 3
0
    def handle(self, dndSource, dndContext):  #@UnusedVariable
        bc = wx.BusyCursor()

        try:
            return self._doHandle(dndSource, dndContext)
        finally:
            del bc
Esempio n. 4
0
    def doUpload(self, event):
        busy = wx.BusyCursor()

        self.uploadStatus.SetValue(_("Starting Upload..."))
        resultText = u''

        url = self.fixUrl()
        try:
            response = PostEventCrossMgr(url)
        except Exception as e:
            response = {'errors': [unicode(e)], 'warnings': []}

        if response.get('errors', None) or response.get('warnings', None):
            resultText = u'\n'.join(u'RaceDB{}: {}'.format(_('Error'), e)
                                    for e in response.get('errors', []))
            if resultText:
                resultText += u'\n\n'
            resultText += u'\n'.join(u'RaceDB{}: {}'.format(_('Warning'), w)
                                     for w in response.get('warnings', []))

        if not response.get('errors', None):
            if resultText:
                resultText += u'\n\n'
            if response.get('warnings', None):
                resultText += _('Otherwise, Upload Successful.')
            else:
                resultText += _('Upload Successful.')

        self.uploadStatus.SetValue(resultText)
Esempio n. 5
0
    def openSeries(self, fileName):
        wait = wx.BusyCursor()

        if not fileName:
            return
        try:
            with open(fileName, 'rb') as fp:
                SeriesModel.model = pickle.load(fp)
        except IOError:
            Utils.MessageOK(self,
                            'Cannot Open File "{}".'.format(fileName),
                            'Cannot Open File',
                            iconMask=wx.ICON_ERROR)
            return

        SeriesModel.model.postReadFix()
        self.fileName = fileName
        self.updateRecentFiles()
        SeriesModel.model.setChanged(False)
        self.readResetAll()
        try:
            self.refreshAll()
        except Exception as e:
            Utils.MessageOK(self,
                            'Error:\n\n"{}".'.format(e),
                            'Error',
                            iconMask=wx.ICON_ERROR)
        self.showPageName('Races')
Esempio n. 6
0
    def UpdateCur(self, busy):
        self.is_busy = busy
        if self.cur_inside and self.is_busy:
            self.busy_cur = wx.BusyCursor()
            return

        self.busy_cur = None
Esempio n. 7
0
 def OnUploadConSeries(self, event):  # MainConSeriesFrame
     if self.Seriesname is None or len(self.Seriesname) == 0:
         wx.MessageBox("You must supply a convention series name to upload")
         return
     wait = wx.BusyCursor()
     self.UploadConSeries()
     del wait  # End the wait cursor
Esempio n. 8
0
    def Go(self, ID=False):

        busy = wx.BusyCursor()

        self.listbox.RefreshList()

        del busy
Esempio n. 9
0
    def runPreviousBdayTreas(self, event):

        dlg = wx.MessageDialog(
            self,
            "Run Treasury Best Ex Report for previous business day?",
            style=wx.DD_DEFAULT_STYLE
            #| wx.DD_DIR_MUST_EXIST
            #| wx.DD_CHANGE_DIR
        )

        if dlg.ShowModal() == wx.ID_OK:

            i = 0
            while i < 1:
                wait = wx.BusyCursor()

                date = creation_date(MTG_BLP)
                year = creation_year(MTG_BLP)
                month = creation_month(MTG_BLP)
                bloomy = TSY_BLP
                save = os.path.join(BLOOMBERG_REPORT_PATH['main'],
                                    'Best Ex Treasuries', year, month + "\\")
                treas = treasMgr(date, bloomy, save)
                treas.save()
                i = 1

                wx.MessageBox('Completed', 'Invalid directory',
                              wx.OK | wx.ICON_EXCLAMATION)
Esempio n. 10
0
    def saveAsExcel(self, event):
        fname_excel = self.getOutputExcelName()
        if os.path.isfile(fname_excel):
            if not Utils.MessageOKCancel(
                    self,
                    u'"{}"\n\n{}'.format(fname_excel,
                                         _('File exists.  Replace?')),
                    _('Output Excel File Exists'),
            ):
                return

        try:
            StageRaceGCToExcel(fname_excel, Model.model)
        except Exception as e:
            Utils.MessageOK(
                self,
                u'{}: "{}"\n\n{}\n\n"{}"'.format(
                    _("Write Failed"), e,
                    _("If you have this file open, close it and try again."),
                    fname_excel),
                _("Excel Write Failed."),
                iconMask=wx.ICON_ERROR,
            )
            return

        wait = wx.BusyCursor()
        Utils.LaunchApplication(fname_excel)
Esempio n. 11
0
    def SaveMedia(self, ID=False):

        busy = wx.BusyCursor()

        listboxid = self.listbox.GetSelection()

        mediaid = self.listbox.htmllist[listboxid][0]
        filename = self.listbox.htmllist[listboxid][3]

        action = "SELECT Content FROM media WHERE ID = " + str(mediaid)
        results = db.SendSQL(action, self.localsettings.dbconnection)

        output = base64.decodestring(str(results[0][0]))

        if filename.__contains__("."):

            fileextension = filename.split(".")[-1]

        else:

            fileextension = ""

        targetfile = wx.SaveFileSelector(fileextension.upper(), fileextension,
                                         filename)

        out = open(targetfile, "wb")
        out.write(output)
        out.close()

        del busy
Esempio n. 12
0
 def OnSettings(self, event):
     event.GetId()
     cursor = wx.BusyCursor()
     dlg = Settings.ScSettings(self)
     dlg.CenterOnParent()
     dlg.ShowModal()
     del cursor
Esempio n. 13
0
    def DoItemExpanding(self, item):
        """Handle when an item is expanding to display the folder contents
        @param item: TreeItem

        """
        cursor = wx.BusyCursor()  # can take a few seconds on big directories

        d = None
        try:
            d = self.GetPyData(item)
        except wx.PyAssertionError:
            logger.debug("[FileBrowser][err] FileBrowser.DoItemExpanding")
            return

        if d and os.path.exists(d) and os.access(d, os.R_OK):
            contents = FileBrowser.GetDirContents(d)
            t1 = time.time()
            with Freezer(self) as _tmp:
                self.AppendFileNodes(item, contents)
                self.SortChildren(item)
            logger.info("Tree expand time: %f" % (time.time() - t1))

#             if not self._monitor.AddDirectory(d):
#                 self.SetItemImage(item, self._mime.IMG_NO_ACCESS)
#                 return

# Update tree image
        self.SetItemImage(item, self._mime.GetImageIndex(d, True))
        del cursor
Esempio n. 14
0
 def OnGo(self, e):
     if self.labels == ['Tetris']:
         import Tetris
     else:
         wait = wx.BusyCursor()
         rsa.RSA(self.paths, self.files, self.labels)
         del wait
Esempio n. 15
0
	def onSaveGif( self, event ):
		self.playStop()
		fd = wx.FileDialog( self, message='Save Animated Gif', wildcard='*.gif', style=wx.FD_SAVE )
		if fd.ShowModal() == wx.ID_OK:
			work = wx.BusyCursor()
			try:
				command = [
					Utils.getFFMegExe(),
					'-nostats', '-loglevel', '0',	# silence ffmpeg output
					'-y', # (optional) overwrite output file if it exists
					'-f', 'image2pipe',
					'-r', '{}'.format(self.fps), # frames per second
					'-i', '-', # The input comes from a pipe
					'-an', # Tells FFMPEG not to expect any audio
					fd.GetPath(),
				]
				proc = subprocess.Popen( command, stdin=subprocess.PIPE, bufsize=-1 )
				for i, (ts, jpg) in enumerate(self.tsJpg):
					proc.stdin.write( jpg )
				proc.stdin.close()
				proc.wait()
				wx.MessageBox( _('Gif Save Successful'), _('Success') )
			except Exception as e:
				wx.MessageBox( _('Gif Save Failed:\n\n{}').format(e), _('Save Failed') )
		fd.Destroy()
Esempio n. 16
0
	def onSaveMP4( self, event ):
		self.playStop()
		fd = wx.FileDialog( self, message='Save MP4', wildcard='*.mp4', style=wx.FD_SAVE )
		if fd.ShowModal() == wx.ID_OK:
			work = wx.BusyCursor()
			try:
				# ffmpeg -i animated.gif -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" video.mp4
				command = [
					Utils.getFFMegExe(),
					'-nostats', '-loglevel', '0',	# silence ffmpeg output
					'-y', # (optional) overwrite output file if it exists
					'-f', 'image2pipe',
					'-r', '{}'.format(self.fps), # frames per second
					'-i', '-', # The input comes from a pipe
					'-an', # Tells FFMPEG not to expect any audio
					'-movflags', 'faststart',
					'-pix_fmt', 'yuv420p',
					'-vf', 'scale=trunc(iw/2)*2:trunc(ih/2)*2',
					fd.GetPath(),
				]
				proc = subprocess.Popen( command, stdin=subprocess.PIPE, bufsize=-1 )
				for i, (ts, jpg) in enumerate(self.tsJpg):
					proc.stdin.write( jpg )
				proc.stdin.close()
				proc.wait()
				
				wx.MessageBox( _('MP4 Save Successful'), _('Success') )
			except Exception as e:
				wx.MessageBox( _('MP4 Save Failed:\n\n{}').format(e), _('Save Failed') )
		fd.Destroy()
Esempio n. 17
0
    def onWriteButton(self, event):
        if not self.tagWriter:
            Utils.MessageOK(
                self,
                'Reader not connected.\n\nSet reader connection parameters and press "Reset Connection".',
                'Reader Not Connected')
            return

        busy = wx.BusyCursor()
        wx.CallAfter(self.writeOptions)

        self.setWriteSuccess(False)

        writeValue = self.getWriteValue()

        try:
            self.tagWriter.WriteTag('', writeValue)
        except Exception as e:
            Utils.MessageOK(
                self,
                'Write Fails: {}\n\nCheck the reader connection.\n\n{}'.format(
                    e, traceback.format_exc()), 'Write Fails')

        self.setWriteSuccess(True)
        wx.CallLater(50, self.onReadButton, None)
Esempio n. 18
0
 def fetchRecordsToBuffer(self, constraints):
     wait = wx.BusyCursor()
     print("Paso fetchRecords")
     records = self.__dao.fetch_records(constraints, raw_answers=True)
     del wait
     del records[0]
     return records
Esempio n. 19
0
    def __init__(self, notebook, localsettings):

        busy = wx.BusyCursor()

        self.localsettings = localsettings

        self.pagetitle = self.GetLabel("mailshotpagetitle")

        self.pagetitle = miscmethods.GetPageTitle(notebook, self.pagetitle)

        wx.Panel.__init__(self, notebook)

        topsizer = wx.BoxSizer(wx.VERTICAL)

        mainnotebook = wx.Notebook(self)

        self.vaccinationspanel = VaccinationsPanel(mainnotebook,
                                                   self.localsettings)

        mainnotebook.AddPage(self.vaccinationspanel,
                             self.GetLabel("animalvaccinationslabel"),
                             select=True)

        topsizer.Add(mainnotebook, 1, wx.EXPAND)

        self.SetSizer(topsizer)

        del busy
Esempio n. 20
0
 def OnItemExpanding(self, event):
     """Add children to the item."""
     busy = wx.BusyCursor()
     item = event.GetItem()
     if self.IsExpanded(item):
         return
     self.addChildren(item)
    def push(self, command, silent=False):
        """Send command to the interpreter for execution."""
        if not silent:
            self.write(os.linesep)
        busy = wx.BusyCursor()
        self.waiting = True

        # Execute the code.
        # fixme: Need to handle the case when a line doesn't represent a full
        #        line of code (like the more part of the old interpreter)
        ip_output, self.more = self.ip_readline.push_text(command)

        if isinstance(ip_output, dict):
            self.write(''.join(ip_output['exception_value']))
            self.waiting = False
            return

        if not hasattr(ip_output, 'result_dict'):
            # No command was executed
            self.waiting = False
            return

        print ip_output.result_dict  # dbg

        # If there was any output from the ipython, write out an output prompt
        # and the output results pretty printed to the window.
        self.handle_output(ip_output)

        self.waiting = False
        del busy

        if not silent:
            self.prompt(ip_output.prompt_num)
Esempio n. 22
0
    def onAutoThreshold(self, evt):

        with wx.BusyCursor():
            self._Threshold = self.GetMicroView().GetROIStats().GetThreshold()

        if self._Threshold is None:

            dlg = wx.MessageDialog(
                self._Dialog,
                'Volume of Interest is not defined.  Please select a VOI before continuing.',
                'Error', wx.OK | wx.ICON_ERROR)
            dlg.ShowModal()
            dlg.Destroy()

            return -1

        state = self._app_states[self._current_image_index]
        state.threshold = "%0.4f" % self._Threshold
        self.gui.m_textCtrlThreshold.SetValue(state.threshold)

        # This next bit of code shouldn't be here, because it exposes the
        # implementation of MicroView's window/level code too much
        table = component.getUtility(ICurrentOrthoView).GetLookupTable()
        r = table.GetRange()
        level = (r[1] + r[0]) / 2.0
        delta = self._Threshold - level
        r = (r[0] + delta, r[1] + delta)
        table.SetRange(r[0], r[1])

        self.updateRunButtonState()

        return self._Threshold
Esempio n. 23
0
 def run_server(self, event):
     busy = wx.BusyCursor()
     self.server.run()
     notification = wx.adv.NotificationMessage(
         "dalYinski server", message="Opening browser").Show()
     self.server.open_browser()
     del busy
Esempio n. 24
0
    def Generate(self, event=None):
        dlg = genImageDialog.GenImageDialog(self.mainWind, mode=self.mode)
        ret = dlg.ShowModal()

        bCurr = wx.BusyCursor()

        if ret == wx.ID_OK:
            mdh = MetaDataHandler.NestedClassMDHandler()
            mdh['Rendering.Method'] = self.name
            if 'imageID' in self.pipeline.mdh.getEntryNames():
                mdh['Rendering.SourceImageID'] = self.pipeline.mdh['imageID']
            mdh['Rendering.SourceFilename'] = self.pipeline.filename
            
            for cb in renderMetadataProviders:
                cb(mdh)            
            
            pixelSize = dlg.getPixelSize()

            imb = self._getImBounds()

            im = self.genIm(dlg, imb, mdh)
            img = GeneratedImage(im,imb, pixelSize, 0, ['Image'] , mdh = mdh)
            imf = ViewIm3D(img, mode='visGUI', title='Generated %s - %3.1fnm bins' % (self.name, pixelSize), glCanvas=self.visFr.glCanvas, parent=self.mainWind)
            #imf = imageView.ImageViewFrame(self.visFr,img, self.visFr.glCanvas)
            #imageView.MultiChannelImageViewFrame(self.visFr, self.visFr.glCanvas, img, title='Generated %s - %3.1fnm bins' % (self.name, pixelSize))
            #self.visFr.generatedImages.append(imf)
            #imf.Show()

            self.visFr.RefreshView()

        dlg.Destroy()
        return imf
Esempio n. 25
0
    def ok(self, event):
        logger.debug('OK clicked')
        self.bc = wx.BusyCursor()
        self.choose.Enable(False)
        self.button.Enable(False)

        chosen = self.choose.GetString(self.choose.GetSelection())
        exif = {}
        for lens in self.config['lenses']:
            if lens['key'] == chosen:
                exif = lens['exif']
                break
        exifcommand = [
            f'-{key}={value}'.encode('ascii') for key, value in exif.items()
        ]
        logger.debug(f'PATH={os.environ["PATH"]}')
        logger.debug('opening exiftool')
        with exiftool.ExifTool(self.config['exiftool']) as et:
            logger.debug('enumerating files')
            for i, fn in enumerate(self.files):
                logger.debug(f'working on {fn}')
                self.txt.SetLabel(f'Tagging {os.path.basename(fn)}')
                r = et.execute(*(exifcommand + [exiftool.fsencode(fn)]))
                self.progress.SetValue(i)

        logger.debug('done')
        self.txt.SetLabel('All done, quit now')
        self.Bind(wx.EVT_BUTTON, self.quit, self.button)
        self.button.SetLabel('Quit')
        self.button.Enable(True)
        del self.bc
Esempio n. 26
0
    def DoItemExpanding(self, item):
        """Handle when an item is expanding to display the folder contents
        @param item: TreeItem

        """
        busy = wx.BusyCursor()  # can take a few seconds

        d = None
        try:
            d = self.GetPyData(item)
        except wx.PyAssertionError:
            util.Log("[FileBrowser][err] FileBrowser2.DoItemExpanding")
            return

        if d and os.path.exists(d) and os.access(d, os.R_OK):
            contents = FileBrowser2.GetDirContents(d)
            t1 = time.time()
            with eclib.Freezer(self) as _tmp:
                self.AppendFileNodes(item, self.FilterFileList(contents))
                self.SortChildren(item)
            util.Log("[FileBrowser][info] Tree expand time: %f" %
                     (time.time() - t1))

            if not self._monitor.AddDirectory(d):
                self.SetItemImage(item, self._mime.IMG_NO_ACCESS)
                return

        # Update tree image
        self.SetItemImage(item, self._mime.GetImageIndex(d, True))
Esempio n. 27
0
	def OnSearch(self, event):
		txt = self.birthplace.GetValue()
		if txt == '':
 			dlg = wx.MessageDialog(self, mtexts.txts['PlaceEmpty'], '', wx.OK|wx.ICON_EXCLAMATION)
			dlg.ShowModal()
			dlg.Destroy()
			return

		if len(txt) < 3:
 			dlg = wx.MessageDialog(self, mtexts.txts['TooFewChars'], '', wx.OK|wx.ICON_EXCLAMATION)
			dlg.ShowModal()
			dlg.Destroy()
			return

		wait = wx.BusyCursor()
		maxnum = self.sizeslider.GetValue()
		geo = geonames.Geonames(self.birthplace.GetValue().encode("utf-8"), maxnum, self.langid)
		if (geo.get_location_info()):
			if len(geo.li) == 1:
				self.fillFields(geo.li[0])
			else:
				#popup list
				pldlg = placeslistdlg.PlacesListDlg(self, geo.li)
				val = pldlg.ShowModal()
				if val == wx.ID_OK:
					if pldlg.li.currentItem != -1:
						self.fillFields(geo.li[pldlg.li.currentItem])

				pldlg.Destroy()

		else:
 			dlg = wx.MessageDialog(self, mtexts.txts['NotFound'], '', wx.OK|wx.ICON_EXCLAMATION)
			dlg.ShowModal()
Esempio n. 28
0
    def on_predict(self, evt):
        if False:
            self.classifier_output.AppendText("Chosen model:")
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText(
                self.classifier_ch.GetString(
                    self.classifier_ch.GetSelection()))
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText("Chosen features:")
            self.classifier_output.AppendText("\n")
            for feature in self.attr_check_list.get_selected():
                self.classifier_output.AppendText(feature)
                self.classifier_output.AppendText(" ")
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText("Chosen test method")
            self.classifier_output.AppendText("\n")
            for rb in self.rad_btns:
                if rb.GetValue():
                    self.classifier_output.AppendText(rb.GetLabel())
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText("Chosen target:")
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText(self.target_choice.GetValue())
            self.classifier_output.AppendText("\n")
            self.classifier_output.AppendText("\n")

        if self.target_choice.GetValue() == "None":
            dlg = wx.MessageDialog(self, 'Target not selected',
                                   "Evaluate Target",
                                   wx.OK | wx.ICON_INFORMATION)
            dlg.ShowModal()
            dlg.Destroy()

        elif self.classifier_ch.GetSelection() == 1:
            self.classifier_output.AppendText("Starting algorithm ...\n")

            busy = wx.BusyCursor()

            features_list = self.attr_check_list.get_selected()
            target = self.target_choice.GetValue()
            output = self.workset_controller.random_forest(
                features_list, target, self.percentage_split_box.GetValue())

            del busy

            self.classifier_output.AppendText(str(output))
            self.classifier_output.AppendText("\n")

        elif self.classifier_ch.GetSelection() == 0:
            self.classifier_output.AppendText("Starting algorithm ...\n")
            features_list = self.attr_check_list.get_selected()
            target = self.target_choice.GetValue()
            output = self.workset_controller.mlogit(
                features_list, target, self.percentage_split_box.GetValue())
            self.classifier_output.AppendText(str(output))
            self.classifier_output.AppendText("\n")
Esempio n. 29
0
 def OpenInWebBrowser(self, event=None):
     self._busy = wx.BusyCursor()
     try:
         if self._rss_reader:
             self._rss_reader.process_current_item(
                 action=self.OpenItemInWebBrowser)
     finally:
         self._busy = None
Esempio n. 30
0
 def change_window(self):
     wait = wx.BusyCursor()
     self.save_map()
     self.update_window()
     self.load_map()
     self.load_aspect()
     self.refresh_canvas()
     del wait