Exemple #1
0
 def setServerDb(self, serverAbstractDb):
     self.serverAbstractDb = serverAbstractDb
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     try:
         if self.serverAbstractDb:
             dbList = self.serverAbstractDb.getEDGVDbsFromServer(parentWidget = self.parent)
             dbList.sort()
             self.clear()
             self.addItem(self.tr('Select Database'))
             self.addItems(dbList)
         else:
             self.clear()
             self.abstractDb = None
             return
     except Exception as e:
         QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))
     QApplication.restoreOverrideCursor()
Exemple #2
0
 def on_batchImportPushButton_clicked(self):
     """
     Imports all config files from a folder into dsgtools_admindb. It only works for a single type of config per time.
     """
     fd = QFileDialog()
     folder = fd.getExistingDirectory(caption = self.tr('Select a folder with json files: '))
     if folder == '':
         QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a input folder!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.batchImportSettings(folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(self, self.tr('Success!'), self.widgetName + self.tr(' successfully imported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(self, self.tr('Error!'), self.tr('Error! Problem importing ') + self.widgetName + ': ' + ':'.join(e.args))
Exemple #3
0
 def on_batchExportPushButton_clicked(self):
     """
     Exports all configs from dsgtools_admindb.
     """
     fd = QFileDialog()
     folder = fd.getExistingDirectory(caption = self.tr('Select a folder to output'))
     if folder == '':
         QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a output!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.batchExportSettings(folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(self, self.tr('Success!'), self.widgetName + self.tr(' successfully exported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(self, self.tr('Error!'), self.tr('Error! Problem exporting ') + self.widgetName + ': ' + ':'.join(e.args))
Exemple #4
0
    def _loadTablePreview(self, table, limit=False):
        """ if has geometry column load to map canvas """
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.setRenderFlag(False)
        newLayerId = None

        if table.geomType:
            # limit the query result if required
            if limit and table.rowCount > 1000:
                uniqueField = table.getValidQGisUniqueFields(True)
                if uniqueField is None:
                    self.parent.tabs.setCurrentWidget(self.parent.info)
                    self.parent.infoBar.pushMessage(
                        QApplication.translate(
                            "DBManagerPlugin",
                            "Unable to find a valid unique field"),
                        QgsMessageBar.WARNING,
                        self.parent.iface.messageTimeout())
                    return

                uri = table.database().uri()
                uri.setDataSource(
                    "", u"(SELECT * FROM %s LIMIT 1000)" % table.quotedName(),
                    table.geomColumn, "", uniqueField.name)
                provider = table.database().dbplugin().providerName()
                vl = QgsVectorLayer(uri.uri(), table.name, provider)
            else:
                vl = table.toMapLayer()

            if not vl.isValid():
                self.setLayerSet([])
            else:
                newLayerId = vl.id() if hasattr(vl, 'id') else vl.id()
                self.setLayerSet([QgsMapCanvasLayer(vl)])
                QgsMapLayerRegistry.instance().addMapLayers([vl], False)
                self.zoomToFullExtent()

        # remove old layer (if any) and set new
        if self.currentLayerId:
            QgsMapLayerRegistry.instance().removeMapLayers(
                [self.currentLayerId], False)
        self.currentLayerId = newLayerId

        self.setRenderFlag(True)
        QApplication.restoreOverrideCursor()
Exemple #5
0
 def executeProcess(self, process):
     """
     Executes a process by its name
     processName: process name
     """
     #checking for running processes
     processName = self.processDict[process]
     runningProc = None
     try:
         runningProc = self.postgisDb.getRunningProc()
     except Exception as e:
         QgsMessageLog.logMessage(':'.join(e.args), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
         return 0
         
     #if there is a running process we should stop
     QApplication.restoreOverrideCursor()
     if runningProc != None:
         if not QtGui.QMessageBox.question(self.iface.mainWindow(), self.tr('Question'),  self.tr('It seems that process {0} is already running. Would you like to ignore it and start another process?').format(process), QtGui.QMessageBox.Ok|QtGui.QMessageBox.Cancel) == QtGui.QMessageBox.Ok:
             QgsMessageLog.logMessage(self.tr('Unable to run process {0}. Process {1} is already running.\n').format(process, runningProc), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
             return 0
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     currProc = self.instantiateProcessByName(processName, False)
     #checking for existing pre process
     preProcessName = currProc.preProcess()
     if preProcessName:
         self.executeProcess(preProcessName)
     # setting parameters
     if currProc.parameters:
         dlg = ProcessParametersDialog(None, currProc.parameters, None, self.tr('Process parameters setter for process {0}').format(process))
         if dlg.exec_() == 0:
             return -1
         # get parameters
         params = dlg.values
         # adjusting the parameters in the process
         currProc.setParameters(params)
     #check status
     QgsMessageLog.logMessage('Process %s Log:\n' % currProc.getName(), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
     ret = currProc.execute() #run bitch run!
     #status = currProc.getStatus() #must set status
     QgsMessageLog.logMessage('Process ran with status %s\n' % currProc.getStatusMessage(), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
     #checking for existing post process
     postProcessName = currProc.postProcess()
     if postProcessName:
         self.executeProcess(postProcessName)
     return ret
Exemple #6
0
 def test1(self, displayOutputPlace):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     displayOutputPlace.setText("")
     self.boldLine(displayOutputPlace,
                   "Test for " + self.currentHW + " Hardware on USB")
     print "current dir:", os.getcwd()
     os.chdir("../helpers/hexes")
     print "current dir:", os.getcwd()
     print "looking for programming hardware on usb"
     dudeCommand = None
     QApplication.processEvents(
     )  #this makes the UI update before going on.
     if self.opSys == "NIX" and self.currentHW == "Waltech":
         dudeCommand = self.testWaltechNIX(displayOutputPlace)
     if self.opSys == "WIN" and self.currentHW == "Waltech":
         dudeCommand = self.testWaltechWIN(displayOutputPlace)
     if self.opSys == "MAC" and self.currentHW == "Waltech":
         dudeCommand = self.testWaltechMAC(displayOutputPlace)
     if self.opSys == "NIX" and self.currentHW == "ArduinoUno":
         dudeCommand = self.testArduinoUnoNIX(displayOutputPlace)
     if self.opSys == "WIN" and self.currentHW == "ArduinoUno":
         dudeCommand = self.testArduinoUnoWIN(displayOutputPlace)
     if self.opSys == "MAC" and self.currentHW == "ArduinoUno":
         dudeCommand = self.testArduinoUnoMAC(displayOutputPlace)
     if self.opSys == "NIX" and self.currentHW == "ArduinoMega":
         dudeCommand = self.testArduinoMegaNIX(displayOutputPlace)
     if self.opSys == "WIN" and self.currentHW == "ArduinoMega":
         dudeCommand = self.testArduinoMegaWIN(displayOutputPlace)
     if self.opSys == "MAC" and self.currentHW == "ArduinoMega":
         dudeCommand = self.testArduinoMegaMAC(displayOutputPlace)
     if self.opSys == "NIX" and self.currentHW == "ArduinoNano":
         dudeCommand = self.testArduinoNanoNIX(displayOutputPlace)
     if self.opSys == "WIN" and self.currentHW == "ArduinoNano":
         dudeCommand = self.testArduinoNanoWIN(displayOutputPlace)
     if self.opSys == "MAC" and self.currentHW == "ArduinoNano":
         dudeCommand = self.testArduinoNanoMAC(displayOutputPlace)
     os.chdir("../")
     time.sleep(1)
     QApplication.restoreOverrideCursor()
     os.chdir("../")
     print "current dir:", os.getcwd()
     os.chdir("./program")
     print "current dir:", os.getcwd()
     if "program" not in os.getcwd(): print "worng place"
     return dudeCommand
Exemple #7
0
    def activate(self):
        """
        Called by QGIS whenever the tool is activated.
        """

        # A dict of layers
        #  and for each layer the fields to use as foreign key
        #  as well as the possible target layers
        # Reaches can be connected to reaches and nodes
        # Catchment areas only to nodes
        self.network_element_sources = {
            QgepLayerManager.layer('vw_qgep_reach'): {
                'fields': [
                    ('rp_to_fk_wastewater_networkelement',
                     QCoreApplication.translate('QgepMapToolConnectNetworkElements', 'Reach Point To')),
                    ('rp_from_fk_wastewater_networkelement',
                     QCoreApplication.translate('QgepMapToolConnectNetworkElements', 'Reach Point From'))
                ],
                'target_layers': [
                    QgepLayerManager.layer('vw_wastewater_node'),
                    QgepLayerManager.layer('vw_qgep_reach')
                ]},
            QgepLayerManager.layer('od_catchment_area'): {'fields': [
                ('fk_wastewater_networkelement_rw_current', QCoreApplication.translate(
                    'QgepMapToolConnectNetworkElements', 'Rainwater current')),
                ('fk_wastewater_networkelement_rw_planned', QCoreApplication.translate(
                    'QgepMapToolConnectNetworkElements', 'Rainwater planned')),
                ('fk_wastewater_networkelement_ww_current', QCoreApplication.translate(
                    'QgepMapToolConnectNetworkElements', 'Wastewater current')),
                ('fk_wastewater_networkelement_ww_planned', QCoreApplication.translate(
                    'QgepMapToolConnectNetworkElements', 'Wastewater planned'))
            ],
                'target_layers': [
                QgepLayerManager.layer('vw_wastewater_node')
            ]}
        }

        self.setSnapLayers(self.source_snapper,
                           self.network_element_sources.keys())

        self.reset()

        self.action.setChecked(True)

        self.iface.mapCanvas().setCursor(QCursor(Qt.CrossCursor))
Exemple #8
0
 def load_survey_data(self):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     try:
         # liberate some memory before loading new data
         self.reset_aggregate()
         gc.collect()
         fname = CONF.get('paths', 'survey_data/file')
         self.survey = DataTable(InputTable, survey_data=fname)
         self._dataframe_widget.set_dataframe(self.survey.table)
         return True
     except Exception, e:
         self.aggregate_enabled = False
         QMessageBox.warning(
             self, u"Impossible de lire les données",
             u"OpenFisca n'a pas réussi à lire les données d'enquête et passe en mode barème. L'erreur suivante a été renvoyé:\n%s\n\nVous pouvez charger des nouvelles données d'enquête dans Fichier>Paramètres>Chemins>Données d'enquête"
             % e)
         self.emit(SIGNAL('baremeOnly()'))
         return False
Exemple #9
0
    def get_contrib(self):
        QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            ExtraSources().load_contrib_pack()
            QgsApplication.restoreOverrideCursor()
            info_message = self.tr(
                'Last version of contrib pack was downloaded!')
            QMessageBox.information(self, PluginSettings.product_name(),
                                    info_message)

            self.dsManagerViewModel.resetModel()
        except:
            QgsApplication.restoreOverrideCursor()
            error_message = self.tr('Error on getting contrib pack: %s %s') % (
                sys.exc_type, sys.exc_value)
            QMessageBox.critical(self, PluginSettings.product_name(),
                                 error_message)
Exemple #10
0
def doSVNCommit(plugin, client, path):
    " Performs SVN commit "

    # The path could be a single file (buffer or project browser) or
    # a directory

    QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
    try:
        if path.endswith(os.path.sep):
            # This is a directory. Path lists should be built.
            statuses = plugin.getLocalStatus(path, pysvn.depth.infinity)
            if type(statuses) != list:
                logging.error("Error checking local SVN statuses for " + path)
                QApplication.restoreOverrideCursor()
                return

            pathsToCommit = []
            pathsToIgnore = []
            for item in statuses:
                if item[1] in COMMIT_ALLOW_STATUSES:
                    pathsToCommit.append(item)
                elif item[1] in IGNORE_STATUSES + [plugin.NOT_UNDER_VCS]:
                    pathsToIgnore.append(item)

            if not pathsToCommit:
                logging.info("No paths to commit for " + path)
                QApplication.restoreOverrideCursor()
                return
        else:
            # This is a single file
            status = plugin.getLocalStatus(path)
            if status not in COMMIT_ALLOW_STATUSES:
                logging.error("Cannot commit " + path +
                              " due to unexpected SVN status")
                QApplication.restoreOverrideCursor()
                return
            pathsToCommit = [
                (path, status),
            ]
            pathsToIgnore = []
    except Exception, exc:
        logging.error(str(exc))
        QApplication.restoreOverrideCursor()
        return
Exemple #11
0
    def __init__(self, canvas, layers, snapradius=2):
        MapTool.__init__(self, canvas, layers)
        self.canvas = canvas
        self.radius = snapradius

        self.band = QgsRubberBand(self.canvas)
        self.band.setColor(QColor.fromRgb(224, 162, 16))
        self.band.setWidth(3)

        self.cursor = QCursor(
            QPixmap([
                "16 16 3 1", "      c None", ".     c #FF0000",
                "+     c #FFFFFF", "                ", "       +.+      ",
                "      ++.++     ", "     +.....+    ", "    +.     .+   ",
                "   +.   .   .+  ", "  +.    .    .+ ", " ++.    .    .++",
                " ... ...+... ...", " ++.    .    .++", "  +.    .    .+ ",
                "   +.   .   .+  ", "   ++.     .+   ", "    ++.....+    ",
                "      ++.++     ", "       +.+      "
            ]))
Exemple #12
0
    def propagateEventUnderConnectionWidget(self, connection, event):
        """ This function propagates an event to one of it's children.
        
        If a connection widget is clicked in an area where it does not draw the connection line, the event should be forwarded to the underlying widget if there is such one.
        However the default behavior of Qt is to propagate the event to the connection's parent. This should be an ConnectableWidgetOwner object.
        This function is a workaround searching for any child widget at event.pos() which is not the initial connection.
        If it finds such a widget a new event with correct position in the new widget's own frame is created and sent to the widget.
        This function calls grabMouse() on the found child. The child should make sure releaseMouse() will be called e.g. in mouseReleaseEvent().

        Currently supported events: QEvent.MouseButtonPress, QEvent.MouseButtonDblClick.
        """
        logging.debug("%s: propagateEventUnderConnectionWidget() - %s" %
                      (self.__class__.__name__, str(event.type())))

        workspacePos = connection.mapToParent(event.pos())
        for child in reversed(self.children()):
            if not child == connection and isinstance(
                    child,
                    QWidget) and child.geometry().contains(workspacePos):
                # do not forward event to connections which do not cross the mouse click point, this is important to prevent infinite loop error
                if isinstance(child, PortConnection
                              ) and not child.belongsToRoute(workspacePos):
                    continue
#                if event.type() == QEvent.MouseButtonDblClick or \
#                    event.type() == QEvent.MouseButtonPress or \
#                    event.type() == QEvent.MouseButtonRelease or \
#                    event.type() == QEvent.MouseMove or \
#                    event.type() == QEvent.DragEnter or \
#                    event.type() == QEvent.Drop:

                childPos = child.mapFromParent(workspacePos)
                grandChild = child.childAt(childPos)
                if grandChild:
                    child = grandChild
                    childPos = child.mapFromParent(childPos)
                if event.type() == QEvent.MouseButtonPress:
                    child.grabMouse(QCursor(Qt.ClosedHandCursor))
                    child.setFocus()
                newEvent = QMouseEvent(event.type(), childPos, event.button(),
                                       event.buttons(), event.modifiers())
                QCoreApplication.instance().sendEvent(child, newEvent)
                return True
        return False
 def on_importPushButton_clicked(self):
     """
     Imports a property file into dsgtools_admindb
     """
     fd = QFileDialog()
     widgetType = self.getWhoAmI()
     filename = fd.getOpenFileName(caption=self.captionDict[widgetType],filter=self.filterDict[widgetType])
     if filename == '':
         QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a file to import!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.importSetting(filename)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(self, self.tr('Success!'), self.widgetName + self.tr(' successfully imported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(self, self.tr('Error!'), self.tr('Error! Problem importing ') +self.widgetName + ': '  + ':'.join(e.args))
     self.refresh()
Exemple #14
0
    def mouseMoveEvent(self, event):

        dx = event.x() - self.lastpos.x()
        dy = event.y() - self.lastpos.y()

        if not self.zoom_mode:
            if event.buttons() == Qt.LeftButton:
                a = self.normalizeAngle(self.xrot + 8 * dy)
                b = self.normalizeAngle(self.yrot + 8 * dx)
                self.xrot = a  #self.xrot + 8 * dy
                self.yrot = b  #self.yrot + 8 * dx

            if event.buttons() == Qt.RightButton:
                self.setCursor(QCursor(Qt.ClosedHandCursor))
                self.trans_y -= dy / 5
                self.trans_x += dx / 5

            self.lastpos = QPoint(event.pos())
            self.updateGL()
 def revokeSelectedPermission(self):
     permissionName = self.permissionTreeWidget.currentItem().text(2)
     dbName = self.permissionTreeWidget.currentItem().parent().text(1)
     userName = self.permissionTreeWidget.currentItem().parent().parent(
     ).text(0)
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.permissionManager.revokePermission(dbName, permissionName,
                                                 userName)
         QApplication.restoreOverrideCursor()
         QMessageBox.warning(
             self, self.tr('Revoke Complete!'),
             self.tr('Revoke for user ') + userName +
             self.tr(' on profile ') + permissionName +
             self.tr(' of database ') + dbName + self.tr(' complete.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.warning(self, self.tr('Error!'), ':'.join(e.args))
     self.refresh()
Exemple #16
0
    def _get_csw(self):
        """convenience function to init owslib.csw.CatalogueServiceWeb"""

        # connect to the server
        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.catalog = CatalogueServiceWeb(self.catalog_url,
                                               timeout=self.timeout)
            return True
        except ExceptionReport as err:
            msg = self.tr('Error connecting to service: %s') % err
        except ValueError as err:
            msg = self.tr('Value Error: %s') % err
        except Exception as err:
            msg = self.tr('Unknown Error: %s') % err

        QMessageBox.warning(self, self.tr('CSW Connection error'), msg)
        QApplication.restoreOverrideCursor()
        return False
Exemple #17
0
    def update_view(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        if not self.selected_vars:
            self.view.clear()
            QApplication.restoreOverrideCursor()
            return

        cols = self.selected_vars
        df = self.data[list(cols)]
        self.view.set_dataframe(df)

        #        by_var_label = self.var2label[by_var]
        #        dist_frame.insert(0,by_var_label,u"")
        #        enum = self.var2enum[by_var]
        #        dist_frame[by_var_label] = dist_frame[by_var].apply(lambda x: enum._vars[x])
        #        dist_frame.pop(by_var)
        self.view.reset()
        self.update_btns()
        QApplication.restoreOverrideCursor()
Exemple #18
0
    def __process(self):
        " Runs profiling session and waits till it ends, fails or is cancelled "

        self.__inProgress = True
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        sock, port = createDoneFeedbackSocket()

        params = GlobalData().getRunParameters(self.__scriptName)
        workingDir, cmd, environment = getCwdCmdEnv(CMD_TYPE_PROFILE,
                                                    self.__scriptName, params,
                                                    Settings().terminalType,
                                                    port)
        try:
            # profProc =
            Popen(cmd, shell=True, cwd=workingDir, env=environment)
        except Exception, exc:
            self.__onError(str(exc))
            return
Exemple #19
0
 def on_dropDatabasePushButton_clicked(self):
     selectedDbNameList = self.getSelectedDbList()
     if len(selectedDbNameList) == 0:
         QMessageBox.warning(
             self, self.tr('Warning'),
             self.tr('Please select one or more databases to drop!'))
     if QtGui.QMessageBox.question(
             self, self.tr('Question'),
             self.tr('Do you really want to drop databases: ') +
             ', '.join(selectedDbNameList), QtGui.QMessageBox.Ok
             | QtGui.QMessageBox.Cancel) == QtGui.QMessageBox.Cancel:
         return
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     successList, exceptionDict = self.batchDropDbs(selectedDbNameList)
     QApplication.restoreOverrideCursor()
     self.setDatabases()
     header = self.tr('Drop operation complete. \n')
     self.outputMessage(header, successList, exceptionDict)
     self.dbsCustomSelector.setInitialState(self.dbsCustomSelector.fromLs)
    def update_output(self, output_data, description=None):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        if output_data is None:
            return
        self.set_data(output_data)

        if description is not None:
            self.set_distribution_choices(description)

        if not hasattr(self, 'distribution_by_var'):
            self.distribution_by_var = 'typmen15'

        by_var = self.distribution_by_var

        V = []
        M = []
        B = []
        for var in self.varlist:
            montant, benef = self.get_aggregate(var)
            V.append(var)
            M.append(montant)
            B.append(benef)

        items = [(u'Mesure', V), (u"Dépense\n(millions d'€)", M),
                 (u"Bénéficiaires\n(milliers de ménages)", B)]
        aggr_frame = DataFrame.from_items(items)
        self.aggregate_view.set_dataframe(aggr_frame)

        dist_frame = self.group_by(['revdisp', 'nivvie'], by_var)
        by_var_label = self.var2label[by_var]
        dist_frame.insert(0, by_var_label, u"")
        enum = self.var2enum[by_var]
        dist_frame[by_var_label] = dist_frame[by_var].apply(
            lambda x: enum._vars[x])

        dist_frame.pop(by_var)

        self.distribution_view.set_dataframe(dist_frame)
        self.distribution_view.reset()
        self.calculated()
        QApplication.restoreOverrideCursor()
Exemple #21
0
    def populateWidgetWithSingleValue(self):
        if self.allTablesCheckBox.checkState() == 2 or (
                self.allAttributesCheckBox.checkState() == 2
                and self.schemaComboBox.currentIndex() <> 0
                and self.tableComboBox.currentIndex() <> 0):
            self.attributeComboBox.clear()
            self.attributeComboBox.setEnabled(False)
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.singleValueComboBox.clear()
            self.singleValueComboBox.addItem(
                self.tr('Select a value to alter'))
            if self.allAttributesCheckBox.checkState() == 2:
                tableList = [self.tableComboBox.currentText()]
            else:
                tableList = self.domainDict.keys()
            allValueList = []
            idxList = []
            for tableName in tableList:
                for attrName in self.domainDict[tableName]['columns'].keys():
                    for code in self.domainDict[tableName]['columns'][
                            attrName]['values']:
                        value = self.domainDict[tableName]['columns'][
                            attrName]['values'][code]
                        if value not in allValueList:
                            allValueList.append(value)

            for value in allValueList:
                for tableName in tableList:
                    for attrName in self.domainDict[tableName]['columns'].keys(
                    ):
                        if value not in self.domainDict[tableName]['columns'][
                                attrName]['values'].values():
                            idx = allValueList.index(value)
                            if idx not in idxList:
                                idxList.append(idx)
            idxList.sort(reverse=True)
            for idx in idxList:
                allValueList.pop(idx)
            for value in allValueList:
                self.singleValueComboBox.addItem(value)
            self.populateInheritanceTree(tableList)
            QApplication.restoreOverrideCursor()
Exemple #22
0
    def burnHex(self, displayOutputPlace):
        import os
        import subprocess
        from subprocess import PIPE
        import sys
        import os
        import time
        from tester import tester

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        filename = ntpath.basename(self.__class__.projectName)
        os.chdir(self.__class__.helpDir)
        if self.commandAvrDude != None:
            displayOutputPlace.append("checking port and programming")
            commandwfile = self.commandAvrDude + " -U flash:w:" + self.__class__.currentFileDir + r"/" + filename + ".hex:i"
            print "command", commandwfile
            p = subprocess.Popen(commandwfile,
                                 shell=True,
                                 stdout=PIPE,
                                 stderr=PIPE)
            while p.poll() is None:  # polls to se`e if the programming is done
                time.sleep(0.5)
            print "P outut:", p.communicate()
            if p.returncode != 0:
                displayOutputPlace.append("upload failed")
            if p.returncode == 0:
                displayOutputPlace.append("Hex file uploaded")
            else:
                print("progrmming error")
            """
            #p = subprocess.Popen(commandwfile,stdout = subprocess.PIPE, stderr= subprocess.PIPE,shell=True).communicate()
               
            #output,error =p
            #print"avrdude errstream", error
            """
        if self.commandAvrDude == None:
            displayOutputPlace.append("Hardware: " + currentHW + " Not found")
        QApplication.restoreOverrideCursor()
        os.chdir(self.__class__.pyDir)
        #delete all temp files:
        #os.unlink(f.name)
        """"
 def on_saveButton_clicked(self):
     profileName, edgvVersion = self.profilesListWidget.currentItem().text(
     ).split(' (')
     edgvVersion = edgvVersion.replace(')', '')
     newProfileDict = self.makeProfileDict()
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.permissionManager.updateSetting(profileName, edgvVersion,
                                              newProfileDict)
         QApplication.restoreOverrideCursor()
         QMessageBox.warning(
             self, self.tr('Success!'),
             self.tr('Permission ') + profileName +
             self.tr(' successfully updated.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.warning(
             self, self.tr('Warning!'),
             self.tr('Error! Problem updating permission: ') +
             ':'.join(e.args))
Exemple #24
0
 def on_buttonBox_accepted(self):
     '''
     Creates view with resolved domain values
     '''
     createViewClause = self.viewTypeDict[
         self.viewTypeComboBox.currentIndex()]
     fromClause = self.inheritanceType[
         self.inheritanceTypeComboBox.currentIndex()]
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.abstractDb.createResolvedDomainViews(createViewClause,
                                                   fromClause)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(
             self, self.tr('Success!'),
             self.tr('Views created successfully on database ') +
             self.dBLineEdit.text())
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))
 def on_batchImportPushButton_clicked(self):
     fd = QFileDialog()
     folder = fd.getExistingDirectory(
         caption=self.tr('Select a folder with permissions: '))
     if folder == '':
         QMessageBox.warning(self, self.tr('Warning!'),
                             self.tr('Error! Select a input folder!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.permissionManager.batchImportSettings(folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.warning(self, self.tr('Success!'),
                             self.tr('Permissions successfully imported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.warning(
             self, self.tr('Warning!'),
             self.tr('Error! Problem importing permission: ') +
             ':'.join(e.args))
Exemple #26
0
 def __init__(self, canvas, layer, Parent):
     QgsMapTool.__init__(self, canvas)
     self.Parent = Parent
     self.canvas = canvas
     self.layer = layer
     self.geom = None
     self.rb = None
     self.x0 = None
     self.y0 = None
     #our own fancy cursor
     self.cursor = QCursor(
         QPixmap([
             "16 16 3 1", "      c None", ".     c #FF0000",
             "+     c #17a51a", "                ", "       +.+      ",
             "      ++.++     ", "     +.....+    ", "    +.  .  .+   ",
             "   +.   .   .+  ", "  +.    .    .+ ", " ++.    .    .++",
             " ... ...+... ...", " ++.    .    .++", "  +.    .    .+ ",
             "   +.   .   .+  ", "   ++.  .  .+   ", "    ++.....+    ",
             "      ++.++     ", "       +.+      "
         ]))
Exemple #27
0
    def __init__(self, qpart, model):
        QListView.__init__(self, qpart.viewport())

        # ensure good selected item background on Windows
        palette = self.palette()
        palette.setColor(palette.Inactive, palette.Highlight,
                         palette.color(palette.Active, palette.Highlight))
        self.setPalette(palette)

        self.setAttribute(Qt.WA_DeleteOnClose)

        self.setItemDelegate(HTMLDelegate(self))

        self._qpart = qpart
        self.setFont(qpart.font())

        self.setCursor(QCursor(Qt.PointingHandCursor))
        self.setFocusPolicy(Qt.NoFocus)

        self.setModel(model)

        self._selectedIndex = -1

        # if cursor moved, we shall close widget, if its position (and model) hasn't been updated
        self._closeIfNotUpdatedTimer = QTimer(self)
        self._closeIfNotUpdatedTimer.setInterval(200)
        self._closeIfNotUpdatedTimer.setSingleShot(True)

        self._closeIfNotUpdatedTimer.timeout.connect(
            self._afterCursorPositionChanged)

        qpart.installEventFilter(self)

        qpart.cursorPositionChanged.connect(self._onCursorPositionChanged)

        self.clicked.connect(lambda index: self.itemSelected.emit(index.row()))

        self.updateGeometry()
        self.show()

        qpart.setFocus()
    def mousePressEvent(self, event):
        """
            Selecting a line.
        """

        if self._parent.crop_extents_model._editable:
            new_pos = self.scene().data2scene.map(event.scenePos())
            width, height = self._parent.dataShape

            positionH = int(new_pos.y() + 0.5)
            positionH = max(0, positionH)
            positionH = min(height, positionH)

            positionV = int(new_pos.x() + 0.5)
            positionV = max(0, positionV)
            positionV = min(width, positionV)

            if self._direction == 'horizontal' and abs(
                    self._parent._vertical0.position -
                    positionV) <= self._line_thickness:
                self.mouseMoveStartH = self._index
                self.mouseMoveStartV = 0
            elif self._direction == 'horizontal' and abs(
                    self._parent._vertical1.position -
                    positionV) <= self._line_thickness:
                self.mouseMoveStartH = self._index
                self.mouseMoveStartV = 1
            elif self._direction == 'vertical' and abs(
                    self._parent._horizontal0.position -
                    positionH) <= self._line_thickness:
                self.mouseMoveStartV = self._index
                self.mouseMoveStartH = 0
            elif self._direction == 'vertical' and abs(
                    self._parent._horizontal1.position -
                    positionH) <= self._line_thickness:
                self.mouseMoveStartV = self._index
                self.mouseMoveStartH = 1

            #  Change the cursor to indicate "currently dragging"
            cursor = QCursor(Qt.ClosedHandCursor)
            QApplication.instance().setOverrideCursor(cursor)
Exemple #29
0
    def refresh_bareme(self):
        # Consistency check on scenario
        msg = self.scenario.check_consistency()
        if msg:
            QMessageBox.critical(self, u"Ménage non valide", msg,
                                 QMessageBox.Ok, QMessageBox.NoButton)
            return False
        # Si oui, on lance le calcul
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.statusbar.showMessage(u"Calcul en cours...")
        self.action_refresh_bareme.setEnabled(False)
        # set the table model to None before changing data
        self._table.clearModel()

        P_default = self._parametres.getParam(defaut=True)
        P_courant = self._parametres.getParam(defaut=False)

        input_table = DataTable(InputTable, scenario=self.scenario)

        population_courant = SystemSf(ModelFrance, P_courant, P_default)
        population_courant.set_inputs(input_table)
        data_courant = gen_output_data(population_courant)

        if self.reforme:
            population_default = SystemSf(ModelFrance, P_default, P_default)
            population_default.set_inputs(input_table)
            data_default = gen_output_data(population_default)
            data_courant.difference(data_default)
        else:
            data_default = data_courant
        self._table.updateTable(data_courant,
                                reforme=self.reforme,
                                mode=self.mode,
                                dataDefault=data_default)
        self._graph.updateGraph(data_courant,
                                reforme=self.reforme,
                                mode=self.mode,
                                dataDefault=data_default)

        self.statusbar.showMessage(u"")
        QApplication.restoreOverrideCursor()
Exemple #30
0
    def __svnStatus(self, path, update):
        " Called to perform svn status "
        settings = self.getSettings()
        client = self.getSVNClient(settings)

        dlg = SVNStatusProgress(self, client, path, update)
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        res = dlg.exec_()
        QApplication.restoreOverrideCursor()

        if res != QDialog.Accepted:
            logging.info("SVN status for '" + path + "' cancelled")
            return

        if len(dlg.statusList) == 0:
            logging.error("Error getting SVN status for '" + path + "'")
            return

        statusDialog = SVNPluginStatusDialog(dlg.statusList)
        statusDialog.exec_()
        return