def __init__(self, parent_widget = None):
        QDialog.__init__(self, parent_widget)
        self.setupUi(self)
        self.original_variable = None
        self.variable = None
        self.validator = None
        self.callback = None
        def send_to_uc(): self.send_to_urbancanvas()
        def check_data(): self.check_variable(check = 'data')
        def check_syntax(): self.check_variable(check = 'syntax')
        self.connect(self.btnUrbanCanvas, SIGNAL("clicked()"), send_to_uc)
        self.connect(self.btnCheckData, SIGNAL("clicked()"), check_data)
        self.connect(self.btnCheckSyntax, SIGNAL("clicked()"), check_syntax)
        self.connect(self.buttonBox, SIGNAL('rejected()'), self.reject)

        self.frame_name_warning.setVisible(False)
        hide_widget_on_value_change(self.frame_name_warning, self.leVarName)

        self.group_settings.setVisible(False)
        self._toggle_settings()
        self.layout().update()
        qApp.processEvents(QEventLoop.AllEvents)

        # give instant feedback in the information label when settings are changed
        self.connect(self.rbUseBoth, SIGNAL('clicked()'), self._update_variable_info)
        self.connect(self.rbUseIndicator, SIGNAL('clicked()'), self._update_variable_info)
        self.connect(self.rbUseModel, SIGNAL('clicked()'), self._update_variable_info)
        self.connect(self.cboVarType, SIGNAL('currentIndexChanged(int)'),
                     lambda x: self._update_variable_info())
        self.connect(self.pb_change, SIGNAL("clicked()"), self._toggle_settings)
Пример #2
0
 def join(self, processEvents=True):
     """ Wait until the execution finishes.
     """
     while self.poll() is None:
         QThread.currentThread().msleep(50)
         if processEvents and QThread.currentThread() is qApp.thread():
             qApp.processEvents()
Пример #3
0
    def progressBarSet(self, value):
        old = self.__progressBarValue
        self.__progressBarValue = value

        if value > 0:
            if self.__progressState != 1:
                warnings.warn("progressBarSet() called without a "
                              "preceding progressBarInit()",
                              stacklevel=2)
                self.__progressState = 1
                self.processingStateChanged.emit(1)

            usedTime = max(1, time.time() - self.startTime)
            totalTime = (100.0 * usedTime) / float(value)
            remainingTime = max(0, totalTime - usedTime)
            h = int(remainingTime / 3600)
            min = int((remainingTime - h * 3600) / 60)
            sec = int(remainingTime - h * 3600 - min * 60)
            if h > 0:
                text = "%(h)d:%(min)02d:%(sec)02d" % vars()
            else:
                text = "%(min)d:%(sec)02d" % vars()
            self.setWindowTitle(self.captionTitle +
                                " (%(value).2f%% complete, remaining time: %(text)s)" % vars())
        else:
            self.setWindowTitle(self.captionTitle + " (0% complete)")

        self.progressBarValueChanged.emit(value)

        if old != value:
            self.progressBarValueChanged.emit(value)

        qApp.processEvents()
Пример #4
0
    def UpdateOrientation(self, yaw=None):
        ''' Update Orientation '''
        self.bearing = self.selected_features.attribute(config.column_yaw)
        try:
            self.actualPointOrientation.reset()
        except:
            pass

        self.actualPointOrientation = QgsRubberBand(
            self.iface.mapCanvas(), QGis.Line)
        self.actualPointOrientation.setColor(Qt.blue)
        self.actualPointOrientation.setWidth(5)
        self.actualPointOrientation.addPoint(self.actualPointDx)

        # End Point
        CS = self.canvas.mapUnitsPerPixel() * 25
        A1x = self.actualPointDx.x() - CS * math.cos(math.pi / 2)
        A1y = self.actualPointDx.y() + CS * math.sin(math.pi / 2)

        self.actualPointOrientation.addPoint(QgsPoint(A1x, A1y))

        # Vision Angle
        if yaw is not None:
            angle = float(self.bearing + yaw) * math.pi / -180
        else:
            angle = float(self.bearing) * math.pi / -180

        tmpGeom = self.actualPointOrientation.asGeometry()

        self.actualPointOrientation.setToGeometry(self.rotateTool.rotate(
            tmpGeom, self.actualPointDx, angle), self.dumLayer)
        qApp.processEvents()
 def join(self, processEvents=True):
     """ Wait until the execution finishes.
     """
     while self.poll() is None:
         QThread.currentThread().msleep(50)
         if processEvents and QThread.currentThread() is qApp.thread():
             qApp.processEvents()
Пример #6
0
 def on_btnOscilloscope_clicked(self):
     """
     Monitor the light incident on the power meter.
     """
     
     # create the object for the power meter
     if not self.oscilloscope:
         self.oscilloscope = True
         
         self.btnOscilloscope.setStyleSheet("background-color: green")
         
         acqPause = float(self.txtPause.text())
         
         sampleIndex = 0
         sampleTot = 1000
         sample = np.arange(sampleTot)*acqPause/1000
         pwm = pm100d()
         
         power = np.zeros((sampleTot, 1))
         while self.oscilloscope:
             qApp.processEvents()
             p = max(pwm.read()*1000, 0.)
             power[sampleIndex] = p
             sampleIndex = (sampleIndex+1) % sampleTot
             self.lblPower.setText("{:.3}".format(p))
             self.axOscilloscope.plot(sample, power, '.')
             self.plotOscilloscope.draw()
             
             time.sleep(acqPause/1000)
         
     else:
         self.btnOscilloscope.setStyleSheet("")
         self.oscilloscope = False
Пример #7
0
    def ReloadView(self, newId):
        ''' Reaload Image viewer '''
        self.setWindowState(self.windowState() & ~
                            Qt.WindowMinimized | Qt.WindowActive)
        # this will activate the window
        self.activateWindow()
        qApp.processEvents()

        self.selected_features = qgsutils.getToFeature(
            self.layer, newId)

        self.current_image = self.GetImage()

        # Check if image exist
        if os.path.exists(self.current_image) is False:
            qgsutils.showUserAndLogMessage(
                self, u"Information: ", u"It is not in the associated image.",
                QgsMessageBar.INFO)
            self.ChangeUrlViewer(config.DEFAULT_EMPTY)
            self.setPosition()
            return

        # Set RubberBand
        self.setOrientation()
        self.setPosition()

        # Copy file to local server
        self.CopyFile(self.current_image)

        self.ChangeUrlViewer(config.DEFAULT_URL)
        qApp.processEvents()

        return
Пример #8
0
 def safeProcessEvents(self):
     keys = ["widgetShown"]
     vals = [(key, getattr(self, key, None)) for key in keys]
     qApp.processEvents()
     for (key, val) in vals:
         if val != None:
             setattr(self, key, val)
Пример #9
0
    def __init__(self, parent_widget = None):
        QDialog.__init__(self, parent_widget)
        self.setupUi(self)
        self.original_variable = None
        self.variable = None
        self.validator = None
        self.callback = None
        def send_to_uc(): self.send_to_urbancanvas()
        def check_data(): self.check_variable(check = 'data')
        def check_syntax(): self.check_variable(check = 'syntax')
        self.connect(self.btnUrbanCanvas, SIGNAL("clicked()"), send_to_uc)
        self.connect(self.btnCheckData, SIGNAL("clicked()"), check_data)
        self.connect(self.btnCheckSyntax, SIGNAL("clicked()"), check_syntax)
        self.connect(self.buttonBox, SIGNAL('rejected()'), self.reject)

        self.frame_name_warning.setVisible(False)
        hide_widget_on_value_change(self.frame_name_warning, self.leVarName)

        self.group_settings.setVisible(False)
        self._toggle_settings()
        self.layout().update()
        qApp.processEvents(QEventLoop.AllEvents)

        # give instant feedback in the information label when settings are changed
        self.connect(self.rbUseBoth, SIGNAL('clicked()'), self._update_variable_info)
        self.connect(self.rbUseIndicator, SIGNAL('clicked()'), self._update_variable_info)
        self.connect(self.rbUseModel, SIGNAL('clicked()'), self._update_variable_info)
        self.connect(self.cboVarType, SIGNAL('currentIndexChanged(int)'),
                     lambda x: self._update_variable_info())
        self.connect(self.pb_change, SIGNAL("clicked()"), self._toggle_settings)
Пример #10
0
def variable_batch_check(variables, validator_func, variable_key = None,
                         progress_callback = None, cancel_flag = None):
    '''
    Go through a list of variables and runs the validator_func on each of them.
    Variables that does not validate gets the key indicated by 'variable_key' set to the error msg.
    Variables that pass gets the key set to False.
    'variable_key' can also be None, in which case no key is set.

    @param variables list(dict) list of variables in the format specified in variable_table_model
    @param validator_func (function) a function that takes a list of variables (dict)and returns a
    tuple with result of the whole validation and the collected error messages (bool, list(str))
    @return a list of tuples. The tuples contain, for each variable:
        the variable (dict), the result (bool) and the error messages (str).
    '''
    if progress_callback is None:
        progress_callback = lambda x: None
    cancel_flag = cancel_flag or {'value':False}
    res = []
    num_steps = len(variables)
    for step, variable in enumerate(variables):
        qApp.processEvents(QEventLoop.AllEvents) # flush out events so that progress bars update
        if cancel_flag['value']: break
        converted_var = variable_to_validator_format(variable)
        try:
            success, msg = validator_func(variables = [converted_var,])
        except Exception, ex:
            success = False
            msg = ['ERROR while trying to validate %s: %s' %(variable['name'], ex),]
        if success is True:
            variable[variable_key] = False
        else:
            variable[variable_key] = msg
        res.append((variable, success, msg))
        progress_callback(float(step)/float(num_steps))
Пример #11
0
    def CopyFile(self, src):
        ''' Copy Image File in Local Server '''
        qgsutils.showUserAndLogMessage(
            self, u"Information: ", u"Copiar imagem",
            QgsMessageBar.INFO,
            onlyLog=True)

        pattern = "^(?P<photo_id>\d+)[^\d].*jpg$"
        src_dir = src
        dst_dir = self.plugin_path + "\\viewer"

        # Delete images on first time
        for root, dirs, files in os.walk(dst_dir):
            for file in filter(lambda x: re.match(pattern, x), files):
                os.remove(os.path.join(root, file))

        # Copy image in local folder
        # Uncomment for large images if viewer is blank screen
        img = Image.open(src_dir)
        newwidth = 8000
        dst_dir = dst_dir + "\\image.jpg"
        width, height = img.size

        if width > newwidth:
            wpercent = (newwidth / float(img.size[0]))
            hsize = int((float(img.size[1]) * float(wpercent)))
            img = img.resize((newwidth, hsize), Image.ANTIALIAS)
            img.save(dst_dir, optimize=True, quality=95)

        # Comment for large images if viewer is blank screen
        else:
            shutil.copy(src_dir, dst_dir)

        qApp.processEvents()
        return
Пример #12
0
    def progressBarSet(self, value):
        old = self.__progressBarValue
        self.__progressBarValue = value

        if value > 0:
            if self.__progressState != 1:
                warnings.warn(
                    "progressBarSet() called without a "
                    "preceding progressBarInit()",
                    stacklevel=2)
                self.__progressState = 1
                self.processingStateChanged.emit(1)

            usedTime = max(1, time.time() - self.startTime)
            totalTime = (100.0 * usedTime) / float(value)
            remainingTime = max(0, totalTime - usedTime)
            h = int(remainingTime / 3600)
            min = int((remainingTime - h * 3600) / 60)
            sec = int(remainingTime - h * 3600 - min * 60)
            if h > 0:
                text = "%(h)d:%(min)02d:%(sec)02d" % vars()
            else:
                text = "%(min)d:%(sec)02d" % vars()
            self.setWindowTitle(
                self.captionTitle +
                " (%(value).2f%% complete, remaining time: %(text)s)" % vars())
        else:
            self.setWindowTitle(self.captionTitle + " (0% complete)")

        self.progressBarValueChanged.emit(value)

        if old != value:
            self.progressBarValueChanged.emit(value)

        qApp.processEvents()
Пример #13
0
    def optimizeSeparation(self, steps=10, singleStep=False, distances=None):
        # check if we have data and a discrete class
        if not self.graph.haveData or len(
                self.graph.rawData) == 0 or not (self.graph.dataHasClass
                                                 or distances):
            return
        ai = self.graph.attributeNameIndex
        attrIndices = [ai[label] for label in self.getShownAttributeList()]
        if not attrIndices: return

        if self.implementation == FAST_IMPLEMENTATION:
            return self.optimize_FAST_Separation(steps, singleStep, distances)

        if self.__class__ != FreeViz: from PyQt4.QtGui import qApp
        if singleStep: steps = 1
        if self.implementation == SLOW_IMPLEMENTATION:
            impl = self.optimize_SLOW_Separation
        elif self.implementation == LDA_IMPLEMENTATION:
            impl = self.optimize_LDA_Separation
        XAnchors = None
        YAnchors = None

        for c in range((singleStep and 1) or 50):
            for i in range(steps):
                if self.__class__ != FreeViz and self.cancelOptimization == 1:
                    return
                self.graph.anchorData, (XAnchors, YAnchors) = impl(
                    attrIndices, self.graph.anchorData, XAnchors, YAnchors)
            if self.__class__ != FreeViz: qApp.processEvents()
            if hasattr(self.graph, "updateGraph"): self.graph.updateData()
Пример #14
0
    def __init__(self, filename=''):
        MainWindowBA.__init__(self)

        # Initialized here because QPixmap should be loaded in the main thread
        STATUS_PIXMAPS_DICT[MATCH_NA] = getPixmap('yellowStatusIcon.xpm')
        STATUS_PIXMAPS_DICT[MATCH_OK] = getPixmap('greenStatusIcon.xpm')
        STATUS_PIXMAPS_DICT[MATCH_FAIL] = getPixmap('redStatusIcon.xpm')
        STATUS_PIXMAPS_DICT[MATCH_PAUSED] = getPixmap('pauseStatusIcon.xpm')

        self._rp = RegexProcessor()
        self._rp.connect(self._regexStatusChanged)

        self._regexSaved = ''
        self._isExamined = False
        self._isPaused = False

        self.importFilename = ''
        self.filename = ''

        self.url = KANG_WEBSITE
        self.editstate = STATE_UNEDITED

        header = self.groupTable.horizontalHeader()
        header.setResizeMode(QHeaderView.Stretch)
        # header.setStretchLastSection(True)

        self.refWin = None
        self.regexlibwin = None

        self.setWindowIcon(getIcon('kang-icon'))

        self.statusbar = StatusBar(self)

        self.loadToolbarIcons()

        self.updateStatus(MSG_NA, MATCH_NA)
        self._clearResults()

        restoreWindowSettings(self, GEO)

        self._showReplaceWidgets(False)

        self.show()

        self.preferences = Preferences()
        self.recentFiles = RecentFiles(self, self.preferences.recentFilesNum)
        self.preferencesChanged()

        if filename and self.openFile(filename):
            qApp.processEvents()

        self._signalException.connect(self.showReportBugDialog)

        self.connect(self, SIGNAL('preferencesChanged()'), self.preferencesChanged)
        self.connect(self, SIGNAL('pasteSymbol(PyQt_PyObject)'), self.pasteSymbol)
        self.connect(self, SIGNAL('urlImported(PyQt_PyObject, PyQt_PyObject)'), self.urlImported)
        self.connect(self, SIGNAL('pasteRegexLib(PyQt_PyObject)'), self.pasteFromRegexLib)

        self.checkForKangDir()
    def display_message(self, msg):
        """Display a message in the message section of the dialog.

        Keyword arguments:
        msg -- the message
        """
        self.message.append(msg)
        qApp.processEvents()
Пример #16
0
    def display_message(self, msg):
        """Display a message in the message section of the dialog.

        Keyword arguments:
        msg -- the message
        """
        self.message.append(msg)
        qApp.processEvents()
Пример #17
0
 def processAlgorithm(self, progress):
     postString = self.defineProcess()
     qDebug(postString)
     self.wps = ExecutionResult(self.getLiteralResult, self.getResultFile, self.errorResult, None)
     self.wps.executeProcess(self.process.processUrl, postString)
     #Wait for answer
     while not self.wps.finished():
          qApp.processEvents()
Пример #18
0
 def EditProgram(self):
     self.resourcesGraphEditor.canvas.changed = False
     self.resourcesGraphEditor.show()
     while self.resourcesGraphEditor.isVisible():
         qApp.processEvents()
     if self.resourcesGraphEditor.canvas.changed:
         for t in self.project.tenants:
             t.RemoveAssignment()
Пример #19
0
 def SaveSize(self):
     ''' Save Dialog Size '''
     dw = self.width()
     dh = self.height()
     self.s.setValue("EquirectangularViewer/width", dw)
     self.s.setValue("EquirectangularViewer/height", dh)
     qApp.processEvents()
     return
Пример #20
0
 def processAlgorithm(self, progress):
     postString = self.defineProcess()
     qDebug(postString)
     self.wps = ExecutionResult(self.getLiteralResult, self.getResultFile, self.errorResult, None)
     self.wps.executeProcess(self.process.processUrl, postString)
     #Wait for answer
     while not self.wps.finished():
          qApp.processEvents()
Пример #21
0
 def on_pushEnroll_clicked(self):
     """Enroll button slot."""
     popup = swipe.swipeDialog()
     popup.show()
     qApp.processEvents(QEventLoop.AllEvents)
     #thread.start_new_thread(self.enroll())
     self.enroll()
     popup.reject()
     self.updateUi()
Пример #22
0
 def on_btnOscilloscope_clicked(self):
     """
     Monitor the light incident on the power meter.
     """
     
     # create the object for the power meter
     if not self.oscilloscope:
         if(self.isPWMConnected and not self.isSPADConnected):
             # create the object for the power meter and open it
             pwm = pm100d()
         elif (self.isSPADConnected and not self.isPWMConnected):
             #create object for the SPAD
             self.ttagBuf = ttag.TTBuffer(self.bufNum) 
         else:
             print("Please connect a sensor")
             return
         self.oscilloscope = True
         
         self.btnOscilloscope.setStyleSheet("background-color: red")
         self.btnOscilloscope.setText("Stop Oscilloscope")
         self.btnStart.setEnabled(False)
         self.btnConnectPWM.setEnabled(False)
         self.btnConnectSPAD.setEnabled(False)
         self.btnLoad.setEnabled(False)
         
         sampleIndex = 0
         sampleTot = 1000
         sample = np.arange(sampleTot)
         
         power = np.zeros((sampleTot, 1))
         while self.oscilloscope:
             qApp.processEvents()
             if(self.isPWMConnected and not self.isSPADConnected):
                 time.sleep(self.pause)
                 p = max(pwm.read()*1000, 0.)  
             elif (self.isSPADConnected and not self.isPWMConnected):
                 time.sleep(self.exptime)
                 if self.SPADChannel == self.SPADOtherChannel:
                     singles = self.ttagBuf.singles(self.exptime)
                     p = singles[self.SPADChannel]
                 else:
                     coincidences = self.ttagBuf.coincidences(self.exptime,self.coincWindow,-self.delay)
                     p=coincidences[self.SPADChannel, self.SPADOtherChannel]
             power[sampleIndex] = p
             sampleIndex = (sampleIndex+1) % sampleTot
             self.lblPower.setText("{:.3}".format(float(p)))
             self.axOscilloscope.plot(sample, power, '.')
             self.plotOscilloscope.draw()
         
     else:
         self.btnOscilloscope.setStyleSheet("")
         self.btnOscilloscope.setText("Oscilloscope")
         self.btnStart.setEnabled(True)
         self.btnConnectPWM.setEnabled(True)
         self.btnConnectSPAD.setEnabled(True)
         self.btnLoad.setEnabled(True)
         self.oscilloscope = False
Пример #23
0
 def on_pushEnroll_clicked(self):
     """Enroll button slot."""
     popup = swipe.swipeDialog()
     popup.show()
     qApp.processEvents(QEventLoop.AllEvents)
     # thread.start_new_thread(self.enroll())
     self.enroll()
     popup.reject()
     self.updateUi()
Пример #24
0
 def refit_gaussians(self):
     for i in np.arange(len(self.puffs)):
         percent = i / len(self.puffs)
         self.puffAnalyzer.algorithm_gui.gaussianProgress.setValue(percent * 100)
         qApp.processEvents()
         puff = self.puffs[i]
         puff.refit_gaussian()
     self.puffAnalyzer.algorithm_gui.gaussianProgress.setValue(100)
     qApp.processEvents()
Пример #25
0
    def encrypt_and_save_to(self, warehouse):
        files_count = sum(len(f) for f in self.files_found.values())
        self.progressBarBackup.setMaximum(files_count)
        self.progressBarBackup.setValue(0)
        now_date = datetime.datetime.now().strftime('Backup_%m-%d-%y_%H-%M')
        mkdir(self.current_dir + warehouse + sep + now_date + sep)
        for category, files in self.files_found.items():
            current_dir = self.current_dir + warehouse + sep + now_date + sep + category + sep
            if not path.exists(current_dir):
                mkdir(current_dir)
            print(files)
            for file_path in files:
                if file_path == 'deleted':
                    qApp.processEvents()
                    self.progressBarBackup.setValue(
                        self.progressBarBackup.value() + 1)
                    continue
                file_name = file_path.split(sep)[-1]
                if not self.is_exist(warehouse, file_path, category, now_date):
                    checksumm = Crc(0x104c11db7)
                    checksumm.update(file_path.encode('utf-8'))
                    checksumm.update(str(
                        stat(file_path)[-2]))  # modification time
                    with open(file_path,
                              'rb') as reader, open(current_dir + file_name,
                                                    'wb') as writer:
                        chunksize = 64 * 1024 * 16
                        iv = ''.join(
                            chr(random.randint(0, 0xFF)) for _ in range(16))
                        cipher = AES.new(
                            self.password + self.padding[len(self.password):],
                            AES.MODE_CBC, iv)
                        filesize = path.getsize(file_path)

                        writer.write(pack('<Q', filesize))
                        writer.write(iv)
                        writer.write(pack('<B',
                                          len(file_path.encode('utf-8'))))
                        writer.write(file_path.encode('utf-8'))

                        part = reader.read(chunksize)
                        checksumm.update(part)
                        while part:
                            if len(part) % 16 != 0:
                                part += ' ' * (16 - len(part) % 16)
                            ciphertext = cipher.encrypt(part)
                            writer.write(ciphertext)
                            part = reader.read(chunksize)
                            checksumm.update(part)
                    rename(current_dir + file_name,
                           current_dir + file_name + checksumm.hexdigest())

                qApp.processEvents()
                self.progressBarBackup.setValue(
                    self.progressBarBackup.value() + 1)
        self.progressBarBackup.setValue(self.progressBarBackup.maximum())
Пример #26
0
    def GetBackNextImage(self):
        ''' Get to Back Image '''
        qgsutils.removeAllHighlightFeaturesFromCanvasScene(self.canvas)

        sender = QObject.sender(self)

        lys = self.canvas.layers()  # Check if mapa foto is loaded
        if len(lys) == 0:
            qgsutils.showUserAndLogMessage(
                self, u"Information: ", u"You need to upload the photo layer.",
                QgsMessageBar.INFO)
            return

        for layer in lys:
            if layer.name() == config.layer_name:
                self.encontrado = True
                self.iface.setActiveLayer(layer)
                qApp.processEvents()

                f = self.selected_features

                ac_lordem = f.attribute(config.column_order)

                if sender.objectName() == "btn_back":
                    new_lordem = int(ac_lordem) - 1
                else:
                    new_lordem = int(ac_lordem) + 1

                # Filter mapa foto layer
                ids = [feat.id() for feat in layer.getFeatures(
                    QgsFeatureRequest().setFilterExpression(config.column_order + " ='" + 
                                                            str(new_lordem) + 
                                                            "'"))]

                if len(ids) == 0:
                    qgsutils.showUserAndLogMessage(
                        self, u"Information: ", u"There is no superiority that follows.",
                        QgsMessageBar.INFO)
                    # Filter mapa foto layer
                    ids = [feat.id() for feat in layer.getFeatures(
                        QgsFeatureRequest().setFilterExpression(config.column_order + " ='" + 
                                                                str(ac_lordem) + 
                                                                "'"))]
                    # Update selected feature
                    self.ReloadView(ids[0])
                    return

                self.ReloadView(ids[0])
                qApp.processEvents()

        if self.encontrado is False:
            qgsutils.showUserAndLogMessage(
                self, u"Information: ", u"You need to upload the photo layer.",
                QgsMessageBar.INFO)

        return
Пример #27
0
 def readData(self, maxlen):
     while self.bytesAvailable() == 0:    
         qApp.processEvents()     
         time.sleep(0.01) 
     
     number = min(maxlen, len(self.__buffer) - self.__offset)    
     data = self.__buffer[self.__offset:self.__offset + number]
     self.__offset += number
     
     return data
Пример #28
0
 def seqIterator(self):
     """Generator which iterates over the input elements, calling
     processFuncs and yields the processed element, one at a time.
     """
     for item in self.inputSlot.container:
         if armor.useOrange:
             from PyQt4.QtGui import qApp
             qApp.processEvents()
         item = self.processFunc(item)
         yield item
Пример #29
0
 def seqIterator(self):
     """Generator which iterates over the input elements, calling
     processFuncs and yields the processed element, one at a time.
     """
     for item in self.inputSlot.container:
         if pynopticon.useOrange:
             from PyQt4.QtGui import qApp
             qApp.processEvents()
         item = self.processFunc(item)
         yield item
Пример #30
0
 def FullScreen(self, bool):
     ''' FullScreen action button '''
     qgsutils.showUserAndLogMessage(
         self, u"Information: ", u"Fullscreen.", QgsMessageBar.INFO,
         onlyLog=True)
     if(bool):
         self.showFullScreen()
     else:
         self.showNormal()
     qApp.processEvents()
     return
Пример #31
0
    def s2nMixAnchorsAutoSet(self):
        # check if we have data and a discrete class
        if not self.graph.haveData or len(self.graph.rawData) == 0 or not self.graph.dataHasDiscreteClass:
            self.setStatusBarText("No data or data without a discrete class") 
            return

        vizrank = self.parentWidget.vizrank
        if self.__class__ != FreeViz: from PyQt4.QtGui import qApp

        if self.autoSetParameters:
            results = {}
            self.s2nSpread = 0
            permutations = orngVisFuncts.generateDifferentPermutations(range(len(self.graph.dataDomain.classVar.values)))
            for perm in permutations:
                self.classPermutationList = perm
                for val in self.attrsNum:
                    if self.attrsNum[self.attrsNum.index(val)-1] > len(self.graph.dataDomain.attributes): continue    # allow the computations once
                    self.s2nPlaceAttributes = val
                    if not self.s2nMixAnchors(0):
                        return
                    if self.__class__ != FreeViz:
                        qApp.processEvents()

                    acc, other = vizrank.kNNComputeAccuracy(self.graph.createProjectionAsExampleTable(None, useAnchorData = 1))
                    if results.keys() != []: self.setStatusBarText("Current projection value is %.2f (best is %.2f)" % (acc, max(results.keys())))
                    else:                    self.setStatusBarText("Current projection value is %.2f" % (acc))

                    results[acc] = (perm, val)
            if results.keys() == []: return
            self.classPermutationList, self.s2nPlaceAttributes = results[max(results.keys())]
            if self.__class__ != FreeViz:
                qApp.processEvents()
            if not self.s2nMixAnchors(0):        # update the best number of attributes
                return

            results = []
            anchors = self.graph.anchorData
            attributeNameIndex = self.graph.attributeNameIndex
            attrIndices = [attributeNameIndex[val[2]] for val in anchors]
            for val in range(10):
                self.s2nSpread = val
                if not self.s2nMixAnchors(0):
                    return
                acc, other = vizrank.kNNComputeAccuracy(self.graph.createProjectionAsExampleTable(attrIndices, useAnchorData = 1))
                results.append(acc)
                if results != []: self.setStatusBarText("Current projection value is %.2f (best is %.2f)" % (acc, max(results)))
                else:             self.setStatusBarText("Current projection value is %.2f" % (acc))
            self.s2nSpread = results.index(max(results))

            self.setStatusBarText("Best projection value is %.2f" % (max(results)))

        # always call this. if autoSetParameters then because we need to set the attribute list in radviz. otherwise because it finds the best attributes for current settings
        self.s2nMixAnchors()
Пример #32
0
 def write(self, s):
     if self.echo:
         sys.__stdout__.write(s)
     doc = self.document()
     cursor = QTextCursor(doc)
     cursor.clearSelection()
     cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
     cursor.insertText(s)
     cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
     cursor.clearSelection()
     self.ensureCursorVisible()
     qApp.processEvents()
Пример #33
0
 def write(self, s):
     if self.echo:
         sys.__stdout__.write(s)
     doc = self.document()
     cursor = QTextCursor(doc)
     cursor.clearSelection()
     cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
     cursor.insertText(s)
     cursor.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
     cursor.clearSelection()
     self.ensureCursorVisible()
     qApp.processEvents()
Пример #34
0
 def EditProgram(self):
     self.graphEditor.show()
     # Wait until the editor window is closed
     while self.graphEditor.isVisible():
         qApp.processEvents()
     if self.graphEditor.canvas.changed:
         if self.LoadErrors():
             self.project.method.Reset()
             self.loadSchedule()
             self.EnableRunning()
         else:
             self.DisableRunning()
             self.viewer.hide()
Пример #35
0
 def updateLog(self, msg):
     '''
     Update the log
     '''
     t = self.dlg.txtLog
     t.ensureCursorVisible()
     prefix = '<span style="font-weight:normal;">'
     suffix = '</span>'
     t.append( '%s %s %s' % (prefix, msg, suffix) )
     c = t.textCursor()
     c.movePosition(QTextCursor.End, QTextCursor.MoveAnchor)
     t.setTextCursor(c)
     qApp.processEvents()
Пример #36
0
    def closeEvent(self, evt):
        ''' Close dialog '''
        qgsutils.showUserAndLogMessage(
            self, u"Information: ", u"Close dialog", QgsMessageBar.INFO,
            onlyLog=True)
        qgsutils.removeAllHighlightFeaturesFromCanvasScene(self.canvas)
        qApp.processEvents()

        self.canvas.refresh()
        self.iface.actionPan().trigger()
        self.SaveSize()
        qApp.processEvents()
        return
Пример #37
0
    def RestoreSize(self):
        ''' Restore Dialog Size '''
        dw = self.s.value("EquirectangularViewer/width")
        dh = self.s.value("EquirectangularViewer/height")

        if dw is None:
            return
        size = self.size()

        anim = QPropertyAnimation(self, 'size', self)
        anim.setStartValue(size)
        anim.setEndValue(QSize(dw, dh))
        anim.setDuration(1)
        anim.start()
        qApp.processEvents()
        return
Пример #38
0
 def __init__(self, parent, msg='', steps=0):
     '''
     progressBar class instatiation method. It creates a QgsMessageBar with provided msg and a working QProgressBar
     :param parent:
     :param msg: string
     '''
     self.iface = parent.iface
     widget = self.iface.messageBar().createMessage("fdtm plugin:", msg)
     self.progressBar = QProgressBar()
     self.progressBar.setRange(0, steps)  #(1,steps)
     self.progressBar.setValue(0)
     self.progressBar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
     widget.layout().addWidget(self.progressBar)
     qApp.processEvents()
     self.iface.messageBar().pushWidget(widget, QgsMessageBar.INFO, 50)
     qApp.processEvents()
Пример #39
0
    def start(self):
        '''
        Starts the conversion process.
        '''
        def myLoadProgress(progress):
            self._loadProgress = progress

        def myLoadFinished(isLoaded):
            self._loaded = True

        webpage = QWebPage()
        webpage.loadProgress.connect(myLoadProgress)
        webpage.loadFinished.connect(myLoadFinished)

        url = misc.temp_path('import')
        baseUrl = QUrl.fromLocalFile(url)
        webpage.mainFrame().setHtml(
            self._document.getMainPage(mathOutput='svg'), baseUrl)

        while not self._loaded and not self._canceled:
            qApp.processEvents()

        self.ui.label.setText('Typesetting math equations...')

        if not self._canceled:

            # Wait for the MathJax to typeset
            while not self._mathTypeset and not self._canceled:
                qApp.processEvents()
                progress = int(webpage.mainFrame().evaluateJavaScript(
                    misc.js_command('GetMathTypesetProgress', [])).toInt()[0])
                self.ui.progressBar.setValue(progress)
                self._mathTypeset = webpage.mainFrame().evaluateJavaScript(
                    misc.js_command('IsMathTypeset', [])).toBool()

            # If I haven't canceled yet, let's convert the document in a
            # separate thread
            if not self._canceled:
                self._thread = ExportToHtmlThread(
                    unicode(webpage.mainFrame().evaluateJavaScript(
                        misc.js_command('GetBodyHTML', [])).toString()),
                    self._configuration, self._assigner, self._filePath)
                self._thread.onProgress.connect(self.ui.progressBar.setValue)
                self._thread.onProgressLabel.connect(self.ui.label.setText)
                self._thread.finished.connect(self._threadFinished)
                self.ui.cancelButton.clicked.connect(self._thread.quit)
                self._thread.start()
Пример #40
0
    def progressBarSet(self, value, processEvents=QEventLoop.AllEvents):
        """
        Set the current progress bar to `value`.

        .. note::
            This method will by default call `QApplication.processEvents`
            with `processEvents`. To suppress this behavior pass
            ``processEvents=None``.

        :param float value: Progress value
        :param processEvents: Process events flag
        :type processEvents: `QEventLoop.ProcessEventsFlags` or `None`
        """
        old = self.__progressBarValue
        self.__progressBarValue = value

        if value > 0:
            if self.__progressState != 1:
                warnings.warn(
                    "progressBarSet() called without a "
                    "preceding progressBarInit()",
                    stacklevel=2)
                self.__progressState = 1
                self.processingStateChanged.emit(1)

            usedTime = max(1, time.time() - self.startTime)
            totalTime = 100.0 * usedTime / value
            remainingTime = max(0, int(totalTime - usedTime))
            hrs = remainingTime // 3600
            mins = (remainingTime % 3600) // 60
            secs = remainingTime % 60
            if hrs > 0:
                text = "{}:{:02}:{:02}".format(hrs, mins, secs)
            else:
                text = "{}:{}:{:02}".format(hrs, mins, secs)
            self.setWindowTitle(
                "{} ({:.2f}% complete, remaining time: {})".format(
                    self.captionTitle, value, text))
        else:
            self.setWindowTitle(self.captionTitle + " (0% complete)")

        if old != value:
            self.progressBarValueChanged.emit(value)

        if processEvents is not None and processEvents is not False:
            qApp.processEvents(processEvents)
Пример #41
0
    def progressBarSet(self, value, processEvents=QEventLoop.AllEvents):
        """
        Set the current progress bar to `value`.

        .. note::
            This method will by default call `QApplication.processEvents`
            with `processEvents`. To suppress this behavior pass
            ``processEvents=None``.

        :param float value: Progress value
        :param processEvents: Process events flag
        :type processEvents: `QEventLoop.ProcessEventsFlags` or `None`
        """
        old = self.__progressBarValue
        self.__progressBarValue = value

        if value > 0:
            if self.__progressState != 1:
                warnings.warn(
                    "progressBarSet() called without a "
                    "preceding progressBarInit()",
                    stacklevel=2)
                self.__progressState = 1
                self.processingStateChanged.emit(1)

            usedTime = max(1, time.time() - self.startTime)
            totalTime = (100.0 * usedTime) / float(value)
            remainingTime = max(0, totalTime - usedTime)
            h = int(remainingTime / 3600)
            min = int((remainingTime - h * 3600) / 60)
            sec = int(remainingTime - h * 3600 - min * 60)
            if h > 0:
                text = "%(h)d:%(min)02d:%(sec)02d" % vars()
            else:
                text = "%(min)d:%(sec)02d" % vars()
            self.setWindowTitle(
                self.captionTitle +
                " (%(value).2f%% complete, remaining time: %(text)s)" % vars())
        else:
            self.setWindowTitle(self.captionTitle + " (0% complete)")

        if old != value:
            self.progressBarValueChanged.emit(value)

        if processEvents is not None and processEvents is not False:
            qApp.processEvents(processEvents)
Пример #42
0
    def progressBarSet(self, value, processEvents=QEventLoop.AllEvents):
        """
        Set the current progress bar to `value`.

        .. note::
            This method will by default call `QApplication.processEvents`
            with `processEvents`. To suppress this behavior pass
            ``processEvents=None``.

        :param float value: Progress value
        :param processEvents: Process events flag
        :type processEvents: `QEventLoop.ProcessEventsFlags` or `None`
        """
        old = self.__progressBarValue
        self.__progressBarValue = value

        if value > 0:
            if self.__progressState != 1:
                warnings.warn("progressBarSet() called without a "
                              "preceding progressBarInit()",
                              stacklevel=2)
                self.__progressState = 1
                self.processingStateChanged.emit(1)

            usedTime = max(1, time.time() - self.startTime)
            totalTime = 100.0 * usedTime / value
            remainingTime = max(0, int(totalTime - usedTime))
            hrs = remainingTime // 3600
            mins = (remainingTime % 3600) // 60
            secs = remainingTime % 60
            if hrs > 0:
                text = "{}:{:02}:{:02}".format(hrs, mins, secs)
            else:
                text = "{}:{}:{:02}".format(hrs, mins, secs)
            self.setWindowTitle(
                self.captionTitle +
                " ({}% complete, remaining time: {})".format(value, text))
        else:
            self.setWindowTitle(self.captionTitle + " (0% complete)")

        if old != value:
            self.progressBarValueChanged.emit(value)

        if processEvents is not None and processEvents is not False:
            qApp.processEvents(processEvents)
Пример #43
0
    def __init__(self, iface, parent=None, featuresId=None, layer=None):

        QDialog.__init__(self)

        self.setupUi(self)
        self.s = QSettings()

        self.plugin_path = os.path.dirname(os.path.realpath(__file__))

        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        self.parent = parent

        # Orientation from image
        self.yaw = math.pi
        self.bearing = None

        self.layer = layer
        self.featuresId = featuresId

        # Restore Previous size
        self.RestoreSize()

        self.actualPointDx = None
        self.actualPointSx = None
        self.actualPointOrientation = None

        self.selected_features = qgsutils.getToFeature(
            self.layer, self.featuresId)

        # Get image path
        self.current_image = self.GetImage()
        qApp.processEvents()

        # Create Viewer
        self.CreateViewer()
        qApp.processEvents()

        # Check if image exist
        if os.path.exists(self.current_image) is False:
            qgsutils.showUserAndLogMessage(
                self, u"Information: ", u"There is no associated image.",
                QgsMessageBar.INFO)
            self.ChangeUrlViewer(config.DEFAULT_EMPTY)
            self.setPosition()
            return

        # Set RubberBand
        self.setOrientation()
        self.setPosition()
        qApp.processEvents()

        # Copy file to local server
        self.CopyFile(self.current_image)
        qApp.processEvents()
Пример #44
0
 def __init__(self,clusters,cluster_im,puffAnalyzer,persistentInfo=None):#weakfilt,strongfilt,paddingXY,paddingT_pre,paddingT_post,maxSigmaForGaussianFit,rotatedfit):
     self.puffAnalyzer=puffAnalyzer
     self.udc=puffAnalyzer.udc        
     self.puffs=[]
     self.index=0
     self.clusters=clusters
     self.normalized_window=puffAnalyzer.normalized_window
     self.data_window=puffAnalyzer.data_window
     self.cluster_im=cluster_im
     
     self.puffs=[]
     nClusters=len(self.clusters.clusters)
     for i in np.arange(nClusters):
         percent=i/nClusters
         self.puffAnalyzer.algorithm_gui.gaussianProgress.setValue(percent*100); qApp.processEvents();
         self.puffs.append(Puff(i,self.clusters,self,persistentInfo))
     self.puffAnalyzer.algorithm_gui.gaussianProgress.setValue(100)
     qApp.processEvents()
Пример #45
0
    def chart(self,
              options=None,
              *,
              highchart=None,
              javascript='',
              javascript_after='',
              **kwargs):
        """ Populate the webview with a new Highcharts JS chart.

        Parameters
        ----------
        options, highchart, javascript, **kwargs:
            The parameters are the same as for the object constructor.
        javascript_after: str
            Same as `javascript`, except that the code is evaluated
            after the chart, available as ``window.chart``, is created.

        Notes
        -----
        Passing ``{ series: [{ data: some_data }] }``, if ``some_data`` is
        a numpy array, it is **more efficient** to leave it as numpy array
        instead of converting it ``some_data.tolist()``, which is done
        implicitly.
        """
        # Give default options some time to apply
        qApp.processEvents(QEventLoop.ExcludeUserInputEvents)

        options = (options or {}).copy()
        if not isinstance(options, MutableMapping):
            raise ValueError('options must be dict')

        if kwargs:
            _merge_dicts(options, _kwargs_options(kwargs))
        self.exposeObject('pydata', options)
        highchart = highchart or self.highchart or 'Chart'
        self.evalJS('''
            {javascript};
            window.chart = new Highcharts.{highchart}(pydata);
            {javascript_after};
        '''.format(
            javascript=javascript,
            javascript_after=javascript_after,
            highchart=highchart,
        ))
Пример #46
0
    def progressBarSet(self, value, processEvents=QEventLoop.AllEvents):
        """
        Set the current progress bar to `value`.

        .. note::
            This method will by default call `QApplication.processEvents`
            with `processEvents`. To suppress this behavior pass
            ``processEvents=None``.

        :param float value: Progress value
        :param processEvents: Process events flag
        :type processEvents: `QEventLoop.ProcessEventsFlags` or `None`
        """
        old = self.__progressBarValue
        self.__progressBarValue = value

        if value > 0:
            if self.__progressState != 1:
                warnings.warn("progressBarSet() called without a "
                              "preceding progressBarInit()",
                              stacklevel=2)
                self.__progressState = 1
                self.processingStateChanged.emit(1)

            usedTime = max(1, time.time() - self.startTime)
            totalTime = (100.0 * usedTime) / float(value)
            remainingTime = max(0, totalTime - usedTime)
            h = int(remainingTime / 3600)
            min = int((remainingTime - h * 3600) / 60)
            sec = int(remainingTime - h * 3600 - min * 60)
            if h > 0:
                text = "%(h)d:%(min)02d:%(sec)02d" % vars()
            else:
                text = "%(min)d:%(sec)02d" % vars()
            self.setWindowTitle(self.captionTitle +
                                " (%(value).2f%% complete, remaining time: %(text)s)" % vars())
        else:
            self.setWindowTitle(self.captionTitle + " (0% complete)")

        if old != value:
            self.progressBarValueChanged.emit(value)

        if processEvents is not None and processEvents is not False:
            qApp.processEvents(processEvents)
Пример #47
0
    def makeGif(self):

        imgs = [unicode(self.listWidget.item(i).text()) for i in range(self.listWidget.count())]
        if len(imgs) <= 1:
            QMessageBox.warning(self, u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName),
                                u"GIF动画文件必须要给定大于一张图片。")
            return
        if not self.updateGifPath():
            return
        durations = self.spbTime.value()
        loops = self.spbLoop.value()
        ok, msg = img2gif.images2gif(imgs, self.txtGifPath.text(), durations=durations, loops=loops)
        if ok:
            QMessageBox.about(self, u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName),
                              u"Succeed!\n{0}".format(msg))
            qApp.processEvents()
        else:
            QMessageBox.about(u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName),
                              u"sorry! Failed to generate the {0}".format(unicode(self.txtGifPath)))
Пример #48
0
 def run(self):
     print "stream handler started [stream_id: %s, chunks_count: %d]" % (self.stream_id, self.chunks_count)
     while self.buffer is None:
         qApp.processEvents()
         sleep(0.01)
     while not self.receive_complete:
         for peer in self.peers:
             print "new request packet sent [stream_id: %s, n: %d]" % (self.stream_id, self.current_packet_number)
             print "current packet number: %d" % self.current_packet_number
             print "chunks count: %d" % self.chunks_count
             print "buffer size: %d" % self.buffer.size()
             print "bytes available: %d" % self.buffer.size()
             peer.sendPacket(Packet(PacketTypes.REQUEST_PART, {"stream_id": self.stream_id,
                                 "from": self.current_packet_number}))
         if self.current_packet_number >= self.chunks_count:
             break
         else:
             self.current_packet_number += 1
         sleep(0.01)
Пример #49
0
    def progressBarFinished(self, processEvents=QEventLoop.AllEvents):
        """
        Stop the widget's progress (i.e hide the progress bar).

        .. note::
            This method will by default call `QApplication.processEvents`
            with `processEvents`. To suppress this behavior pass
            ``processEvents=None``.

        :param processEvents: Process events flag
        :type processEvents: `QEventLoop.ProcessEventsFlags` or `None`
        """
        self.setWindowTitle(self.captionTitle)
        if self.__progressState != 0:
            self.__progressState = 0
            self.processingStateChanged.emit(0)

        if processEvents is not None and processEvents is not False:
            qApp.processEvents(processEvents)
Пример #50
0
    def progressBarFinished(self, processEvents=QEventLoop.AllEvents):
        """
        Stop the widget's progress (i.e hide the progress bar).

        .. note::
            This method will by default call `QApplication.processEvents`
            with `processEvents`. To suppress this behavior pass
            ``processEvents=None``.

        :param processEvents: Process events flag
        :type processEvents: `QEventLoop.ProcessEventsFlags` or `None`
        """
        self.setWindowTitle(self.captionTitle)
        if self.__progressState != 0:
            self.__progressState = 0
            self.processingStateChanged.emit(0)

        if processEvents is not None and processEvents is not False:
            qApp.processEvents(processEvents)
Пример #51
0
    def progressBarSet(self, value):
        if value > 0:
            self.__progressBarValue = value
            usedTime = max(1, time.time() - self.startTime)
            totalTime = (100.0 * usedTime) / float(value)
            remainingTime = max(0, totalTime - usedTime)
            h = int(remainingTime / 3600)
            min = int((remainingTime - h * 3600) / 60)
            sec = int(remainingTime - h * 3600 - min * 60)
            if h > 0:
                text = "%(h)d:%(min)02d:%(sec)02d" % vars()
            else:
                text = "%(min)d:%(sec)02d" % vars()
            self.setWindowTitle(self.captionTitle + " (%(value).2f%% complete, remaining time: %(text)s)" % vars())
        else:
            self.setWindowTitle(self.captionTitle + " (0% complete)")

        self.progressBarValueChanged.emit(value)

        qApp.processEvents()
Пример #52
0
    def setOrientation(self, yaw=None):
        ''' Set Orientation in the firt time '''
        self.bearing = self.selected_features.attribute(config.column_yaw)

        self.actualPointDx = self.selected_features.geometry().asPoint()

        try:
            self.actualPointOrientation.reset()
        except:
            pass

        qApp.processEvents()

        self.actualPointOrientation = QgsRubberBand(
            self.iface.mapCanvas(), QGis.Line)
        self.actualPointOrientation.setColor(Qt.blue)
        self.actualPointOrientation.setWidth(5)

        self.actualPointOrientation.addPoint(self.actualPointDx)

        # End Point
        CS = self.canvas.mapUnitsPerPixel() * 25
        A1x = self.actualPointDx.x() - CS * math.cos(math.pi / 2)
        A1y = self.actualPointDx.y() + CS * math.sin(math.pi / 2)

        self.actualPointOrientation.addPoint(QgsPoint(A1x, A1y))
        # Vision Angle
        if yaw is not None:
            angle = float(self.bearing + yaw) * math.pi / -180
        else:
            angle = float(self.bearing) * math.pi / -180

        tmpGeom = self.actualPointOrientation.asGeometry()

        self.rotateTool = transformGeometry()
        epsg = self.canvas.mapRenderer().destinationCrs().authid()
        self.dumLayer = QgsVectorLayer(
            "Point?crs=" + epsg, "temporary_points", "memory")
        self.actualPointOrientation.setToGeometry(self.rotateTool.rotate(
            tmpGeom, self.actualPointDx, angle), self.dumLayer)
        qApp.processEvents()
Пример #53
0
    def markFirstCountItemsAsRead(self, count, protectionMessage):
        """ 
        Отмечаем первые count записей в текущей категории, как прочитанные.
        Перед этим показываем 'защитное сообщение' protectionMessage

        """
        if not self.login():
            return

        if not self.userReallyWantsToMarkAsRead(protectionMessage):
            return
        progress = self.progressDialog(count)
        progress.show()
        for row in range(count):
            item = self._currentCategory().child(row)
            progress.setValue(row)
            id = item.data(0, Qt.UserRole)
            if item.checkState(0) == Qt.Checked:
                self._feed.getItem(id).interesting = True
                continue
            try:
                self._feed.getItem(id).markRead()
            except HTTPException as e:
                # Вообще, здесь нужно попытаться получить токен или auth заново
                text = 'При попытке отметить записи, как прочитанные возникла ошибка: ' + str(e)
                QMessageBox.warning(self, 'Ошибка', text)
                break
            if progress.wasCanceled():
                break
            qApp.processEvents()

        progress.setValue(count)
        self._ui.twEntries.setCurrentItem(None)
        self.updateDb()
        shouldReturnToDates = (settings.autoSwitchCategories() and
                        self._cbCategories.currentIndex() == 3)
        if shouldReturnToDates:
            self._switchToDates()
        self.splitItemsIntoCategories()
        self._updateWindowTitle()
Пример #54
0
    def chart(self, options=None, *,
              highchart=None, javascript='', javascript_after='', **kwargs):
        """ Populate the webview with a new Highcharts JS chart.

        Parameters
        ----------
        options, highchart, javascript, **kwargs:
            The parameters are the same as for the object constructor.
        javascript_after: str
            Same as `javascript`, except that the code is evaluated
            after the chart, available as ``window.chart``, is created.

        Notes
        -----
        Passing ``{ series: [{ data: some_data }] }``, if ``some_data`` is
        a numpy array, it is **more efficient** to leave it as numpy array
        instead of converting it ``some_data.tolist()``, which is done
        implicitly.
        """
        # Give default options some time to apply
        qApp.processEvents(QEventLoop.ExcludeUserInputEvents)

        options = (options or {}).copy()
        if not isinstance(options, MutableMapping):
            raise ValueError('options must be dict')

        if kwargs:
            _merge_dicts(options, _kwargs_options(kwargs))
        self.exposeObject('pydata', options)
        highchart = highchart or self.highchart or 'Chart'
        self.evalJS('''
            {javascript};
            window.chart = new Highcharts.{highchart}(pydata);
            {javascript_after};
        '''.format(javascript=javascript,
                   javascript_after=javascript_after,
                   highchart=highchart,))
Пример #55
0
 def _update_positions(self, positions):
     for node, pos in zip(self.nodes, positions*300):
         node.setPos(*pos)
     qApp.processEvents()
Пример #56
0
    def test(self):
        op = GenerateUuidsOperation()
        self.assertEqual(op.title, 'gen_uuids')
        self.assertEqual(op.state.status, OperationState.NotStarted)
        self.assertEqual(op.state.progress, 0)
        self.assertEqual(op.runMode, Operation.RunModeNotStarted)

        op.run(Operation.RunModeNewThread)
        final_status = op.join()
        self.assertEqual(op.state.status, OperationState.Completed)
        self.assertEqual(op.state.status, final_status)
        self.assertEqual(len(op.state.results), 1000)
        self.assertEqual(op.runMode, Operation.RunModeNewThread)

        with globalOperationContext().newOperation('test_op') as op:
            self.assertEqual(op.title, 'test_op')
            self.assertEqual(op.state.status, OperationState.Running)

        self.assertTrue(op.state.isFinished)
        self.assertEqual(op.state.status, OperationState.Completed)

        try:
            with globalOperationContext().newOperation('test_op') as op:
                raise TypeError('test_error')
        except TypeError:
            pass
        else:
            self.assertTrue(False)

        self.assertTrue(op.state.isFinished)
        self.assertEqual(op.state.status, OperationState.Failed)
        self.assertEqual(op.state.progress, 100)

        with globalOperationContext().newOperation('test_op') as op:
            op.setProgress(10.0)
            self.assertEqual(op.state.progress, 10.0)

            op.setProgress(100.0)
            self.assertEqual(op.state.progress, 100.0)

            op.setProgressText('working')
            self.assertEqual(op.state.progressText, 'working')

            op.setCanPause(True)
            self.assertEqual(op.state.canPause, True)
            op.setCanPause(False)

            op.setCanCancel(True)
            self.assertEqual(op.state.canCancel, True)
            op.setCanCancel(False)

            op.addMessage('error occupied', logging.ERROR)
            self.assertEqual(op.state.errorCount, 1)
            self.assertEqual(op.state.messages, [('error occupied', logging.ERROR)])

            op.addMessage('warning', logging.WARNING)
            self.assertEqual(op.state.errorCount, 1)
            self.assertEqual(op.state.warningCount, 1)
            self.assertEqual(op.state.messages, [('error occupied', logging.ERROR),
                                                 ('warning', logging.WARNING)])

            op.setProgress(20)
            self.assertEqual(op.state.progress, 20)

            with globalOperationContext().newOperation('sub-operation', progress_weight=40) as subop:
                subop.setCanPause(True)   # parent -> True
                subop.setCanCancel(True)  # parent -> False

                self.assertEqual(op.state.progress, 20)
                self.assertEqual(op.state.canPause, True)
                self.assertEqual(op.state.canCancel, False)
                self.assertEqual(op.state.progressText, 'working')

                subop.setProgress(50)
                self.assertEqual(op.state.progress, 40)  # 20 + 40 * (50 / 100)

                subop.setProgressText('sub task')
                self.assertEqual(op.state.progressText, 'sub task')

                subop.addResult('sub-result', 'result_value')
                self.assertEqual(len(subop.state.results), 1)
                self.assertEqual(len(op.state.results), 0)

            # sub operation finished
            self.assertEqual(op.state.canPause, False)
            self.assertEqual(op.state.canCancel, False)
            self.assertEqual(op.state.progress, 60)  # 20 + 40
            self.assertEqual(op.state.progressText, 'working')
            self.assertEqual(len(op.state.results), 0)

            op.sendPause()
            self.assertEqual(op.takeCommand(), Operation.PauseCommand)

        def some_function():
            return 2 * 2

        wrapper_operation = WrapperOperation(some_function)
        wrapper_operation.run()
        wrapper_operation.join()
        self.assertEqual(wrapper_operation.state.results['result'], 4)

        seq_operation = SequentialOperationGroup('some_operation')
        seq_operation.appendOperation(WrapperOperation(lambda: 1), result_name_converter=lambda x: '1')
        seq_operation.appendOperation(WrapperOperation(lambda: 2), result_name_converter=lambda x: '2')
        seq_operation.appendOperation(WrapperOperation(lambda: 3), result_name_converter=lambda x: '3')
        seq_operation.run()
        seq_operation.join()
        self.assertEqual(seq_operation.state.results, {'1': 1, '2': 2, '3': 3})

        callback_called = False
        main_thread = threading.current_thread()
        def user_callback():
            nonlocal callback_called
            callback_called = True
            self.assertTrue(main_thread is threading.current_thread())
            return 1

        def parallel():
            op = globalOperationContext().currentOperation
            accepted, result = op.requestGuiCallback(user_callback)
            self.assertTrue(accepted)
            self.assertEqual(result, 1)
            self.assertTrue(callback_called)

        wrapper_operation = WrapperOperation(parallel)
        wrapper_operation.run()
        while not wrapper_operation.state.isFinished:
            qApp.processEvents()
        self.assertTrue(callback_called)
Пример #57
0
    def ParseSML(self):
        """Parse SAS Planet data to splite db and make layers tree"""
        try:
            self.dockwidget.sasprogressBar.value = 0
            if not os.path.exists(self.sml_data['db_file']):
                empty_db = os.path.join(os.path.dirname(__file__),'empty.sqlite')
                if os.path.exists(empty_db):
                    shutil.copy2(empty_db,self.sml_data['db_file'])
                else:
                    UniumPlugin.create_db(self.sml_data['db_file'])
                QgsMessageLog.logMessage(u'Новая база создана', level=QgsMessageLog.INFO)
            self.src_info["database"] = self.sml_data['db_file']
            self.dockwidget.sasprogressBar.setValue(25)
            qApp.processEvents()

            self.sml_data['table'] = UniumPlugin.create_table(self.sml_data['db_file'],self.sml_data['table'])
            self.src_info["datatable"] = self.sml_data['table']
            QgsMessageLog.logMessage(u'Новая таблица в базе создана', level=QgsMessageLog.INFO)
            self.dockwidget.sasprogressBar.setValue(50)
            qApp.processEvents()

            QgsMessageLog.logMessage(u'Начинаю загружать метки', level=QgsMessageLog.INFO)

            marksf = open(self.sml_data['marks_file'],'r')
            tree = etree.XML(marksf.read().decode('cp1251'))
            marksf.close()

            nodes = tree.xpath('/DATAPACKET/ROWDATA/ROW')

            uri = QgsDataSourceURI()
            uri.setDatabase(self.sml_data['db_file'])
            uri.setDataSource('', self.sml_data['table'], 'shape')

            lyr = QgsVectorLayer(uri.uri(),self.sml_data['table'],'spatialite')
            pr = lyr.dataProvider()
            lyr.startEditing()

            nodes_count = len(nodes)
            groups = [self.config["write_block"] for i in xrange(nodes_count/self.config["write_block"])]
            groups.append(nodes_count%self.config["write_block"])

            prgrs_interval = int(math.ceil(nodes_count/25.0))

            features = []
            group_idx = 0
            f_idx = 0
            position = 50

            for node in nodes:
                feature = QgsFeature()
                feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(float(node.get('lonL')),float(node.get('LatB')))))
                fields = pr.fields()
                feature.setFields(fields)
                feature.setAttribute('name',node.get('name'))
                feature.setAttribute('descr',node.get('descr'))
                feature.setAttribute('sign',self.get_sign_by_src(node.get('picname')))
                feature.setAttribute('cat_id',int(node.get('categoryid')))
                features.append(feature)
                if len(features) == groups[group_idx]:
                    pr.addFeatures(features)
                    features = []
                    group_idx+=1
                f_idx+=1
                if f_idx%prgrs_interval == 0:
                    position+=1
                    self.dockwidget.sasprogressBar.setValue(position)
                    qApp.processEvents()

            lyr.commitChanges()
            self.dockwidget.sasprogressBar.setValue(75)
            qApp.processEvents()
            
            lyr = None
            
            QgsMessageLog.logMessage(u'Метки записаны в БД', level=QgsMessageLog.INFO)
            QgsMessageLog.logMessage(u'Начинаем добавлять слои', level=QgsMessageLog.INFO)
        
            catf = open(self.sml_data['cat_file'],'r')
            tree = etree.XML(catf.read().decode('cp1251'))
            catf.close()
            
            nodes = tree.xpath('/DATAPACKET/ROWDATA/ROW')
            
            root = QgsProject.instance().layerTreeRoot()
            root.removeAllChildren()
            QgsMapLayerRegistry.instance().removeAllMapLayers()

            self.categories = {}
            
            prgrs_interval = int(math.ceil(len(nodes)/25.0))

            f_idx = 0
            position = 75

            for node in nodes:
                chain = node.get('name').split(chr(92))
                self.categories[node.get('id')] = node.get('name')

                # Create sublayers for category
                c_root = UniumPlugin.create_sublayers(root, chain)

                # Create category vector layer
                cat_lyr = self.create_catlyr(uri.uri(),chain[len(chain)-1],int(node.get('id')))
                self.layers[cat_lyr.id()] = {'name': cat_lyr.name(),
                                             'cat_id': node.get('id'),
                                    'subset': cat_lyr.subsetString(),
                                    'path': chr(92).join(chain[:len(chain)-1]),
                                    'full_name':chr(92).join(chain)}
                QgsMapLayerRegistry.instance().addMapLayer(cat_lyr,False)                            
                c_root.addLayer(cat_lyr)
                self.iface.legendInterface().setLayerVisible(cat_lyr, False)
                f_idx+=1
                if f_idx%prgrs_interval == 0:
                    position+=1
                    self.dockwidget.sasprogressBar.setValue(position)
                    qApp.processEvents()
                
            #self.get_layers()
            self.remove_vlayers_as_group()
            self.set_project_settings()
            canvas = self.iface.mapCanvas()
            renderer = canvas.mapRenderer()
            renderer.setDestinationCrs(self.mercator)
            canvas.setMapUnits(0)
            canvas.refresh()
            #self.set_style_to_lyrs()
            self.set_styles()
            renderer.setDestinationCrs(self.mercator)
            canvas.refresh()
            QgsMessageLog.logMessage(u'Слои созданы', level=QgsMessageLog.INFO)
            self.dockwidget.sasprogressBar.setValue(100)
            qApp.processEvents()
        except Exception, err:
            self.iface.messageBar().pushMessage("Error", u"Что-то случилось: %s" % err, level=QgsMessageBar.CRITICAL, duration=7)
            QgsMessageLog.logMessage(u'%s' % err, level=QgsMessageLog.CRITICAL)