def open(self):
     fileName = QtGui.QFileDialog.getOpenFileName(self)
     if not fileName.isEmpty():
         inFile = QtCore.QFile(fileName)
         if not inFile.open(QtCore.QFile.ReadOnly):
             QtGui.QMessageBox.warning(
                 self, self.tr("Abrir"),
                 self.tr("Cannot read file %1:\n%2").arg(fileName).arg(
                     inFile.errorString()))
             return
         line = inFile.readLine()
         leerDatos()
         #variable usada para separar las filas impares(traindata) y las pares(testdata)
         i = 0
         self.tDatos.setColumnCount(14)
         self.tDatos.setRowCount(178)
         self.tDatos.setHorizontalHeaderLabels([
             'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10',
             'x11', 'x12', 'x13', 'x14'
         ])
         #tabla de entrenamiento
         self.dTrain.setColumnCount(13)
         self.dTrain.setRowCount(89)
         self.dTrain.setHorizontalHeaderLabels([
             'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10',
             'x11', 'x12', 'x13'
         ])
         #table de pruebas
         self.dTest.setColumnCount(13)
         self.dTest.setRowCount(89)
         self.dTest.setHorizontalHeaderLabels([
             'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9', 'x10',
             'x11', 'x12', 'x13'
         ])
         while line != "":
             line = unicode(line, encoding="UTF-8")
             self.tDatos.setItem(
                 i, 0, QtGui.QTableWidgetItem(line.strip().split(",")[0]))
             self.tDatos.setItem(
                 i, 1, QtGui.QTableWidgetItem(line.strip().split(",")[1]))
             self.tDatos.setItem(
                 i, 2, QtGui.QTableWidgetItem(line.strip().split(",")[2]))
             self.tDatos.setItem(
                 i, 3, QtGui.QTableWidgetItem(line.strip().split(",")[3]))
             self.tDatos.setItem(
                 i, 4, QtGui.QTableWidgetItem(line.strip().split(",")[4]))
             self.tDatos.setItem(
                 i, 5, QtGui.QTableWidgetItem(line.strip().split(",")[5]))
             self.tDatos.setItem(
                 i, 6, QtGui.QTableWidgetItem(line.strip().split(",")[6]))
             self.tDatos.setItem(
                 i, 7, QtGui.QTableWidgetItem(line.strip().split(",")[7]))
             self.tDatos.setItem(
                 i, 8, QtGui.QTableWidgetItem(line.strip().split(",")[8]))
             self.tDatos.setItem(
                 i, 9, QtGui.QTableWidgetItem(line.strip().split(",")[9]))
             self.tDatos.setItem(
                 i, 10, QtGui.QTableWidgetItem(line.strip().split(",")[10]))
             self.tDatos.setItem(
                 i, 11, QtGui.QTableWidgetItem(line.strip().split(",")[11]))
             self.tDatos.setItem(
                 i, 12, QtGui.QTableWidgetItem(line.strip().split(",")[12]))
             self.tDatos.setItem(
                 i, 13, QtGui.QTableWidgetItem(line.strip().split(",")[13]))
             line = inFile.readLine()
             i = i + 1
         i = 0
         f1 = escalarFeaturesInTrain(0)
         f2 = escalarFeaturesInTest(0)
         for k in xrange(89):
             for p in xrange(13):
                 self.dTrain.setItem(i, p,
                                     QtGui.QTableWidgetItem(str(f1[k, p])))
                 self.dTest.setItem(i, p,
                                    QtGui.QTableWidgetItem(str(f2[k, p])))
             i = i + 1
Example #2
0
        datas0['close'] = datas.apply(
            lambda x: 0 if x['close'] < x['open'] else x['volume'], axis=1)
        datas0['low'] = 0
        datas0['high'] = datas['volume']
        datas0['time_int'] = np.array(range(len(datas.index)))
        self.listVol = datas0[['time_int', 'open', 'close', 'low',
                               'high']].to_records(False)
        # 调用画图函数
        self.plotAll(True, 0, len(self.datas))
        self.crosshair.signal.emit((None, None))


########################################################################
# 功能测试
########################################################################
import sys
if __name__ == '__main__':
    app = QApplication(sys.argv)
    # 界面设置
    cfgfile = QtCore.QFile('css.qss')
    cfgfile.open(QtCore.QFile.ReadOnly)
    styleSheet = cfgfile.readAll()
    styleSheet = unicode(styleSheet, encoding='utf8')
    app.setStyleSheet(styleSheet)
    # K线界面
    ui = KLineWidget()
    ui.show()
    ui.KLtitle.setText('rb1701', size='20pt')
    ui.loadData(pd.DataFrame.from_csv('data.csv'))
    app.exec_()
Example #3
0
    def loadTopology(self):
        """
        Load a topology.
        """
        if self.running:
            self.log.append("You cannot load a topology when one is still running!")
            return

        if isinstance(mainWidgets["canvas"], Tutorial):
            self.log.append("You cannot load a topology during the tutorial!")
            return
        
        def loadIntoScene(line):
            scene = self.canvas.scene()
            itemType,arg = line.split(":")
            args = str(arg).strip("()").split(",")

            if itemType == "edge":
                source = scene.findItem(args[0])
                dest = scene.findItem(args[1])
                if source.device_type == "Mobile" or dest.device_type == "Mobile":
                    item = Wireless_Connection(source, dest)
                else:
                    item = Connection(source, dest)
                scene.addItem(item)
            else:
                devType, index = str(itemType).rsplit("_", 1)
                item = deviceTypes[devType]()
                item.setIndex(int(index))
                scene.addItem(item)
                item.setPos(float(args[0]), float(args[1]))
                item.nudge()

            return item

        def loadProperties(itemDict):
            currentInterfaceTarget = None
            currentRouteSubnet = None
            
            for item, properties in itemDict.iteritems():
                for line in properties:
                    count = 0
                    while line.find("\t") == 0:
                        line = line[1:]
                        count += 1

                    prop, value = line.split(":", 1)
                    if count == 1:
                        item.setProperty(prop, value)
                    elif count == 2:
                        currentInterfaceTarget = self.canvas.scene().findItem(value)
                    elif count == 3:
                        item.setInterfaceProperty(prop, value, currentInterfaceTarget)
                    elif count == 4:
                        currentRouteSubnet = value
                        item.addEntry("", "", value, currentInterfaceTarget)
                    elif count == 5:
                        item.setEntryProperty(prop, value, currentRouteSubnet, currentInterfaceTarget)

        filename = self.loadFile("GSAV (*.gsav)")
        if filename.isEmpty():
            return

        file = QtCore.QFile(filename)
        if not file.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, self.tr("Load Error"),
                                      self.tr("Cannot read file %1:\n%2.")
                                      .arg(filename)
                                      .arg(file.errorString()))
            return

        self.newScene()
        self.filename = str(filename)

        _in = QtCore.QTextStream(file)
        QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)

        itemDict = {}
        
        line = str(_in.readLine())
        lines = []
        while not _in.atEnd():
            item = loadIntoScene(line)
            line = str(_in.readLine())
            while line.find("\t") == 0:
                lines.append(line)
                line = str(_in.readLine())
            itemDict[item] = lines
            lines = []

        loadProperties(itemDict)
        
        QtGui.QApplication.restoreOverrideCursor()
        
        self.statusBar().showMessage(self.tr("Loaded '%1'").arg(filename), 2000)
Example #4
0
 def writeFile(self, bound, sideLen, isHexagon, shapefileName, encoding):
     crs = self.iface.mapCanvas().mapRenderer().destinationCrs()
     self.ui.progressBar.setRange(0, 100)
     if not crs.isValid():
         crs = None
     # TSW - 2011-10-11 - row and column fields for adjancency determination when exporting
     # modified to 20,5 for float field to match calc
     fields = {
         0: QgsField("pu_id", QtCore.QVariant.Int),
         1: QgsField("pu_cost", QtCore.QVariant.Double, "real", 19, 10),
         2: QgsField("pu_status", QtCore.QVariant.Double, "real", 19, 10),
         3: QgsField("bnd_cost", QtCore.QVariant.Double, "real", 19, 10),
         4: QgsField("area", QtCore.QVariant.Double, "real", 19, 10),
         5: QgsField("perimeter", QtCore.QVariant.Double, "real", 19, 10),
         6: QgsField("sidelength", QtCore.QVariant.Double, "real", 19, 10)
     }
     check = QtCore.QFile(shapefileName)
     if check.exists():
         if not QgsVectorFileWriter.deleteShapeFile(shapefileName):
             return
     writer = QgsVectorFileWriter(shapefileName, encoding, fields,
                                  QGis.WKBPolygon, crs)
     outFeat = QgsFeature()
     outGeom = QgsGeometry()
     idVar = 0
     if self.ui.cbLimit.isChecked():
         # create spatial index
         tFeat = QgsFeature()
         newFeat = QgsFeature()
         tGeom = QgsGeometry()
         tIndex = QgsSpatialIndex()
         tPv = self.tLayer.dataProvider()
         tPv.select([], QgsRectangle(), True, False)
         while tPv.nextFeature(tFeat):
             tIndex.insertFeature(tFeat)
         # begin creating records
         if not isHexagon:
             # place squares from top left corner
             puArea = float(sideLen)**2
             puPerimeter = float(sideLen) * 4
             y = bound.yMaximum()
             rowCount = int((bound.yMaximum() - bound.yMinimum()) / sideLen)
             row = 1
             while y >= bound.yMinimum():
                 x = bound.xMinimum()
                 while x <= bound.xMaximum():
                     polygon = self.CreateSquare(x, y, sideLen)
                     outFeat.setGeometry(outGeom.fromPolygon(polygon))
                     outFeat.addAttribute(0, QtCore.QVariant(idVar))
                     outFeat.addAttribute(1, QtCore.QVariant(1.0))
                     outFeat.addAttribute(2, QtCore.QVariant(0.0))
                     outFeat.addAttribute(3, QtCore.QVariant(1.0))
                     outFeat.addAttribute(4, QtCore.QVariant(puArea))
                     outFeat.addAttribute(5, QtCore.QVariant(puPerimeter))
                     outFeat.addAttribute(6, QtCore.QVariant(sideLen))
                     # test to see if new feature intersects bounding box of
                     # source extent layer
                     outGeom = QgsGeometry(outFeat.geometry())
                     features = tIndex.intersects(outGeom.boundingBox())
                     for fid in features:
                         # now test if actually intersects
                         tPv.featureAtId(int(fid), tFeat, True, [])
                         tGeom = QgsGeometry(tFeat.geometry())
                         if outGeom.intersects(tGeom):
                             # intersects so add and go on to next new feature
                             writer.addFeature(outFeat)
                             break
                     idVar = idVar + 1
                     x = x + sideLen
                 y = y - sideLen
                 self.ui.progressBar.setValue((row * 100) / rowCount)
                 self.ui.progressBar.repaint()
         else:
             # NOTE each start point needs special calculation
             # because of space between bottom corners of hexagons in a
             # same row or column
             #
             # basic trig to determine placement of hexagons
             angle_a = math.radians(30)
             hyp = sideLen
             side_b = hyp * math.cos(angle_a)
             side_a = hyp * math.sin(angle_a)
             puArea = self.CalculateHexagonArea(sideLen)
             puPerimeter = float(sideLen) * 6
             # place hexagons from within top left corner
             y = bound.yMaximum() - side_b
             rowCount = int((bound.yMaximum() - bound.yMinimum()) / sideLen)
             row = 1
             while y >= bound.yMinimum() - (2 * side_a) - sideLen:
                 if row % 2 == 0:
                     x = bound.xMinimum() + sideLen
                 else:
                     x = bound.xMinimum() - side_a
                 while x <= bound.xMaximum() + sideLen:
                     polygon = self.CreateHexagon(x, y, sideLen)
                     outFeat.setGeometry(outGeom.fromPolygon(polygon))
                     outFeat.addAttribute(0, QtCore.QVariant(idVar))
                     outFeat.addAttribute(1, QtCore.QVariant(1.0))
                     outFeat.addAttribute(2, QtCore.QVariant(0.0))
                     outFeat.addAttribute(3, QtCore.QVariant(1.0))
                     outFeat.addAttribute(4, QtCore.QVariant(puArea))
                     outFeat.addAttribute(5, QtCore.QVariant(puPerimeter))
                     outFeat.addAttribute(6, QtCore.QVariant(sideLen))
                     # test to see if new feature intersects bounding box of
                     # source extent layer
                     outGeom = QgsGeometry(outFeat.geometry())
                     features = tIndex.intersects(outGeom.boundingBox())
                     for fid in features:
                         # now test if actually intersects
                         tPv.featureAtId(int(fid), tFeat, True, [])
                         tGeom = QgsGeometry(tFeat.geometry())
                         if outGeom.intersects(tGeom):
                             # intersects so add and go on to next new feature
                             writer.addFeature(outFeat)
                             break
                     idVar = idVar + 1
                     x = x + (2 * sideLen) + (2 * side_a)
                 y = y - side_b
                 row = row + 1
                 self.ui.progressBar.setValue((row * 100) / rowCount)
                 self.ui.progressBar.repaint()
         self.ui.progressBar.setRange(0, 100)
         tPv = None
     else:
         if not isHexagon:
             # place squares from top left corner
             puArea = float(sideLen)**2
             puPerimeter = float(sideLen) * 4
             y = bound.yMaximum()
             rowCount = int((bound.yMaximum() - bound.yMinimum()) / sideLen)
             row = 1
             while y >= bound.yMinimum():
                 x = bound.xMinimum()
                 while x <= bound.xMaximum():
                     polygon = self.CreateSquare(x, y, sideLen)
                     outFeat.setGeometry(outGeom.fromPolygon(polygon))
                     outFeat.addAttribute(0, QtCore.QVariant(idVar))
                     outFeat.addAttribute(1, QtCore.QVariant(1.0))
                     outFeat.addAttribute(2, QtCore.QVariant(0.0))
                     outFeat.addAttribute(3, QtCore.QVariant(1.0))
                     outFeat.addAttribute(4, QtCore.QVariant(puArea))
                     outFeat.addAttribute(5, QtCore.QVariant(puPerimeter))
                     outFeat.addAttribute(6, QtCore.QVariant(sideLen))
                     # INSERT CODE HERE TO DETERMINE IF INSIDE REFERENCE LAYER
                     writer.addFeature(outFeat)
                     idVar = idVar + 1
                     x = x + sideLen
                 y = y - sideLen
                 self.ui.progressBar.setValue((row * 100) / rowCount)
                 self.ui.progressBar.repaint()
         else:
             # NOTE each start point needs special calculation
             # because of space between bottom corners of hexagons in a
             # same row or column
             #
             # basic trig to determine placement of hexagons
             angle_a = math.radians(30)
             hyp = sideLen
             side_b = hyp * math.cos(angle_a)
             side_a = hyp * math.sin(angle_a)
             puArea = self.CalculateHexagonArea(sideLen)
             puPerimeter = float(sideLen) * 6
             # place hexagons from within top left corner
             y = bound.yMaximum() - side_b
             rowCount = int((bound.yMaximum() - bound.yMinimum()) / sideLen)
             row = 1
             while y >= bound.yMinimum() - (2 * side_a) - sideLen:
                 if row % 2 == 0:
                     x = bound.xMinimum() + sideLen
                 else:
                     x = bound.xMinimum() - side_a
                 while x <= bound.xMaximum() + sideLen:
                     polygon = self.CreateHexagon(x, y, sideLen)
                     outFeat.setGeometry(outGeom.fromPolygon(polygon))
                     outFeat.addAttribute(0, QtCore.QVariant(idVar))
                     outFeat.addAttribute(1, QtCore.QVariant(1.0))
                     outFeat.addAttribute(2, QtCore.QVariant(0.0))
                     outFeat.addAttribute(3, QtCore.QVariant(1.0))
                     outFeat.addAttribute(4, QtCore.QVariant(puArea))
                     outFeat.addAttribute(5, QtCore.QVariant(puPerimeter))
                     outFeat.addAttribute(6, QtCore.QVariant(sideLen))
                     writer.addFeature(outFeat)
                     idVar = idVar + 1
                     x = x + (2 * sideLen) + (2 * side_a)
                 y = y - side_b
                 row = row + 1
                 self.ui.progressBar.setValue((row * 100) / rowCount)
                 self.ui.progressBar.repaint()
         self.ui.progressBar.setRange(0, 100)
     del writer
Example #5
0
    def extract_anvs(self, fname, f_traf_filename):
        """
        Extrai as aeronaves que foram criadas pelo core-gui.

        :param fname:
        :param f_traf_filename:
        :return:
        """

        self.traf_filename_created = False

        # para todas as linhas da tabela...
        self.qtw_trf.setRowCount(0)

        # cria o QFile para o arquivo XML
        l_data_file = QtCore.QFile(fname)
        assert l_data_file is not None

        # abre o arquivo XML
        l_data_file.open(QtCore.QIODevice.ReadOnly)

        # cria o documento XML
        l_xdoc_aer = QtXml.QDomDocument("scenario")
        assert l_xdoc_aer is not None

        l_xdoc_aer.setContent(l_data_file)

        # fecha o arquivo
        l_data_file.close()

        # obtém o elemento raíz do documento
        l_elem_root = l_xdoc_aer.documentElement()
        assert l_elem_root is not None

        l_index = 0

        # cria uma lista com os elementos
        l_node_list = l_elem_root.elementsByTagName("host")

        # para todos os nós na lista...
        for li_ndx in xrange(l_node_list.length()):

            l_element = l_node_list.at(li_ndx).toElement()
            assert l_element is not None

            if "host" != l_element.tagName():
                continue

            # read identification if available
            if l_element.hasAttribute("id"):
                ls_host_id = l_element.attribute("id")

            # obtém o primeiro nó da sub-árvore
            l_node = l_element.firstChild()
            assert l_node is not None

            lv_host_ok = False

            # percorre a sub-árvore
            while not l_node.isNull():
                # tenta converter o nó em um elemento
                l_element = l_node.toElement()
                assert l_element is not None

                # o nó é um elemento ?
                if not l_element.isNull():
                    if "type" == l_element.tagName():
                        if "aircraft" == l_element.text():
                            # faz o parse do elemento
                            lv_host_ok = True

                        else:
                            break

                    if "point" == l_element.tagName():
                        # faz o parse do elemento
                        lf_host_lat = float(l_element.attribute("lat"))
                        lf_host_lng = float(l_element.attribute("lon"))

                # próximo nó
                l_node = l_node.nextSibling()
                assert l_node is not None

            # achou aircraft ?
            if lv_host_ok:
                # cria nova linha na tabela
                self.qtw_trf.insertRow(l_index)

                # node
                self.qtw_trf.setItem(l_index, 0,
                                     QtGui.QTableWidgetItem(str(ls_host_id)))

                # cria doubleSpinBox para latitude
                self.lat = QtGui.QDoubleSpinBox()
                self.lat.setDecimals(4)
                self.lat.setRange(-90., 90.)
                self.lat.setValue(lf_host_lat)
                self.lat.valueChanged.connect(self.valuechange)

                # latitude
                self.qtw_trf.setCellWidget(l_index, 1, self.lat)

                # cria doubleSpinBox para longitude
                self.lng = QtGui.QDoubleSpinBox()
                self.lng.setDecimals(4)
                self.lng.setRange(-180., 180.)
                self.lng.setValue(lf_host_lng)
                self.lng.valueChanged.connect(self.valuechange)

                # longitude
                self.qtw_trf.setCellWidget(l_index, 2, self.lng)

                # cria combo para designador
                self.cb = QtGui.QComboBox()
                self.cb.addItems(["B737", "A380", "AVRO"])
                self.cb.currentIndexChanged.connect(self.selectionchange)

                # designador
                self.qtw_trf.setCellWidget(l_index, 3, self.cb)

                # ssr
                self.qtw_trf.setItem(
                    l_index, 4, QtGui.QTableWidgetItem(str(7001 + l_index)))
                # indicativo
                self.qtw_trf.setItem(
                    l_index, 5,
                    QtGui.QTableWidgetItem("{}X{:03d}".format(
                        str(ls_host_id[:3]).upper(), l_index + 1)))
                # origem
                self.qtw_trf.setItem(l_index, 6,
                                     QtGui.QTableWidgetItem("SBGR"))
                # destino
                self.qtw_trf.setItem(l_index, 7,
                                     QtGui.QTableWidgetItem("SBBR"))

                # cria spinBox para proa
                self.proa = QtGui.QSpinBox()
                self.proa.setRange(0, 360)
                self.proa.setValue(60)
                self.proa.valueChanged.connect(self.valuechange)

                # proa
                self.qtw_trf.setCellWidget(l_index, 8, self.proa)

                # cria spinBox para velocidade
                self.velocidade = QtGui.QSpinBox()
                self.velocidade.setRange(0, 600)
                self.velocidade.setValue(500)
                self.velocidade.valueChanged.connect(self.valuechange)

                # velocidade
                self.qtw_trf.setCellWidget(l_index, 9, self.velocidade)

                # cria spinBox para altitude
                self.altitude = QtGui.QSpinBox()
                self.altitude.setRange(0, 40000)
                self.altitude.setValue(2000)
                self.altitude.valueChanged.connect(self.valuechange)

                # altitude
                self.qtw_trf.setCellWidget(l_index, 10, self.altitude)

                # cria combo para procedimento
                self.prc = QtGui.QComboBox()
                self.prc.addItems([u"trajetória", "espera", "subida"])
                self.prc.currentIndexChanged.connect(self.selectionchange)

                # procedimento
                self.qtw_trf.setCellWidget(l_index, 11, self.prc)

                # incrementa contador de linhas
                l_index += 1

        self.traf_filename = f_traf_filename
Example #6
0
    def upload(self):
        n = self.Name.text()
        if any([(i in n) for i in '"<*>|?/\\:']):
            QtGui.QMessageBox.information(
                self.client, "Invalid Name",
                "The mod name contains invalid characters: /\\<>|?:\"")
            return

#        if not self.updateThumbnail():
#            QtGui.QMessageBox.information(self.client,"No thumbnail",
#                        "There is no thumbnail attached")
#            return

#self.modinfo["name"] = n
#self.modinfo["uid"] = self.UID.text()
#self.modinfo["description"] = self.Description.toPlainText()
#self.modinfo["version"] = int(self.Version.text())

        iconpath = modvault.iconPathToFull(self.modinfo.icon)
        #self.modinfo["name"] = n
        #self.modinfo["uid"] = self.UID.text()
        #self.modinfo["description"] = self.Description.toPlainText()
        #self.modinfo["version"] = int(self.Version.text())

        iconpath = modvault.iconPathToFull(self.modinfo.icon)
        infolder = False
        if iconpath != "" and os.path.commonprefix([
                os.path.normcase(self.modDir),
                os.path.normcase(iconpath)
        ]) == os.path.normcase(self.modDir):  #the icon is in the game folder
            localpath = modvault.fullPathToIcon(iconpath)
            infolder = True
        '''
        if self.oldname.lower() != self.modinfo["name"].lower(): # we need to change the name of the folder correspondingly
            try:
                os.rename(os.path.join(modvault.MODFOLDER, self.oldname),
                          os.path.join(modvault.MODFOLDER, self.modinfo["name"]))
                self.oldname = self.modinfo["name"]
            except:
                QtGui.QMessageBox.information(self.client,"Changing folder name",
                        "Because you changed the mod name, the folder name \
                         has to change as well. This failed.")
                return
            if infolder == True:
                iconpath = "/mods/" + self.modinfo["name"] +"/" + "/".join(localpath.split('/')[3:])
            self.modDir = os.path.join(modvault.MODFOLDER, self.modinfo["name"])
        '''
        if iconpath != "" and not infolder:
            QtGui.QMessageBox.information(
                self.client, "Invalid Icon File",
                "The file %s is not located inside the modfolder. Copy the icon file to your modfolder and change the mod_info.lua accordingly"
                % iconpath)
            return
            '''
            newpath = os.path.join(self.modDir, os.path.split(iconpath)[1])
            f = open(iconpath, 'r')
            data = r.read()
            f.close()
            f = open(newpath, 'w')
            f.write(data)
            f.close()
            iconpath = modvault.fullPathToIcon(newpath)
        elif iconpath != "":
            iconpath = modvault.fullPathToIcon(iconpath)
        '''
        #self.modinfo["icon"] = iconpath

        #if not modvault.updateModInfo(self.modinfo["name"], self.modinfo):
        #    QtGui.QMessageBox.information(self.client,"Error updating Mod Info",
        #                "FAF could not read or write to the mod_info.lua file.")
        #    return

        try:
            temp = tempfile.NamedTemporaryFile(mode='w+b',
                                               suffix=".zip",
                                               delete=False)
            zipped = zipfile.ZipFile(temp, "w", zipfile.ZIP_DEFLATED)
            zipdir(self.modDir, zipped, os.path.basename(self.modDir))
            zipped.close()
            temp.flush()
        except:
            QtGui.QMessageBox.critical(
                self.client, "Mod uploading error",
                "Something went wrong zipping the mod files.")
            return
        qfile = QtCore.QFile(temp.name)

        self.modinfo.big = (self.SizeType.currentIndex() == 1)
        self.modinfo.small = (self.SizeType.currentIndex() == 2)

        #The server should check again if there is already a mod with this name or UID.
        self.client.writeToServer(
            "UPLOAD_MOD",
            "%s.v%04d.zip" % (self.modinfo.name, self.modinfo.version),
            self.modinfo.to_dict(), qfile)
Example #7
0
    def load_xml(self, fs_filename):
        """
        load xml airspace file
        """
        # check input
        # assert f_model

        # read coordinates
        ls_filename = ":/data/" + fs_filename + ".xml"

        l_data_file = QtCore.QFile(ls_filename)
        assert l_data_file is not None

        l_data_file.open(QtCore.QIODevice.ReadOnly)

        if not l_data_file.isOpen():
            # logger
            l_log = logging.getLogger("airspace::load_xml")
            l_log.setLevel(logging.NOTSET)
            l_log.fatal("<E01: failed to open {}".format(ls_filename))

            # abend
            sys.exit(1)

        l_xml_doc = QtXml.QDomDocument("airspace")
        assert l_xml_doc is not None

        if not l_xml_doc.setContent(l_data_file):

            l_data_file.close()

            # logger
            l_log = logging.getLogger("airspace::load_xml")
            l_log.setLevel(logging.NOTSET)
            l_log.fatal("<E02: failed to parse {}".format(ls_filename))

            # abend
            sys.exit(1)

        l_data_file.close()

        l_doc_elem = l_xml_doc.documentElement()
        assert l_doc_elem is not None

        self.__f_variation, lv_ok = l_doc_elem.attribute(
            QtCore.QString("variation"), QtCore.QString("0")).toDouble()
        self.__f_elevation, lv_ok = l_doc_elem.attribute(
            QtCore.QString("elevation"), QtCore.QString("0")).toDouble()

        l_node = l_doc_elem.firstChild()
        assert l_node is not None

        while not l_node.isNull():
            l_element = l_node.toElement()
            assert l_element is not None

            if not l_element.isNull():
                self.__parse_dom_element(l_element)

            l_node = l_node.nextSibling()
            assert l_node is not None
Example #8
0
    def accept(self):
        if self.__model.shpFileInfo[0] == None:
            QtGui.QMessageBox.warning(self, self.tr("File is not specified."),
                                      self.tr("Please choose shape."))
            return

        outFile = QtCore.QFile(self.__model.shpFileInfo[0])
        if outFile.exists():
            if not QgsVectorFileWriter.deleteShapeFile(
                    self.__model.shpFileInfo[0]):
                QtGui.QMessageBox.warning(
                    self, self.tr("Delete error"),
                    self.tr("Can't delete file: " +
                            self.__model.shpFileInfo[0]))
                return

        xAttrIndex = self.attrXCoordComboBox.currentIndex()
        yAttrIndex = self.attrYCoordComboBox.currentIndex()
        azAttrIndex = self.attrAzCoordComboBox.currentIndex()
        distAttrIndex = self.attrDistCoordComboBox.currentIndex()

        geoDataAttributes = self.__model.getGeoDataAttributes(
            xAttrIndex, yAttrIndex, azAttrIndex, distAttrIndex)

        shapeFields = QgsFields()
        for attrName in geoDataAttributes.values():
            shapeFields.append(
                QgsField(attrName, QtCore.QVariant.String, u"", 255))

        crs = QgsCoordinateReferenceSystem(4326)

        shapeFileWriter = QgsVectorFileWriter(self.__model.shpFileInfo[0],
                                              self.__model.shpFileInfo[1],
                                              shapeFields, QGis.WKBPoint, crs)

        skipAllBadPointFlag = False
        for (coord, displacement,
             attributes) in self.__model.getGeoDataIterator(
                 xAttrIndex, yAttrIndex, azAttrIndex, distAttrIndex):
            try:
                (x, y) = recalculateCoordinates(
                    map(lambda x: float(x), coord),
                    map(lambda x: float(x), displacement))
                feature = QgsFeature()
                feature.initAttributes(geoDataAttributes.__len__())

                geometry = QgsGeometry()
                point = QgsPoint(x, y)
                feature.setGeometry(geometry.fromPoint(point))

                for attrCounter in range(geoDataAttributes.__len__()):
                    feature.setAttribute(attrCounter, attributes[attrCounter])

                shapeFileWriter.addFeature(feature)

            except ValueError as ex:
                if skipAllBadPointFlag == False:
                    msgBox = QtGui.QMessageBox(self)
                    msgBox.setWindowTitle(self.tr("Wrong attribute type"))
                    msgBox.setText(
                        "Point has incorrect attribute type. Poit's attributes: "
                        + str(coord) + str(displacement))
                    ignorethisButton = msgBox.addButton(
                        self.tr("Ignore this"), QtGui.QMessageBox.ActionRole)
                    ignoreallButton = msgBox.addButton(
                        self.tr("Ignore all"), QtGui.QMessageBox.ActionRole)
                    msgBox.exec_()
                    if (msgBox.clickedButton() == ignorethisButton):
                        pass
                    elif (msgBox.clickedButton() == ignoreallButton):
                        skipAllBadPointFlag = True
                else:
                    pass

        del shapeFileWriter

        newLayer = QgsVectorLayer(
            self.__model.shpFileInfo[0],
            QtCore.QFileInfo(self.__model.shpFileInfo[0]).baseName(), "ogr")
        QgsMapLayerRegistry.instance().addMapLayer(newLayer)

        self.close()
Example #9
0
 def setupModelData(self, filename):
     file = QtCore.QFile(filename)
     file.open(QtCore.QFile.ReadOnly)
     self.xml.setDevice(file)
     self.read()
    def creerFichierIN(self):
        #creation du fichier de sauvegarde
        self.nomFichierIN = QtGui.QFileDialog.getSaveFileName(
            self, self.tr("Sauvegarde des resultats "), "", self.tr("(*.in)"))

        ##        if len(str(self.nomFichierIN.split("/")[-1][:-3]))== 8:

        file = QtCore.QFile(self.nomFichierIN)

        if not (file.open(QtCore.QIODevice.WriteOnly | QtCore.QIODevice.Text)):
            return
        #lecture des types de pousse
        listTypePousse = []

        for i in range(3, len(self.matriceData), 2):
            listTypePousse.append(self.matriceData[i][7])
        #on ne garde q'un seul type de  chaque
        listTypePousse = list(set(listTypePousse))
        listTypePousse.sort()
        #Correspondance pousse-code
        ##        dico = {}
        ##        indice=0
        ##        print "len(listTypePousse)", len(listTypePousse)
        ##        for i in range(len(listTypePousse)):
        ##            if listTypePousse[i]!=None:
        ##                indice+=1
        ##                dico[str(listTypePousse[i])]=indice
        dico = {'BA': 0, 'BF': 1, 'PC': 2, 'PL': 3, 'VC': 4, 'VL': 5}
        #debut d'ecriture dans le fichier IN
        entete = 'Xtop	Ytop	Ztop	Xbottom	Ybottom	Zbottom	code	Shoot	Branch	Axe	nbFruit	Longueur'
        file.writeData(entete)
        file.writeData("\n")

        ##        print "len(self.matriceData)",len(self.matriceData)

        for i in range(3, len(self.matriceData), 2):

            ##            print 'i', i
            xtop = str(self.matriceData[i][1])
            ytop = str(self.matriceData[i][2])
            ztop = str(self.matriceData[i][3])
            xbottom = str(self.matriceData[i - 1][1])
            ybottom = str(self.matriceData[i - 1][2])
            zbottom = str(self.matriceData[i - 1][3])
            if self.matriceData[i][7] != None:
                code = dico[str(self.matriceData[i][7])]
##            print i
#calcul des longueurs
            longueur = math.sqrt((float(xtop) - float(xbottom))**2 +
                                 (float(ytop) - float(ybottom))**2 +
                                 (float(ztop) - float(zbottom))**2)
            #valeurs fixes
            branch = 1
            axe = 1
            #si pas de f ruit alors 0 au lieu de None

            if str(self.matriceData[i][8]) == "":
                nbfruit = '0'
            else:
                nbfruit = int(float(str(self.matriceData[i][8])))

            ligne = str(xtop) + '\t' + str(ytop) + '\t' + str(
                ztop) + '\t' + str(xbottom) + '\t' + str(ybottom) + '\t' + str(
                    zbottom) + '\t' + str(code) + '\t' + str(
                        (i - 1) / 2) + '\t' + str(branch) + '\t' + str(
                            axe) + '\t' + str(nbfruit) + '\t' + str(longueur)
            ##            print 'ligne', ligne
            file.writeData(ligne)
            file.writeData("\n")

        file.close()
        #message de fin dans la zone texte
        self.textEdit = self.textEdit + '\n' + self.nomFichierIN + ' : cree'
        self.ui.txEdit.setText(self.textEdit)
        #affichage des correspondance dans la fenetre texte
        self.textEdit = self.textEdit + '\n' + "correspondance pousse-code " + str(
            dico)
        self.ui.txEdit.setText(self.textEdit)
        self.ui.txIN.setText(self.nomFichierIN)
    def creerFichierDAT(self):

        dicoDonneesFixes = {
            'PC': [71.3, 36.5, 0.2597, 0.9338],
            'VC': [73.1, 37.3, 0.3009, 0.5961],
            'VL': [45.6, 21, 0.2041, 1.3438],
            'BA': [93.1, 30.9, 0.5218, -0.201],
            'PL': [2.2, 26, 0.1632, 1.5096],
            'BF': [93.1, 30.9, 0.5218, -0.201]
        }

        fileName = unicode(
            QtGui.QFileDialog.getSaveFileName(
                self, self.tr("Sauvegarde des resultats"), "",
                self.tr("(*.dat)")))
        ##        self.nomFichierDAT = QtGui.QFileDialog.getSaveFileName (self, self.tr("Fichier DAT"),
        ##                                                "",
        ##                                                self.tr("(*.dat)"))
        file = QtCore.QFile(fileName)
        if not (file.open(QtCore.QIODevice.WriteOnly | QtCore.QIODevice.Text)):
            return
        for pousse in self.listTypePousse:
            file.writeData(str(pousse) + '\t')
        file.writeData('! Entity')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoDataPousse[pousse][0]) + '\t')
        file.writeData('! slope Number of Leaves=f(Length)')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoDataPousse[pousse][1]) + '\t')
        file.writeData('! intercept Number of Leaves=f(Length)')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoDataPousse[pousse][3]) + '\t')
        file.writeData('! slope Shoot leaf area=f(Length)')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoDataPousse[pousse][4]) + '\t')
        file.writeData('! intercept Shoot leaf area=f(Length)')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(dicoDonneesFixes[pousse][0]) + '\t')
        file.writeData('! Mean slope petiole angle')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(dicoDonneesFixes[pousse][1]) + '\t')
        file.writeData('! Std-deviation petiole angle')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(dicoDonneesFixes[pousse][2]) + '\t')
        file.writeData('! slope petiole length=f(Leaf length)')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(dicoDonneesFixes[pousse][3]) + '\t')
        file.writeData('! intercept petiole length=f(Leaf length)')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoDataFeuille[pousse][2]) + '\t')
        file.writeData('! slope Leaf area = f(Midrib length?)')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoDataFeuille[pousse][4]) + '\t')
        file.writeData('! slope Leaf width =f(Leaf length)')
        file.writeData('\t' + "\n")

        #----------------------------Debut Roulis---------------------------------------
        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][0]) + '\t')
        file.writeData('! -180/-165' + '\t' + 'Roulis')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][1]) + '\t')
        file.writeData('! -165/-150')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][2]) + '\t')
        file.writeData('! -150/-135')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][3]) + '\t')
        file.writeData('! -135/-120')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][4]) + '\t')
        file.writeData('! -120/-105')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][5]) + '\t')
        file.writeData('! -105/-90')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][6]) + '\t')
        file.writeData('! -90/-75')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][7]) + '\t')
        file.writeData('! -75/-60')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][8]) + '\t')
        file.writeData('! -60/-45')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][9]) + '\t')
        file.writeData('! -45/-30')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][10]) + '\t')
        file.writeData('! -30/-15')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][11]) + '\t')
        file.writeData('! -15/0')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][12]) + '\t')
        file.writeData('! 0/15')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][13]) + '\t')
        file.writeData('! 15/30')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][14]) + '\t')
        file.writeData('! 30/45')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][15]) + '\t')
        file.writeData('! 45/60')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][15]) + '\t')
        file.writeData('! 60/75')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][16]) + '\t')
        file.writeData('! 75/90')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][17]) + '\t')
        file.writeData('! 90/105')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][18]) + '\t')
        file.writeData('! 105/120')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][19]) + '\t')
        file.writeData('! 120/135')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][20]) + '\t')
        file.writeData('! 135/150')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][21]) + '\t')
        file.writeData('! 150/165')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoRoulis[pousse][22]) + '\t')
        file.writeData('! 165/180')
        file.writeData('\t' + "\n")
        #----------------------------Fin Roulis---------------------------------------
        #----------------------------Debut Inclinaison--------------------------------
        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][0]) + '\t')
        file.writeData('! -90/-75' + '\t' + 'Elevation')

        file.writeData('\t' + "\n")
        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][1]) + '\t')
        file.writeData('! -75/-60')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][2]) + '\t')
        file.writeData('! -60/-45')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][3]) + '\t')
        file.writeData('! -45/-30')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][4]) + '\t')
        file.writeData('! -30/-15')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][5]) + '\t')
        file.writeData('! -15/0')
        file.writeData("\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][6]) + '\t')
        file.writeData('! 0/15')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][7]) + '\t')
        file.writeData('! 15/30')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][8]) + '\t')
        file.writeData('! 30/45')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][9]) + '\t')
        file.writeData('! 45/60')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][10]) + '\t')
        file.writeData('! 60/75')
        file.writeData('\t' + "\n")

        for pousse in self.listTypePousse:
            file.writeData(str(self.DicoInclin[pousse][11]) + '\t')
        file.writeData('! 75/90')
        file.writeData('\t' + "\n")

        #----------------------------Fin Inclinaison--------------------------------
        file.close()
        self.textEdit = self.textEdit + '\n' + fileName + ' : cree'
        self.ui.txEdit.setText(self.textEdit)

        self.ui.txDAT.setText(fileName)
        self.nomFichierDAT = fileName
Example #12
0
    def set_model_data(self, editor, model, index):
        text = QtCore.QString.fromLocal8Bit(editor.text())
        if editor.dialogResult() == QtGui.QDialog.Rejected: return False

        decoder = lambda qstr: qstr.toPyObject().toLocal8Bit().data(
        ) if qstr.toPyObject() is not None else None
        item = index.model()
        fileDataAttr = decoder(
            item.data(index, ObjectModelViewConstants.FileDataAttributeRole))
        fileFormatAttr = decoder(
            item.data(index, ObjectModelViewConstants.FileFormatAttributeRole))

        indexObj = index.sibling(index.row(), 0)
        obj = item.data(indexObj,
                        ObjectModelViewConstants.ItemObjectRole).toPyObject()
        assert ObjectModelViewUtils.test_attribute(obj, fileDataAttr)
        assert ObjectModelViewUtils.test_attribute(obj, fileFormatAttr)

        if not text:
            return False

        fi = QtCore.QFileInfo(text)
        fileExt = fi.suffix()
        acceptableFormats = item.data(
            index, ObjectModelViewConstants.FileAcceptableFormatsRole)
        acceptableFormats = acceptableFormats.toPyObject()
        if acceptableFormats is not None:
            found = False
            fileFormatEntityExtAttribute = decoder(
                item.data(
                    index,
                    ObjectModelViewConstants.FileFormatEntityExtAttributeRole))
            assert fileFormatEntityExtAttribute is not None
            for format in acceptableFormats:
                assert ObjectModelViewUtils.test_attribute(
                    format, fileFormatEntityExtAttribute)
                ext = ObjectModelViewUtils.get_attribute(
                    format, fileFormatEntityExtAttribute)
                if ext.upper() == fileExt.toUtf8().data().upper():
                    ObjectModelViewUtils.set_attribute(obj, fileFormatAttr,
                                                       format)
                    found = True
                    break
            if not found:
                codec = QtCore.QString.fromUtf8
                UiUtils.show_error_without_parent(
                    codec('Ошибка!'),
                    codec('Формат данного файла не поддерживается'))
                return False
        else:
            ObjectModelViewUtils.set_attribute(obj, fileFormatAttr,
                                               fileExt.toLocal8Bit().data())

        f = QtCore.QFile(text)
        f.open(QtCore.QIODevice.ReadWrite)
        ba = f.readAll()
        f.close()

        class wrapper():
            def __init__(self, data):
                self.sanctuary = data

        wrapped_val = wrapper(ba)

        ObjectModelViewUtils.set_attribute(obj, fileDataAttr, ba.data())
        item.setData(index, wrapped_val, ObjectModelViewConstants.ValueRole)
        pixmap = file_icon('.' + fileExt.toUtf8().data())
        item.setData(index, pixmap, QtCore.Qt.DecorationRole)

        return True
Example #13
0
    def set_model_data(self, editor, model, index):  #IGNORE:W0613
        if editor.dialogResult() == QtGui.QDialog.Rejected: return False

        decoder = lambda qstr: qstr.toPyObject().toLocal8Bit().data(
        ) if qstr.toPyObject() is not None else None
        item = index.model()
        imageDataAttr = decoder(
            item.data(index, ObjectModelViewConstants.ImageDataRole))
        imageFormatAttr = decoder(
            item.data(index,
                      ObjectModelViewConstants.ImageFormatAttributeRole))
        imagePreviewAttr = decoder(
            item.data(index,
                      ObjectModelViewConstants.ImagePreviewAttributeRole))
        imageSmallPreviewAttr = decoder(
            item.data(index,
                      ObjectModelViewConstants.ImageSmallPreviewAttributeRole))

        indexObj = index.sibling(index.row(), 0)
        obj = item.data(indexObj,
                        ObjectModelViewConstants.ItemObjectRole).toPyObject()
        #        assert ObjectModelViewUtils.test_attribute(obj, imageDataAttr)
        #        assert ObjectModelViewUtils.test_attribute(obj, imagePreviewAttr)
        #        assert ObjectModelViewUtils.test_attribute(obj, imageFormatAttr)

        text = editor.text()

        fi = QtCore.QFileInfo(text)
        format = fi.suffix()
        format = format.toLocal8Bit().data()
        dfs = [
            df for df in DataPool.document_formats.items
            if df.ext.lower() == format.lower()
        ]
        if len(dfs):
            ObjectModelViewUtils.set_attribute(obj, imageFormatAttr, dfs[0].id)
        else:
            return False

        ba = QtCore.QByteArray()
        f = QtCore.QFile(text)
        f.open(QtCore.QIODevice.ReadWrite)
        ba = f.readAll()
        val = ba

        class wrapper():
            def __init__(self, data):
                self.sanctuary = data

        wrapped_val = wrapper(val)

        ObjectModelViewUtils.set_attribute(obj, imageDataAttr, val.data())
        item.setData(index, wrapped_val, ObjectModelViewConstants.ValueRole)

        pixmap = QtGui.QPixmap()
        ok = pixmap.load(text)
        if ok:
            pixmap = pixmap.scaled(
                UiUtils.compute_new_dimensions(
                    pixmap, ObjectModelViewConstants.PreviewSize.width()),
                QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
            ba = QtCore.QByteArray()
            buffer = QtCore.QBuffer(ba)
            buffer.open(QtCore.QIODevice.WriteOnly)
            pixmap.save(buffer, format)
            ObjectModelViewUtils.set_attribute(obj, imagePreviewAttr,
                                               ba.data())

            pixmap = pixmap.scaled(
                UiUtils.compute_new_dimensions(
                    pixmap,
                    ObjectModelViewConstants.PreviewInGridSize.width()),
                QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
            ba = QtCore.QByteArray()
            buffer = QtCore.QBuffer(ba)
            buffer.open(QtCore.QIODevice.WriteOnly)
            pixmap.save(buffer, format)
            ObjectModelViewUtils.set_attribute(obj, imageSmallPreviewAttr,
                                               ba.data())
        else:
            pixmap = ImageEditorHelper.PreviewNotAvailableImage
            ba = QtCore.QByteArray()
            buffer = QtCore.QBuffer(ba)
            buffer.open(QtCore.QIODevice.WriteOnly)
            pixmap.save(buffer, 'PNG')
            ObjectModelViewUtils.set_attribute(obj, imagePreviewAttr,
                                               ba.data())
            ObjectModelViewUtils.set_attribute(obj, imageSmallPreviewAttr,
                                               ba.data())

        item.setData(index, pixmap, QtCore.Qt.DecorationRole)
Example #14
0
    def startImport(self):

        self.nProcessed = 0
        self.nPayed = 0
        self.nRefused = 0
        self.nNotFound = 0

        zipFileName = forceStringEx(self.edtFileName.text())

        archive = ZipFile(forceString(zipFileName), "r")
        namelist = archive.namelist()
        if len(namelist) != 2:
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'Неожиданное количество файлов в архиве.')
            return
        if namelist[0].startswith('H'):
            hFileName, lFileName = namelist
        elif namelist[1].startswith('H'):
            lFileName, hFileName = namelist
        else:
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'В архиве отсутствует файл с услугами.')
            return
        if not lFileName.startswith('L'):
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'В архиве отсутствует файл с персональными данными.')
            return

        if len(hFileName) < 8:
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'Неверный формат имени файла с услугами')
            return

        outFile = QtCore.QTemporaryFile()
        persOutFile = QtCore.QTemporaryFile()

        if not outFile.open(QtCore.QFile.WriteOnly):
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'Не удаётся открыть временный файл для записи %s:\n%s.' %
                (outFile, outFile.errorString()))
            return
        if not persOutFile.open(QtCore.QFile.WriteOnly):
            QtGui.QMessageBox.warning(
                self, u'Импорт данных из XML',
                u'Не удаётся открыть временный файл для записи %s:\n%s.' %
                (outFile, persOutFile.errorString()))
            return

        self.insurerInfis = hFileName[2:7]

        data = archive.read(hFileName)  #read the binary data
        outFile.write(data)
        outFile.close()
        fileInfo = QtCore.QFileInfo(outFile)

        persData = archive.read(lFileName)
        persOutFile.write(persData)
        persOutFile.close()
        persFileInfo = QtCore.QFileInfo(persOutFile)

        hFile = QtCore.QFile(fileInfo.filePath())
        lFile = QtCore.QFile(persFileInfo.filePath())

        if not hFile.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, u'Импорт данных из XML',
                                  u'Не могу открыть файл для чтения %s:\n%s.' \
                                  % (fileInfo.filePath(), hFile.errorString()))
            return
        if not lFile.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text):
            QtGui.QMessageBox.warning(self, u'Импорт данных из XML',
                                  u'Не могу открыть файл персональных данных для чтения %s:\n%s.' \
                                  % (persFileInfo.filePath(), lFile.errorString()))
            return

        self.labelNum.setText(u'размер источника: ' +
                              str(hFile.size() + lFile.size()))
        self.progressBar.setFormat('%p%')
        self.progressBar.setMaximum(hFile.size() + lFile.size() - 1)

        self.readLFile(lFile)
        self.readHFile(hFile)

        self.stat.setText(
            u'обработано случаев: %d; оплаченых: %d; отказаных: %d; не найдено: %d' % \
            (self.nProcessed, self.nPayed, self.nRefused, self.nNotFound))
        hFile.close()
        lFile.close()
Example #15
0
                        parents.pop()
                        indentations.pop()

                # Append a new item to the current parent's list of children.
                parents[-1].appendChild(TreeItem(columnData, parents[-1]))

            number += 1


if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)

    f = QtCore.QFile(':/default.txt')
    f.open(QtCore.QIODevice.ReadOnly)
    t = f.readAll()
    print t
    print QtCore.QIODevice.ReadOnly

    model = TreeModel(f.readAll())
    print model
    f.close()

    view = QtGui.QTreeView()
    view.setModel(model)
    view.setWindowTitle("Simple Tree Model")
    view.show()
    sys.exit(app.exec_())
Example #16
0
    def __parse_sub_xml(self, fs_sub_pn):
        """
        carrega o arquivo de procedimentos de subida

        @param fs_sub_pn: pathname do arquivo em disco
        """
        # logger
        # M_LOG.info("__parse_sub_xml:>>")

        # check input
        assert fs_sub_pn

        # cria o QFile para o arquivo XML do procedimentos de subida
        l_data_file = QtCore.QFile(fs_sub_pn)
        assert l_data_file is not None

        # abre o arquivo XML do procedimentos de subida
        l_data_file.open(QtCore.QIODevice.ReadOnly)

        # erro na abertura do arquivo ?
        if not l_data_file.isOpen():
            # logger
            l_log = logging.getLogger("CCSubData::__parse_sub_xml")
            l_log.setLevel(logging.CRITICAL)
            l_log.critical(u"<E01: erro na abertura de {}.".format(fs_sub_pn))

            # cria um evento de quit
            l_evt = events.CQuit()
            assert l_evt

            # dissemina o evento
            self.__event.post(l_evt)

            # termina a aplicação
            sys.exit(1)

        # cria o documento XML do procedimento de subida
        l_xdoc_sub = QtXml.QDomDocument("subidas")
        assert l_xdoc_sub is not None

        # erro na carga do documento ?
        if not l_xdoc_sub.setContent(l_data_file):
            # fecha o arquivo
            l_data_file.close()

            # logger
            l_log = logging.getLogger("CCSubData::__parse_sub_xml")
            l_log.setLevel(logging.CRITICAL)
            l_log.critical(u"<E02: falha no parse de {}.".format(fs_sub_pn))

            # cria um evento de quit
            l_evt = events.CQuit()
            assert l_evt

            # dissemina o evento
            self.__event.post(l_evt)

            # termina a aplicação
            sys.exit(1)

        # fecha o arquivo
        l_data_file.close()

        # obtém o elemento raíz do documento
        l_elem_root = l_xdoc_sub.documentElement()
        assert l_elem_root is not None

        # faz o parse dos atributos do elemento raíz
        ldct_root = parser.parse_root_element(l_elem_root)

        # cria uma lista com os elementos de procedimento de subida
        l_node_list = l_elem_root.elementsByTagName("subida")

        # para todos os nós na lista...
        for li_ndx in xrange(l_node_list.length()):
            # inicia o dicionário de dados
            ldct_data = {}

            # inicia a lista de breakpoints
            ldct_data["breakpoints"] = []

            # obtém um nó da lista
            l_element = l_node_list.at(li_ndx).toElement()
            assert l_element is not None

            # read identification if available
            if l_element.hasAttribute("nSub"):
                ldct_data["nSub"] = int(l_element.attribute("nSub"))

            # obtém o primeiro nó da sub-árvore
            l_node = l_element.firstChild()
            assert l_node is not None

            # percorre a sub-árvore
            while not l_node.isNull():
                # tenta converter o nó em um elemento
                l_element = l_node.toElement()
                assert l_element is not None

                # o nó é um elemento ?
                if not l_element.isNull():
                    # faz o parse do elemento
                    ldct_tmp = parser.parse_subida(l_element)

                    # tem breakpoint ?
                    if "breakpoint" in ldct_tmp:
                        # atualiza o dicionário com o breakpoint
                        ldct_data["breakpoints"].append(ldct_tmp["breakpoint"])

                        # apaga este elemento
                        del ldct_tmp["breakpoint"]

                    # atualiza o dicionário de dados
                    ldct_data.update(ldct_tmp)

                # próximo nó
                l_node = l_node.nextSibling()
                assert l_node is not None

            # carrega os dados de procedimento de subida a partir de um dicionário
            self.__make_sub(ldct_root, ldct_data)
Example #17
0
	def load_theme(self):
		QtCore.QDir.setSearchPaths("skin", ["skins:%s" %(self.current_theme)])

		css = QtCore.QFile("skin:ui.css")
		clock_css = QtCore.QFile("skin:clock.css")
		css_isopen = css.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text)
		clock_css_isopen = clock_css.open(QtCore.QFile.ReadOnly | QtCore.QFile.Text)
		if self.use_css and css_isopen and clock_css_isopen:
			self.stylesheet = str(css.readAll()+clock_css.readAll(),
			                    encoding = os.sys.getdefaultencoding())
			make_icon = lambda g, n: QtGui.QIcon(self.grab_icon_path(g, n))
		elif clock_css_isopen:
			self.stylesheet = str(clock_css.readAll(), encoding = os.sys.getdefaultencoding())
			make_icon = lambda g, n: QtGui.QIcon.fromTheme("{}_clnx".format(n),
			                                             QtGui.QIcon(self.grab_icon_path(g, n)))
		else:
			self.stylesheet = ""
			make_icon = lambda g, n: QtGui.QIcon.fromTheme("{}_clnx".format(n),
			                                             QtGui.QIcon(self.grab_icon_path(g, n)))
		css.close()
		clock_css.close()

		if self.current_icon_override > "":
			QtGui.QIcon.setThemeName(self.current_icon_override)
		else:
			QtGui.QIcon.setThemeName(self.sys_icotheme)

		self.main_icons = {
			'Sun' : make_icon("planets", "sun"),
			'Moon' : make_icon("planets", "moon"),
			'Mercury' : make_icon("planets", "mercury"),
			'Venus' : make_icon("planets", "venus"),
			'Mars' : make_icon("planets", "mars"),
			'Jupiter' : make_icon("planets", "jupiter"),
			'Saturn' : make_icon("planets", "saturn"),
			'Uranus' : make_icon("planets", "uranus"),
			'Neptune' : make_icon("planets", "neptune"),
			'Pluto' : make_icon("planets", "pluto"),
			'Pluto 2' : make_icon("planets", "pluto_2"),
			'North Node' : make_icon("planets", "north_node"),
			'South Node' : make_icon("planets", "south_node"),
			'logo' :  make_icon("misc", "chronoslnx"),
			'daylight' : make_icon("misc", "day"),
			'nightlight' : make_icon("misc", "night"),
		}
		#only needed to update labels
		self.main_pixmaps = {
			'Sun' : self.main_icons['Sun'].pixmap(64, 64),
			'Moon' : self.main_icons['Moon'].pixmap(64, 64),
			'Mercury' : self.main_icons['Mercury'].pixmap(64, 64),
			'Venus' : self.main_icons['Venus'].pixmap(64, 64),
			'Mars' : self.main_icons['Mars'].pixmap(64, 64),
			'Jupiter' : self.main_icons['Jupiter'].pixmap(64, 64),
			'Saturn' : self.main_icons['Saturn'].pixmap(64, 64),
		}
		self.moon_icons = {
			'New Moon' : make_icon("moonphase", "new_moon"),
			'Waxing Crescent Moon' : make_icon("moonphase", "waxing_crescent_moon"),
			'First Quarter Moon' : make_icon("moonphase", "first_quarter_moon"),
			'Waxing Gibbous Moon' : make_icon("moonphase", "waxing_gibbous_moon"),
			'Full Moon' : make_icon("moonphase", "full_moon"),
			'Waning Gibbous Moon' : make_icon("moonphase", "waning_gibbous_moon"),
			'Last Quarter Moon' : make_icon("moonphase", "last_quarter_moon"),
			'Waning Crescent Moon' : make_icon("moonphase", "waning_crescent_moon"),
			'Solar Return' : make_icon("misc", "solar_return"),
			'Lunar Return' : make_icon("misc", "lunar_return"),
		}
		self.sign_icons = {
			'Aries': make_icon("signs", 'aries'),
			'Taurus': make_icon("signs", 'taurus'),
			'Gemini': make_icon("signs", 'gemini'),
			'Cancer': make_icon("signs", 'cancer'),
			'Leo': make_icon("signs", 'leo'),
			'Virgo': make_icon("signs", 'virgo'),
			'Libra': make_icon("signs", 'libra'),
			'Scorpio': make_icon("signs", 'scorpio'),
			'Sagittarius': make_icon("signs", 'sagittarius'),
			'Capricorn': make_icon("signs", 'capricorn'),
			'Capricorn 2': make_icon("signs", 'capricorn_2'),
			'Capricorn 3': make_icon("signs", 'capricorn_3'),
			'Aquarius': make_icon("signs", 'aquarius'),
			'Pisces': make_icon("signs", 'pisces'),
			'Ascendant' : make_icon("signs", "ascendant"),
			'Descendant' : make_icon("signs", "descendant"),
			'IC' : make_icon("signs", "ic"),
			'MC' : make_icon("signs", "mc"),
		}
Example #18
0
    def Composer(self, idsortie):
        print 'dans composeur, id_sortie='+str(idsortie)
        #Affichage des contours du site
        #Récupération des données de la table "sortie" pour affichage du site et utilisation dans les étiquettes du composeur
        self.recupDonnSortie(idsortie)
        reqwheresit="""codesite='"""+str(self.codedusite)+"""'"""
        self.uri.setDataSource("sites_cen", "t_sitescen", "the_geom", reqwheresit)
        self.contours_site=QgsVectorLayer(self.uri.uri(), "contours_site", "postgres")
        # Import de la couche contenant les contours du site
        root = QgsProject.instance().layerTreeRoot()
        if self.contours_site.featureCount()>0:
            QgsMapLayerRegistry.instance().addMapLayer(self.contours_site, False)
            root.insertLayer(0, self.contours_site)
        # Symbologie du contour de site
            # create a new single symbol renderer
        symbol = QgsSymbolV2.defaultSymbol(self.contours_site.geometryType())
        renderer = QgsSingleSymbolRendererV2(symbol)
            # create a new simple marker symbol layer, a white circle with a black border
        properties = {'color': 'green', 'color_border': 'red'}
        symbol_layer = QgsSimpleFillSymbolLayerV2.create(properties)
        symbol_layer.setBrushStyle(0) #0 = Qt.NoBrush. Cf doc de QBrush
            # assign the symbol layer to the symbol renderer
        renderer.symbols()[0].changeSymbolLayer(0, symbol_layer)
            # assign the renderer to the layer
        self.contours_site.setRendererV2(renderer)


        #Appel à la fonction "affiche", qui importe les couches non vides de gestion réalisée, parmi operation_poly, operation_lgn et operation_pts
        self.affiche(idsortie)


        # Affichage des couches contenant les contours du site et les opérations de gestion saisies, et masquage des autres
        self.rendreVisible=[]
        layers=iface.legendInterface().layers()
        for layer in layers:
            if layer.type()==QgsMapLayer.VectorLayer:
                if layer.name()=='gestrealpolys' or layer.name()=='gestreallgn' or layer.name()=='gestrealpts' or layer.name()=='contours_site':
                    iface.legendInterface().setLayerVisible(layer, True)
                else:
                    if iface.legendInterface().isLayerVisible(layer):
                        self.rendreVisible.append(layer)
                    iface.legendInterface().setLayerVisible(layer, False)


        #Récupération des données de la table "ch_volont" pour utilisation dans les étiquettes du composeur
        self.recupDonnChVolont(idsortie)

        #COMPOSEUR : Production d'un composeur
        beforeList = self.iface.activeComposers()
        self.iface.actionPrintComposer().trigger()  
        afterList = self.iface.activeComposers()
        diffList = []
        for item in afterList:
            if not item in  beforeList:
                diffList.append(item)
        #Intégration du composeur dans le QgsComposerView et création du QgsComposition
        self.composerView = diffList[0]
        self.composition = self.composerView.composition()
        # Adaptation de la composition : 2 pages A3
        self.composition.setPaperSize(420, 297)
        self.composition.setNumPages(2)


        #TEMPLATE : Récupération du template. Intégration des ses éléments dans la carte.
        if sys.platform.startswith('linux'):
            file1=QtCore.QFile('/home/vincent/.qgis2/python/plugins/bdtravaux/BDT_20130705_T_CART_ComposerTemplate.qpt')
        if sys.platform.startswith('win32'):
            file1=QtCore.QFile('C:\qgistemplate\BDT_20130705_T_CART_ComposerTemplate.qpt')
        doc=QtXml.QDomDocument()
        doc.setContent(file1, False)
        elem=doc.firstChildElement()
        self.composition.loadFromTemplate(doc, substitutionMap=None, addUndoCommands =False)


        #CARTE : Récupération de la carte. 
        maplist=[]
        for item in self.composition.composerMapItems():
            maplist.append(item)
        self.composerMap=maplist[0]
        #Taille définie pour la carte
        x, y, w, h, mode, frame, page = 5, 15, 408, 270, QgsComposerItem.UpperLeft, False, 1
        self.composerMap.setItemPosition(x, y, w, h, mode, frame, page)
#        print self.composerMap.page()
        #Crée la bbox autour du site pour la carte en cours (fonction mapItemSetBBox l 293)
        #self.contours_sites est défini dans la fonction affiche()
        self.margin=10
        self.composerMapSetBBox(self.contours_site, self.margin)
                    #(Dé)zoome sur l'ensemble des deux pages du composeur
                    #self.composition.mActionZoomFullExtent().trigger()


        #ETIQUETTES :       Modifier les étiquettes du composeur.
        # Trouver les étiquettes dans le composeur
        labels = [item for item in self.composition.items()\
                if item.type() == QgsComposerItem.ComposerLabel]

        #trouver les opérations effectuées lors de la sortie et leurs commentaires dans la table postgresql, selon l'id de la sortie sélectionnée dans le module "opération"
        # une boucle permet de récupérer et afficher à la suite dans une seule zone de texte toutes les opérations et leurs descriptions
        querycomope = QtSql.QSqlQuery(self.db)
        qcomope=u"""select operation_id, (select distinct array_to_string(array(select distinct typoperation from bdtravaux.join_typoperation where id_jointyp=id_oper order by typoperation),'; ')) as typope, descriptio, code_gh, round(st_area(the_geom)::numeric,2) as surface, round(st_length(the_geom)::numeric,2) as longueur, ST_NumGeometries(the_geom) as compte, (select distinct array_to_string(array(select distinct operateurs from bdtravaux.join_operateurs where id_joinop=id_oper order by operateurs),'; ')) as operateurs from (select * from bdtravaux.operation_poly UNION select * from bdtravaux.operation_lgn UNION select * from bdtravaux.operation_pts) tables where sortie={zr_sortie} order by typ_operat""".format \
        (zr_sortie = idsortie) #self.ui.sortie.itemData(self.ui.sortie.currentIndex())
        #print unicode(qcomope)
        ok3 = querycomope.exec_(qcomope)
        if not ok3:
            QtGui.QMessageBox.warning(self, 'Alerte', u'Requête operations ratée')
        querycomope.first()
        texteope=""
        #Requête : Données à récupérer pour chaque opération de la sortie
        for i in xrange(0 , querycomope.size()):
            #Récupération des autres valeurs de chaque opération
            ope=unicode(querycomope.value(1))
            descrope=unicode(querycomope.value(2)).replace('\n','<br/>')
            ghope=unicode(querycomope.value(3))
            surfope=unicode(querycomope.value(4))
            longope=unicode(querycomope.value(5))
            countope=unicode(querycomope.value(6))
            operatope=unicode(querycomope.value(7))
            texteope=unicode(texteope+u'<br/>'+u'<b>'+ope+u'</b>'+u'<h style="margin-left:1cm;">('+ ghope+u')<h style="margin-left:0.5cm;">'+u'/'+u'<h style="margin-left:0.5cm;">'+surfope+u' m²'+'<h style="margin-left:0.5cm;">'+u'/'+u'<h style="margin-left:0.5cm;">'+longope+u' ml<h style="margin-left:0.5cm;">'+u'/'+u'<h style="margin-left:0.5cm;">'+operatope+u'<br/>'+descrope+u'<br/>')
            querycomope.next()

        # Pour chaque étiquette qui contient le mot-clé (comme "$codesite"), remplacer le texte par le code du site concerné
        # La methode find() permet de chercher une chaîne dans une autre. 
        # Elle renvoie le rang du début de la chaîne cherchée. Si = -1, c'est que la chaîne cherchée n'est pas trouvée
        for label in labels:
            if label.displayText().find("$codesite")>-1:
                plac_codesite=label.displayText().find("$codesite")
                texte=unicode(label.displayText())
                label.setText(texte[0:plac_codesite]+self.codedusite+texte[plac_codesite+9:])
                #pr python equiv à VB6 left, mid and right : https://mail.python.org/pipermail/tutor/2004-November/033445.html
            if label.displayText().find("$redac")>-1:
                plac_redac=label.displayText().find("$redac")
                texte=unicode(label.displayText())
                label.setText(texte[0:plac_redac]+self.salaries+texte[plac_redac+6:])
            if label.displayText().find("$date")>-1:
                plac_date=label.displayText().find("$date")
                texte=unicode(label.displayText())
                label.setText(texte[0:plac_date]+self.datesortie+texte[plac_date+5:])
            if label.displayText().find("$datefin")>-1:
                plac_date=label.displayText().find("$datefin")
                texte=unicode(label.displayText())
                label.setText(texte[0:plac_date]+self.datefin+texte[plac_date+8:])
            if label.displayText().find("$jourschan")>-1:
                plac_date=label.displayText().find("$jourschan")
                texte=unicode(label.displayText())
                label.setText(texte[0:plac_date]+self.jourschan+texte[plac_date+10:])
            if label.displayText().find("$commsortie")>-1:
                plac_commsortie=label.displayText().find("$commsortie")
                texte=unicode(label.displayText())
                label.setText(texte[0:plac_commsortie]+self.sortcom+texte[plac_commsortie+11:])
            if label.displayText().find("$nomsite")>-1:
                plac_nomsite=label.displayText().find("$nomsite")
                texte=unicode(label.displayText())
                label.setText(texte[0:plac_nomsite]+self.nomdusite+texte[plac_nomsite+8:])
            if label.displayText().find("$commope")>-1:
                label.setText(texteope)
            if label.displayText().find("$objet")>-1:
                plac_objet=label.displayText().find("$objet")
                texte=unicode(label.displayText())
                label.setText(texte[0:plac_objet]+self.objvisite+texte[plac_objet+6:])
            if label.displayText().find("$objvi_autre")>-1:
                plac_objautre=label.displayText().find("$objvi_autre")
                texte=unicode(label.displayText())
                if self.objautre:
                    label.setText(texte[0:plac_objautre]+self.objautre+texte[plac_objautre+12:])
                else:
                    label.setText(texte[0:plac_objautre]+''+texte[plac_objautre+12:])
            if label.displayText().find("$natfaune")>-1:
                label.setText(self.natfaune)
            if label.displayText().find("$natflore")>-1:
                label.setText(self.natflore)
            if self.cv_partenaire is not None:
                if label.displayText().find("$nbjours")>-1:
                    plac_nbjours=label.displayText().find("$nbjours")
                    texte=unicode(label.displayText())
                    label.setText(texte[0:plac_nbjours]+str(self.cv_nb_jours)+texte[plac_nbjours+8:])
                if label.displayText().find("$nbheurch")>-1:
                    plac_nbheurch=label.displayText().find("$nbheurch")
                    texte=unicode(label.displayText())
                    label.setText(texte[0:plac_nbheurch]+str(self.cv_nb_heur_ch)+texte[plac_nbheurch+9:])
                if label.displayText().find("$nbheurdec")>-1:
                    plac_nbheurdec=label.displayText().find("$nbheurdec")
                    texte=unicode(label.displayText())
                    label.setText(texte[0:plac_nbheurdec]+str(self.cv_nb_heur_de)+texte[plac_nbheurdec+10:])
                if label.displayText().find("$partenair")>-1:
                    plac_partenair=label.displayText().find("$partenair")
                    texte=unicode(label.displayText())
                    label.setText(texte[0:plac_partenair]+self.cv_partenaire+texte[plac_partenair+10:])
#                    print unicode(texte)
                if label.displayText().find("$heberg")>-1:
                    plac_heberg=label.displayText().find("$heberg")
                    texte=unicode(label.displayText())
                    label.setText(texte[0:plac_heberg]+self.cv_heberg+texte[plac_heberg+7:])
                if label.displayText().find("$jr1enc_am")>-1:
                    label.setText(str(self.cv_j1_enc_am))
                if label.displayText().find("$jr1enc_pm")>-1:
                    label.setText(str(self.cv_j1_enc_pm))
                if label.displayText().find("$jr1tot_am")>-1:
                    label.setText(str(self.cv_j1_tot_am))
                if label.displayText().find("$jr1tot_pm")>-1:
                    label.setText(str(self.cv_j1_tot_pm))
                if label.displayText().find("$jr1cen_am")>-1:
                    label.setText(str(self.cv_j1adcen_am))
                if label.displayText().find("$jr1cen_pm")>-1:
                    label.setText(str(self.cv_j1adcen_pm))
                if label.displayText().find("$jr1blo_am")>-1:
                    label.setText(str(self.cv_j1_blon_am))
                if label.displayText().find("$jr1blo_pm")>-1:
                    label.setText(str(self.cv_j1_blon_pm))
                if label.displayText().find("$jr2enc_am")>-1:
                    label.setText(str(self.cv_j2_enc_am))
                if label.displayText().find("$jr2enc_pm")>-1:
                    label.setText(str(self.cv_j2_enc_pm))
                if label.displayText().find("$jr2tot_am")>-1:
                    label.setText(str(self.cv_j2_tot_am))
                if label.displayText().find("$jr2tot_pm")>-1:
                    label.setText(str(self.cv_j2_tot_pm))
                if label.displayText().find("$jr2cen_am")>-1:
                    label.setText(str(self.cv_j2adcen_am))
                if label.displayText().find("$jr2cen_pm")>-1:
                    label.setText(str(self.cv_j2adcen_pm))
                if label.displayText().find("$jr2blo_am")>-1:
                    label.setText(str(self.cv_j2_blon_am))
                if label.displayText().find("$jr2blo_pm")>-1:
                    label.setText(str(self.cv_j2_blon_pm))
                if label.displayText().find("$sem_enc")>-1:
                    label.setText(str(self.cv_sem_enc))
                if label.displayText().find("$sem_ben")>-1:
                    label.setText(str(self.cv_sem_ben))
            else:
                if re.match("^\$jr",label.displayText()) or re.search("\$sem",label.displayText()) or re.search("\$nb",label.displayText()):
                    label.setText('0')
                if re.search("\$partenair",label.displayText()) or re.search("\$heberg",label.displayText()):
                    label.setText(' ')
                # le module re permet de chercher des chaînes dans du texte avec des expression régulières
                # match => le début du texte doit correspondre
                #search : on cherche la chaîne quelque-part dans le texte.
                #le \ permet d'échapper le $ (qui correspond normalement à une fin de ligne dans une regexp).


        #LEGENDE : mettre à jour la légende. 
        for i in self.composition.items():
            if isinstance(i,QgsComposerLegend):
                print "mise a jour legende"
                legend = i 
                legend.setAutoUpdateModel(True)
                for j in xrange(legend.modelV2().rowCount()):
                    modelindex=legend.modelV2().index(j, 0)
                    layertreenode=legend.modelV2().index2node(modelindex)
#                    print modelindex.data()
#                    print modelindex.__class__.__name__
#                    print layertreenode.__class__.__name__
                    if isinstance(layertreenode, QgsLayerTreeGroup):
                        layertreenode.setVisible(False)
#                        print modelindex.data()
#                        layertreenode.setName("")
#                        print modelindex.data()
                    else:
                         print 'Layer'
                legend.setAutoUpdateModel(False)
                legend.setLegendFilterByMapEnabled(True)
Example #19
0
    def capabilitiesRequest(self, fileName):
        try:
            self.service = SensorObservationService(self.reply.url(), fileName)
            self.filterRequest = FilterRequest(self.service)
        except Exception as error:
            self.service = None
            widget = self.messageBar.createMessage(unicode(error))
            button = QtGui.QCommandLinkButton(widget)
            button.setText(self.tr("Show reply"))
            button.clicked.connect(
                XmlViewerDialog(self, QtCore.QFile(fileName),
                                XmlHighlighter).exec_)
            widget.layout().addWidget(button)
            self.messageBar.pushWidget(widget, QgsMessageBar.CRITICAL)

        if self.service:
            self.messageBar.pushMessage(self.tr("Capabilities downloaded"),
                                        QgsMessageBar.INFO, 3)
            self.htmlView.setText(unicode(self.service))
            for offer in self.service.observationOfferingList:
                self.cmbOfferings.addItem(
                    "%s (%s)" % (self.service[offer].identifier,
                                 self.service[offer].identifier),
                    self.service[offer].identifier)

            index = self.cmbOfferings.currentIndex()
            if index > -1: self.cmbOfferings.activated.emit(index)

            if 'GetObservation' in self.service.operationsMetadata:
                self.btnAdd.setEnabled(True)

                self.grpFilterSpatial.setChecked(
                    self.filterRequest.spatialFilter == True)
                self.grpFilterSpatial.setEnabled(
                    self.filterRequest.spatialFilter != None)
                self.cmbFilterSpatialOperators.setModel(
                    QtGui.QStringListModel(self.service.spatialOperators))
                self.cmbFilterSpatialOperands.setModel(
                    QtGui.QStringListModel(self.service.spatialOperands))
                self.cmbFilterSpatialOperands.activated.emit(
                    self.cmbFilterSpatialOperands.currentIndex())

                self.grpFilterTemporal.setChecked(
                    self.filterRequest.temporalFilter == True)
                self.grpFilterTemporal.setEnabled(
                    self.filterRequest.temporalFilter != None)
                self.cmbFilterTemporalOperators.setModel(
                    QtGui.QStringListModel(self.service.temporalOperators))
                self.cmbFilterTemporalOperands.setModel(
                    QtGui.QStringListModel(self.service.temporalOperands))
                self.cmbFilterTemporalOperands.activated.emit(
                    self.cmbFilterTemporalOperands.currentIndex())

                self.grpFilterScalar.setChecked(
                    self.filterRequest.temporalFilter == True)
                self.grpFilterScalar.setEnabled(
                    self.filterRequest.temporalFilter != None)
                self.cmbFilterScalarOperators.setModel(
                    QtGui.QStringListModel(self.service.scalarOperators))
                self.cmbFilterScalarOperators.activated.emit(
                    self.cmbFilterScalarOperators.currentIndex())
Example #20
0
    def getImageBase(self, filename):
        """
        getImageBase returns the prefix which will be used for subsequent file naming based upon
        an input filename
        :param filename:
        :return:
        """
        self.imFile = filename
        ind_of_suffx = filename.lastIndexOf('.')
        ind_of_start_num = filename.lastIndexOf('_') + 1
        extension = os.path.splitext(filename.toLatin1().data())[1]
        if "h5" in extension:
            self.h5Flag = True
        else:
            self.h5Flag = False

        newbase = filename.left(ind_of_start_num)
        if not self.h5Flag:
            imstringFilt = '*.tif' % newbase
        else:
            imstringFilt = '*.h5' % newbase
        curimage = filename
        self.filenum = self.getFileNumber(filename)
        #print 'Debug : %s'%self.filenum
        qfinfo = QtCore.QFileInfo(filename)
        apath = qfinfo.absolutePath()
        fileonly = qfinfo.fileName()
        tmpind = fileonly.lastIndexOf('_') + 1
        tmpbase = fileonly.left(tmpind)
        qd = QtCore.QDir(apath)
        qd.setNameFilters(QtCore.QStringList() << imstringFilt)
        imfiles = qd.entryList()
        n = imfiles.count()
        self.minImageNum = 1E10
        self.maxImageNum = -1
        for i in imfiles:
            if (i.contains(tmpbase) == False):
                continue
            startInd = i.lastIndexOf('_') + 1
            endInd = i.lastIndexOf('.')
            self.numDigits = endInd - startInd
            num = i.mid(startInd, self.numDigits).toInt()[0]
            print num, '   ', i
            if (num < self.minImageNum):
                self.minImageNum = num
            if (num > self.maxImageNum):
                self.maxImageNum = num
        print 'min image : ', self.minImageNum
        print 'max image : ', self.maxImageNum
        self.numImages = self.maxImageNum - self.minImageNum + 1
        print 'num images : ', self.numImages
        if (self.base != newbase):
            self.base = QtCore.QString(newbase)
            self.checkForFiles()

        else:
            setfile = filename + '.txt'
            qf = QtCore.QFile(setfile)
            if (qf.exists()):
                self.readFileSettings(setfile)
        return self.base
 def getLastOpenDir(self):
     # open last remember directory
     lastPath = QSettingsUtil.getLastDir()
     if not QtCore.QFile(lastPath).exists():
         lastPath = 'd://'
     return lastPath
Example #22
0
    os.path.abspath(__file__))  # path of the current file

# this allows the script to be run directly from the repository without having to install pydicom or pyqtgraph
if os.path.isdir(scriptdir + '/../pydicom'):
    sys.path.append(scriptdir + '/../pydicom')
    sys.path.append(scriptdir + '/../pyqtgraph')

import numpy as np
import pyqtgraph as pg
from pydicom import dicomio, datadict, errors

from .__init__ import __version__

# load the ui file from the resource, removing the "resources" tag so that uic doesn't try (and fail) to load the resources
# this allows a loading the UI at runtime rather than generating a .py file with pyuic which isn't cross-compatible with PyQt4/5
with closing(QtCore.QFile(':/layout/DicomBrowserWin.ui')) as layout:
    if layout.open(QtCore.QFile.ReadOnly):
        s = bytes(layout.readAll()).decode('utf-8')
        s = re.sub(
            '<resources>.*</resources>', '', s,
            flags=re.DOTALL)  # get rid of the resources section in the XML
        Ui_DicomBrowserWin, _ = uic.loadUiType(
            StringIO(s))  # create a local type definition

# tag names of default columns in the series list, this can be changed to pull out different tag names for columns
seriesListColumns = ('PatientName', 'SeriesDescription', 'SeriesNumber',
                     'NumImages')
# names of columns in tag tree, this shouldn't ever change
tagTreeColumns = ('Name', 'Tag', 'Value')
# list of tags to initially load when a directory is scanned, loading only these speeds up scanning immensely
loadTags = ('SeriesInstanceUID', 'TriggerTime', 'PatientName',
Example #23
0
def getDataFromXmlFile(parentWidget, fileName):
    rootElementName = 'ZL_LIST'
    accountElementName = 'SCHET'
    recordElementName = 'ZAP'
    platElementName = 'PLAT'
    nsvodElementName = 'NSVOD'

    def moveToNearestOfElements(reader, elementNames, stopElements):
        if isinstance(elementNames, basestring):
            elementNames = [elementNames]

        while reader.readNext() not in [
                QtCore.QXmlStreamReader.Invalid,
                QtCore.QXmlStreamReader.EndDocument
        ]:
            if reader.isEndElement() and forceString(
                    reader.name()) in stopElements:
                return False
            if reader.isStartElement() and forceString(
                    reader.name()) in elementNames:
                stopElements.append(forceString(reader.name()))
                return True
        return False

    #end moveToNearestElement

    def moveAfterEndElement(reader, elementNames, stopElements):
        if isinstance(elementNames, basestring):
            elementNames = [elementNames]

        if not reader.isEndElement() or forceString(
                reader.name()) not in stopElements:
            while reader.readNext() not in [
                    QtCore.QXmlStreamReader.Invalid,
                    QtCore.QXmlStreamReader.EndDocument
            ]:
                if reader.isEndElement() and forceString(
                        reader.name()) in stopElements:
                    break

        if reader.isEndElement() and forceString(
                reader.name()) in elementNames:
            stopElements.remove(forceString(reader.name()))
            reader.readNext()
            return True

        return False

    #end moveAfterEndElement

    def readElementText(reader):
        if hasattr(QtCore.QXmlStreamReader, 'SkipChildElements'):
            return reader.readElementText(
                QtCore.QXmlStreamReader.SkipChildElements)
        else:
            return reader.readElementText()

    def parseAccount(reader, accountInfo, stopElements):
        while moveToNearestOfElements(reader, platElementName, stopElements):
            insurrerInfis = forceString(readElementText(reader))
            tableOrganisation = QtGui.qApp.db.table('Organisation')
            record = QtGui.qApp.db.getRecordEx(
                tableOrganisation, 'shortName',
                'infisCode LIKE \'%s%%\' and deleted = 0' % insurrerInfis)
            infisName = forceString(
                record.value('shortName')) if record else ''
            accountInfo[platElementName] = infisName
            if not moveAfterEndElement(reader, platElementName, stopElements):
                return False
        return True

    #end parseAccount

    def parseRecord(reader,
                    reportDataByNumbers,
                    stopElements,
                    specialityNameCashe=None):
        if not specialityNameCashe:
            specialityNameCashe = {}
        eventElementName = 'SLUCH'
        serviceElementName = 'USL'
        serviceTypeElementName = 'USL_OK'
        serviceCodeElementName = 'CODE_USL'
        serviceSumElementName = 'SUMV_USL'
        serviceAddPaymentsElementName = 'DOPL'
        serviceWagesElementName = 'ZPL'
        serviceDrugsElementName = 'MED'
        serviceSoftInventoryElementName = 'M_INV'
        serviceOverheadElementName = 'NAKL'
        orgStructureCodeElementName = 'KODLPU'
        idCaseElementName = 'IDCASE'

        #перебор всех SLUCH в текущем ZAP
        while moveToNearestOfElements(reader, eventElementName, stopElements):
            uslOk = None
            nsvod = '____'
            orgStructureCode = None
            idCase = None

            #Временный словарь с данными для отчета
            #Необходим для того, чтобы не писать в основной словарь данные по случаям с USL_OK != 3
            #(если в xml тег USL_OK задан после USL тегов в SLUCH)
            dataByServiceCode = {}

            eventElements = [
                idCaseElementName, serviceTypeElementName, nsvodElementName,
                orgStructureCodeElementName, serviceElementName
            ]

            #просмотр данных по случаю
            while moveToNearestOfElements(reader, eventElements, stopElements):
                currentEventElementName = forceString(reader.name())
                if currentEventElementName == idCaseElementName:
                    idCase = forceRef(readElementText(reader))

                elif currentEventElementName == serviceTypeElementName:
                    uslOk = forceString(readElementText(reader))
                    if uslOk != '3':
                        if not moveAfterEndElement(
                                reader, currentEventElementName, stopElements):
                            return False
                        break

                elif currentEventElementName == nsvodElementName:
                    nsvod = forceString(readElementText(reader))

                elif currentEventElementName == orgStructureCodeElementName:
                    orgStructureCode = forceString(readElementText(reader))

                elif currentEventElementName == serviceElementName:
                    serviceCode = None
                    serviceSum = 0.0
                    serviceAddPayments = 0.0
                    serviceWages = 0.0
                    serviceDrugs = 0.0
                    serviceSoftInventory = 0.0
                    serviceOverhead = 0.0

                    serviceElements = [
                        serviceCodeElementName, serviceSumElementName,
                        serviceAddPaymentsElementName, serviceWagesElementName,
                        serviceDrugsElementName,
                        serviceSoftInventoryElementName,
                        serviceOverheadElementName
                    ]
                    #перебор всех данных по текущей услуге/посещению
                    while moveToNearestOfElements(reader, serviceElements,
                                                  stopElements):
                        currentServiceElementName = forceString(reader.name())
                        if currentServiceElementName == serviceCodeElementName:
                            serviceCode = forceString(readElementText(reader))
                        elif currentServiceElementName == serviceSumElementName:
                            serviceSum = forceDouble(readElementText(reader))
                        elif currentServiceElementName == serviceAddPaymentsElementName:
                            serviceAddPayments = forceDouble(
                                readElementText(reader))
                        elif currentServiceElementName == serviceWagesElementName:
                            serviceWages = forceDouble(readElementText(reader))
                        elif currentServiceElementName == serviceDrugsElementName:
                            serviceDrugs = forceDouble(readElementText(reader))
                        elif currentServiceElementName == serviceSoftInventoryElementName:
                            serviceSoftInventory = forceDouble(
                                readElementText(reader))
                        elif currentServiceElementName == serviceOverheadElementName:
                            serviceOverhead = forceDouble(
                                readElementText(reader))
                        if not moveAfterEndElement(reader,
                                                   currentServiceElementName,
                                                   stopElements):
                            return False
                    #end while moveToNearestOfElements(reader, serviceElements, stopElements):

                    if serviceCode:
                        serviceData = dataByServiceCode.setdefault(
                            serviceCode, {
                                'serviceCode': serviceCode,
                                'visitCount': 0,
                                'sum': 0.0,
                                'wages': 0.0,
                                'additionalPayments': 0.0,
                                'drugs': 0.0,
                                'softInventory': 0.0,
                                'overhead': 0.0
                            })

                        serviceData['visitCount'] += 1
                        serviceData['sum'] += serviceSum
                        serviceData['wages'] += serviceWages
                        serviceData['additionalPayments'] += serviceAddPayments
                        serviceData['drugs'] += serviceDrugs
                        serviceData['softInventory'] += serviceSoftInventory
                        serviceData['overhead'] += serviceOverhead

                if not moveAfterEndElement(reader, currentEventElementName,
                                           stopElements):
                    return False
            #end while moveToNearestOfElements(reader, eventElements, stopElements)
            #конец просмотра случая

            #обработывать только случаи с USL_OK = 3
            if uslOk == '3':
                reportData = reportDataByNumbers.setdefault(nsvod, {})

                #Сохранение данных по всем услугам из текущего случая в конечный словарь reportData
                for serviceCode in dataByServiceCode.keys():
                    if not specialityNameCashe.has_key(serviceCode):
                        rbSpecialityTable = QtGui.qApp.db.table('rbSpeciality')
                        specialityNameCashe[serviceCode] = forceString(
                            QtGui.qApp.db.translate(
                                rbSpecialityTable,
                                rbSpecialityTable['federalCode'], serviceCode,
                                rbSpecialityTable['OKSOName']))
                    specialityName = specialityNameCashe[serviceCode]
                    orgStructureData = reportData.setdefault(serviceCode, {})
                    serviceData = orgStructureData.setdefault(
                        serviceCode, {
                            'orgStructureCode': orgStructureCode,
                            'serviceCode': serviceCode,
                            'specialityName': specialityName,
                            'visitCount': 0,
                            'eventCount': 0,
                            'sum': 0.0,
                            'wages': 0.0,
                            'additionalPayments': 0.0,
                            'drugs': 0.0,
                            'softInventory': 0.0,
                            'overhead': 0.0,
                            'idCaseValueSet': []
                        })

                    serviceData['visitCount'] += dataByServiceCode[
                        serviceCode]['visitCount']
                    if idCase not in serviceData['idCaseValueSet']:
                        serviceData['idCaseValueSet'].append(idCase)
                        serviceData['eventCount'] += 1
                    serviceData['sum'] += dataByServiceCode[serviceCode]['sum']
                    serviceData['wages'] += dataByServiceCode[serviceCode][
                        'wages']
                    serviceData['additionalPayments'] += dataByServiceCode[
                        serviceCode]['additionalPayments']
                    serviceData['drugs'] += dataByServiceCode[serviceCode][
                        'drugs']
                    serviceData['softInventory'] += dataByServiceCode[
                        serviceCode]['softInventory']
                    serviceData['overhead'] += dataByServiceCode[serviceCode][
                        'overhead']

            if not moveAfterEndElement(reader, eventElementName, stopElements):
                return False
        #end while moveToNearestOfElements(reader, eventElementName, stopElements):
        #конец перебора всех случаев в записи

        return True

    #end parseRecord

    reportDataByNumbers = {}
    accountInfo = {}
    specialityNameCashe = {}

    reportFile = QtCore.QFile(fileName)

    if not reportFile.open(QtCore.QIODevice.ReadOnly):
        QtGui.QMessageBox.warning(
            parentWidget,
            u'Ошибка',
            u'Не удалось открыть файл\n%s\n(%s)' %
            (reportFile.fileName(), reportFile.errorString()),
            buttons=QtGui.QMessageBox.Ok,
            defaultButton=QtGui.QMessageBox.NoButton)
        return reportDataByNumbers, accountInfo.get(platElementName, '')

    reader = QtCore.QXmlStreamReader()
    reader.setDevice(reportFile)

    stopElements = []

    if moveToNearestOfElements(reader, rootElementName, stopElements):
        reportElements = [accountElementName, recordElementName]
        while moveToNearestOfElements(reader, reportElements, stopElements):
            currentReportElementName = forceString(reader.name())
            if currentReportElementName == accountElementName:
                if not parseAccount(reader, accountInfo, stopElements):
                    break
            elif currentReportElementName == recordElementName:
                if not parseRecord(reader, reportDataByNumbers, stopElements,
                                   specialityNameCashe):
                    break
            if not moveAfterEndElement(reader, currentReportElementName,
                                       stopElements):
                return False

    return reportDataByNumbers, accountInfo.get(platElementName, '')
Example #24
0
    def exportXML(self, f_szFName):

        #/ nome do método (logger)
        #/ ----------------------------------------------------------------------------------------
        #l_szMetodo = "clsTabelaPAR::exportXML"

        #/ file descriptor
        #/ ----------------------------------------------------------------------------------------
        l_fdIn = None

        #/ mensagem de erro
        #/ ----------------------------------------------------------------------------------------
        l_szErro = None

        #** ---------------------------------------------------------------------------------------
        #*  m.poirot logger
        #*/
        #l_log = logging.getLogger ( l_szMetodo )
        #l_log.setLevel ( w_logLvl )
        #l_log.debug ( ">> " )

        #** ---------------------------------------------------------------------------------------
        #*/
        try:

            #** -----------------------------------------------------------------------------------
            #*/
            l_fdIn = QtCore.QFile(f_szFName)
            #assert ( l_fdIn )

            #** -----------------------------------------------------------------------------------
            #*/
            if (not l_fdIn.open(QtCore.QIODevice.WriteOnly)):

                #** -------------------------------------------------------------------------------
                #*/
                raise IOError, unicode(l_fdIn.errorString())

            #** -----------------------------------------------------------------------------------
            #*/
            l_stream = QtCore.QTextStream(l_fdIn)
            #assert ( l_stream )

            l_stream.setCodec(glbDefs.xUNI_CODEC)

            #** -----------------------------------------------------------------------------------
            #*/
            l_stream << ("<?xml version='1.0' encoding='{0}'?>\n"
                         "<!DOCTYPE TABPAR>\n"
                         "<TABPAR VERSION='1.0'>\n".format(glbDefs.xUNI_CODEC))

            #** -----------------------------------------------------------------------------------
            #*/
            for _, l_PAR in self._aItens:

                #** -------------------------------------------------------------------------------
                #*/
                l_stream << "<PAR Key='{0}' Descricao='{1}'>\n".format ( l_PAR._szKey, l_PAR._szDescr.replace ( ' ', '_' )) \
                         << "<CAB>"   << l_PAR._iCab0 << "</CAB>\n" \
                         << "<HANT0>" << l_PAR._fHAnt0 << "</HANT0>\n" \
                         << "<HANT1>" << l_PAR._fHAnt1 << "</HANT1>\n" \
                         << "<DAE>" << l_PAR._fDstAntEixo << "</DAE>\n" \
                         << "<DAPT0>" << l_PAR._fDstAntPT0 << "</DAPT0>\n" \
                         << "<DAPT1>" << l_PAR._fDstAntPT1 << "</DAPT1>\n" \
                         << "<ANGR>" << l_PAR._fAngRampa << "</ANGR>\n" \
                         << "<RET>" << l_PAR._aiRetardo [ 0 ] << "</RET>\n" \
                         << "<DECL>" << l_PAR._iDecl << "</DECL>\n" \
                         << "</PAR>\n"

            #** -----------------------------------------------------------------------------------
            #*/
            l_stream << "</TABPAR>\n"

        #** ---------------------------------------------------------------------------------------
        #*/
        except (IOError, OSError), e:

            #** -----------------------------------------------------------------------------------
            #*/
            l_szErro = u"Erro na exportação: {0}".format(e)
Example #25
0
def get_file_contents(file_path):
    xFile = QtCore.QFile(file_path)
    if not xFile.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text):
        raise FileOpenError
    return QtCore.QString(xFile.readAll())
Example #26
0
    def loadQDataStream(self):

        #/ nome do método (logger)
        #/ ----------------------------------------------------------------------------------------
        #l_szMetodo = "clsTabelaPAR::loadQDataStream"

        #/ file descriptor
        #/ ----------------------------------------------------------------------------------------
        l_fdIn = None

        #/ mensagem de erro
        #/ ----------------------------------------------------------------------------------------
        l_szErro = None

        #** ---------------------------------------------------------------------------------------
        #*  m.poirot logger
        #*/
        #l_log = logging.getLogger ( l_szMetodo )
        #l_log.setLevel ( w_logLvl )
        #l_log.debug ( ">> " )

        #** ---------------------------------------------------------------------------------------
        #*  tenta carregar o arquivo...
        #*/
        try:

            #** -----------------------------------------------------------------------------------
            #*  abre o arquivo
            #*/
            l_fdIn = QtCore.QFile(self._szFName)
            #assert ( l_fdIn )

            #** -----------------------------------------------------------------------------------
            #*  erro na abertura ?
            #*/
            if (not l_fdIn.open(QtCore.QIODevice.ReadOnly)):

                #** -------------------------------------------------------------------------------
                #*  gera exception
                #*/
                raise IOError, unicode(l_fdIn.errorString())

            #** -----------------------------------------------------------------------------------
            #*  acessa o arquivo como uma stream de dados
            #*/
            l_stream = QtCore.QDataStream(l_fdIn)
            #assert ( l_stream )

            #** -----------------------------------------------------------------------------------
            #*  le o magic number
            #*/
            l_iMagic = l_stream.readInt32()

            #** -----------------------------------------------------------------------------------
            #*  tipo de arquivo valido ?
            #*/
            if (clsTabelaModel.c_xxMAGIC_NUMBER != l_iMagic):

                #** -------------------------------------------------------------------------------
                #*  gera exception
                #*/
                raise IOError, u"tipo de arquivo não reconhecido !"

            #** -----------------------------------------------------------------------------------
            #*  le a versao do arquivo
            #*/
            l_iVersion = l_stream.readInt32()

            #** -----------------------------------------------------------------------------------
            #*  versao muito antiga ?
            #*/
            if (l_iVersion < clsTabelaModel.c_xxOLD_FILE_VERSION):

                #** -------------------------------------------------------------------------------
                #*  gera exception
                #*/
                raise IOError, u"formato do arquivo é antigo e não legível !"

            #** -----------------------------------------------------------------------------------
            #*  versao nova ?
            #*/
            elif (l_iVersion > clsTabelaModel.c_xxFILE_VERSION):

                #** -------------------------------------------------------------------------------
                #*  gera exception
                #*/
                raise IOError, u"formato do arquivo é novo e não legível !"

            #** -----------------------------------------------------------------------------------
            #*/
            l_stream.setVersion(QtCore.QDataStream.Qt_4_2)

            #** -----------------------------------------------------------------------------------
            #*/
            self.clear(False)

            #** -----------------------------------------------------------------------------------
            #*  enquanto nao termina de ler a stream...
            #*/
            while (not l_stream.atEnd()):

                #** -------------------------------------------------------------------------------
                #*  cria a área para chave do PAR
                #*/
                l_szKey = QtCore.QString()

                #** -------------------------------------------------------------------------------
                #*  lê a chave do PAR
                #*/
                l_stream >> l_szKey

                #** -------------------------------------------------------------------------------
                #*  cria a área para descrição do PAR
                #*/
                l_szDescr = QtCore.QString()

                #** -------------------------------------------------------------------------------
                #*  lê a descrição do PAR
                #*/
                l_stream >> l_szDescr
                l_szDescr = l_szDescr.replace('_', ' ')

                #** -------------------------------------------------------------------------------
                #*  lê a cabeceira principal
                #*/
                l_iCab0 = l_stream.readInt()

                #** -------------------------------------------------------------------------------
                #*  lê a altura da antena relativo ao ponto toque principal
                #*/
                l_fHAnt0 = l_stream.readFloat()

                #** -------------------------------------------------------------------------------
                #*  lê a altura da antena relativo ao ponto toque secundário
                #*/
                l_fHAnt1 = l_stream.readFloat()

                #** -------------------------------------------------------------------------------
                #*  lê o afastamento da antena ao eixo da pista
                #*/
                l_fDstAntEixo = l_stream.readFloat()

                #** -------------------------------------------------------------------------------
                #*  lê a distância da antena ao ponto toque principal
                #*/
                l_fDstAntPT0 = l_stream.readFloat()

                #** -------------------------------------------------------------------------------
                #*  lê a distância da antena ao ponto toque secundário
                #*/
                l_fDstAntPT1 = l_stream.readFloat()

                #** -------------------------------------------------------------------------------
                #*  lê o ângulo da rampa de aproximação
                #*/
                l_fAngRampa = l_stream.readFloat()

                #** -------------------------------------------------------------------------------
                #*  lê o retardo
                #*/
                l_iRetardo = l_stream.readInt()

                #** -------------------------------------------------------------------------------
                #*  lê a declinação magnética
                #*/
                l_iDecl = l_stream.readInt()

                #** -------------------------------------------------------------------------------
                #*  cria o PAR e coloca na tabela de PARs
                #*/
                self.add(
                    clsPAR.clsPAR([
                        l_szKey, l_szDescr, l_iCab0, l_fHAnt0, l_fHAnt1,
                        l_fDstAntEixo, l_fDstAntPT0, l_fDstAntPT1, l_fAngRampa,
                        l_iRetardo, l_iDecl
                    ]), l_szKey)

        #** ---------------------------------------------------------------------------------------
        #*/
        except (IOError, OSError), e:

            #** -----------------------------------------------------------------------------------
            #*  cria a mensagem de erro
            #*/
            l_szErro = "Erro na carga: {0}".format(e)
Example #27
0
    def parse_fix_xml(self, fs_fix_pn):
        """
        carrega o arquivo de fixo

        @param fs_fix_pn: pathname do arquivo em disco
        """
        # check input
        assert fs_fix_pn

        # cria o QFile para o arquivo XML do fixo
        l_data_file = QtCore.QFile(fs_fix_pn)
        assert l_data_file is not None

        # abre o arquivo XML do fixo
        l_data_file.open(QtCore.QIODevice.ReadOnly)

        # erro na abertura do arquivo ?
        if not l_data_file.isOpen():
            # logger
            l_log = logging.getLogger("CFixData::parse_fix_xml")
            l_log.setLevel(logging.CRITICAL)
            l_log.critical(u"<E01: erro na abertura de {}.".format(fs_fix_pn))

            # cria um evento de quit
            l_evt = events.CQuit()
            assert l_evt

            # dissemina o evento
            self.__event.post(l_evt)

            # termina a aplicação
            sys.exit(1)

        # cria o documento XML do fixo
        l_xdoc_fix = QtXml.QDomDocument("fixos")
        assert l_xdoc_fix is not None

        # erro na carga do documento ?
        if not l_xdoc_fix.setContent(l_data_file):
            # fecha o arquivo
            l_data_file.close()

            # logger
            l_log = logging.getLogger("CFixData::parse_fix_xml")
            l_log.setLevel(logging.CRITICAL)
            l_log.critical(u"<E02: falha no parse de {}.".format(fs_fix_pn))

            # cria um evento de quit
            l_evt = events.CQuit()
            assert l_evt

            # dissemina o evento
            self.__event.post(l_evt)

            # termina a aplicação
            sys.exit(1)

        # fecha o arquivo
        l_data_file.close()

        # obtém o elemento raíz do documento
        l_elem_root = l_xdoc_fix.documentElement()
        assert l_elem_root is not None

        # faz o parse dos atributos do elemento raíz
        ldct_root = parser.parse_root_element(l_elem_root)

        # cria uma lista com os elementos de fixo
        l_node_list = l_elem_root.elementsByTagName("fixo")

        # para todos os nós na lista...
        for li_ndx in xrange(l_node_list.length()):
            # inicia o dicionário de dados
            ldct_data = {}

            l_element = l_node_list.at(li_ndx).toElement()
            assert l_element is not None

            # read identification if available
            if l_element.hasAttribute("nFix"):
                ldct_data["nFix"] = str(l_element.attribute("nFix"))

            # obtém o primeiro nó da sub-árvore
            l_node = l_element.firstChild()
            assert l_node is not None

            # percorre a sub-árvore
            while not l_node.isNull():
                # tenta converter o nó em um elemento
                l_element = l_node.toElement()
                assert l_element is not None

                # o nó é um elemento ?
                if not l_element.isNull():
                    # faz o parse do elemento
                    ldct_tmp = parser.parse_fixo(l_element)

                    # atualiza o dicionário de dados
                    ldct_data.update(ldct_tmp)

                # próximo nó
                l_node = l_node.nextSibling()
                assert l_node is not None

            # carrega os dados de fixo a partir de um dicionário
            self.make_fix(ldct_root, ldct_data)
Example #28
0
    def saveQDataStream(self):

        #/ nome do método (logger)
        #/ ----------------------------------------------------------------------------------------
        #l_szMetodo = "clsTabelaPAR::saveQDataStream"

        #/ file descriptor do arquivo de saída
        #/ ----------------------------------------------------------------------------------------
        l_fdOut = None

        #/ mensagem de erro
        #/ ----------------------------------------------------------------------------------------
        l_szError = None

        #** ---------------------------------------------------------------------------------------
        #*  m.poirot logger
        #*/
        #l_log = logging.getLogger ( l_szMetodo )
        #l_log.setLevel ( w_logLvl )
        #l_log.debug ( ">> " )

        #** ---------------------------------------------------------------------------------------
        #*/
        try:

            #** -----------------------------------------------------------------------------------
            #*/
            l_fdOut = QtCore.QFile(self._szFName)
            #assert ( l_fdOut )

            #** -----------------------------------------------------------------------------------
            #*/
            if (not l_fdOut.open(QtCore.QIODevice.WriteOnly)):

                #** -------------------------------------------------------------------------------
                #*/
                raise IOError, unicode(l_fdOut.errorString())

            #** -----------------------------------------------------------------------------------
            #*/
            l_stream = QtCore.QDataStream(l_fdOut)
            #assert ( l_stream )

            #** -----------------------------------------------------------------------------------
            #*/
            l_stream.writeInt32(clsTabelaPAR.c_xxMAGIC_NUMBER)

            #** -----------------------------------------------------------------------------------
            #*/
            l_stream.writeInt32(clsTabelaPAR.c_xxFILE_VERSION)

            #** -----------------------------------------------------------------------------------
            #*/
            l_stream.setVersion(QtCore.QDataStream.Qt_4_2)

            #** -----------------------------------------------------------------------------------
            #*/
            for _, l_PAR in self._aItens:

                #** -------------------------------------------------------------------------------
                #*/
                l_stream << l_PAR._szKey

                #** -------------------------------------------------------------------------------
                #*/
                l_stream << l_PAR._szDescr.replace(' ', '_')

                #** -------------------------------------------------------------------------------
                #*  grava a cabeceira principal
                #*/
                l_stream.writeInt(l_PAR._iCab0)

                #** -------------------------------------------------------------------------------
                #*  grava a altura da antena relativo ao ponto toque principal
                #*/
                l_stream.writeFloat(l_PAR._fHAnt0)

                #** -------------------------------------------------------------------------------
                #*  grava a altura da antena relativo ao ponto toque secundário
                #*/
                l_stream.writeFloat(l_PAR._fHAnt1)

                #** -------------------------------------------------------------------------------
                #*  grava o afastamento da antena ao eixo da pista
                #*/
                l_stream.writeFloat(l_PAR._fDstAntEixo)

                #** -------------------------------------------------------------------------------
                #*  grava a distância da antena ao ponto toque principal
                #*/
                l_stream.writeFloat(l_PAR._fDstAntPT0)

                #** -------------------------------------------------------------------------------
                #*  grava a distância da antena ao ponto toque secundário
                #*/
                l_stream.writeFloat(l_PAR._fDstAntPT1)

                #** -------------------------------------------------------------------------------
                #*  grava o ângulo da rampa de aproximação
                #*/
                l_stream.writeFloat(l_PAR._fAngRampa)

                #** -------------------------------------------------------------------------------
                #*  grava o retardo
                #*/
                l_stream.writeInt(l_PAR._aiRetardo[0])

                #** -------------------------------------------------------------------------------
                #*  grava a declinação magnética
                #*/
                l_stream.writeInt(l_PAR._iDecl)

        #** ---------------------------------------------------------------------------------------
        #*/
        except (IOError, OSError), e:

            #** -----------------------------------------------------------------------------------
            #*/
            l_szError = "Erro no salvamento: {0}".format(e)
Example #29
0
    def handleAction(self, bytecount, action, stream):
        """
        Process server responses by interpreting its intent and then acting upon it
        """
        log("handleAction(%s) - %d bytes" % (action, bytecount))

        if action == "PATH_TO_SIM_MOD":
            path = stream.readQString()
            self.modpath = path
            self.result = self.RESULT_SUCCESS
            return

        elif action == "SIM_MOD_NOT_FOUND":
            log("Error: Unknown sim mod requested.")
            self.modpath = ""
            self.result = self.RESULT_FAILURE
            return

        elif action == "LIST_FILES_TO_UP":
            self.filesToUpdate = eval(str(stream.readQString()))
            if (self.filesToUpdate == None):
                self.filesToUpdate = []
            return

        elif action == "UNKNOWN_APP":
            log("Error: Unknown app/mod requested.")
            self.result = self.RESULT_FAILURE
            return

        elif action == "THIS_PATCH_IS_IN_CREATION EXCEPTION":
            log("Error: Patch is in creation.")
            self.result = self.RESULT_BUSY
            return

        elif action == "VERSION_PATCH_NOT_FOUND":
            response = stream.readQString()
            log("Error: Patch version %s not found for %s." %
                (self.version, response))
            self.writeToServer("REQUEST_VERSION", self.destination, response,
                               self.version)
            return

        elif action == "VERSION_MOD_PATCH_NOT_FOUND":
            response = stream.readQString()
            log("Error: Patch version %s not found for %s." %
                (str(self.modversions), response))
            self.writeToServer("REQUEST_MOD_VERSION", self.destination,
                               response, json.dumps(self.modversions))
            return

        elif action == "PATCH_NOT_FOUND":
            response = stream.readQString()
            log("Error: Patch not found for %s." % response)
            self.writeToServer("REQUEST", self.destination, response)

            return

        elif action == "UP_TO_DATE":
            response = stream.readQString()
            log("file : " + response)
            log("%s is up to date." % response)
            self.filesToUpdate.remove(str(response))
            return

        elif action == "ERROR_FILE":
            response = stream.readQString()
            log("ERROR: File not found on server : %s." % response)
            self.filesToUpdate.remove(str(response))
            self.result = self.RESULT_FAILURE
            return

        elif action == "SEND_FILE_PATH":
            path = stream.readQString()
            fileToCopy = stream.readQString()
            url = stream.readQString()

            toFile = os.path.join(util.APPDATA_DIR, str(path), str(fileToCopy))
            self.fetchFile(url, toFile)
            self.filesToUpdate.remove(str(fileToCopy))

        elif action == "SEND_FILE":
            path = stream.readQString()

            #HACK for feature/new-patcher
            path = util.LUA_DIR if path == "bin" else path

            fileToCopy = stream.readQString()
            size = stream.readInt()
            fileDatas = stream.readRawData(size)

            toFile = os.path.join(util.APPDATA_DIR, str(path), str(fileToCopy))

            writeFile = QtCore.QFile(toFile)

            if (writeFile.open(QtCore.QIODevice.WriteOnly)):
                writeFile.write(fileDatas)
                writeFile.close()
            else:
                logger.warn("%s is not writeable in in %s. Skipping." %
                            (fileToCopy,
                             path))  #This may or may not be desirable behavior

            log("%s is copied in %s." % (fileToCopy, path))
            self.filesToUpdate.remove(str(fileToCopy))

        elif action == "SEND_PATCH_URL":
            destination = str(stream.readQString())
            fileToUpdate = str(stream.readQString())
            url = str(stream.readQString())

            toFile = os.path.join(util.CACHE_DIR, "temp.patch")
            #
            if self.fetchFile(url, toFile):
                completePath = os.path.join(util.APPDATA_DIR, destination,
                                            fileToUpdate)
                self.applyPatch(completePath, toFile)

                log("%s/%s is patched." % (destination, fileToUpdate))
                self.filesToUpdate.remove(str(fileToUpdate))
            else:
                log("Failed to update file :'(")
        else:
            log("Unexpected server command received: " + action)
            self.result = self.RESULT_FAILURE
Example #30
0
    def __init__(self, distributedObjects, filename, parent):
        ScintillaWrapper.__init__(self, parent)
        self.breakpointOverlays = {}

        filename = str(filename)
        self.distributedObjects = distributedObjects
        self.debugController = self.distributedObjects.debugController
        self.__bpModel = self.distributedObjects.breakpointModel
        self.tracepointController = self.distributedObjects.tracepointController
        self.signalProxy = self.distributedObjects.signalProxy
        self.filename = filename
        self.lastContextMenuLine = 0
        self.markerBp = QPixmap(":/markers/bp.png")
        self.markerBpDisabled = QPixmap(":/markers/bp_dis.png")
        self.markerTp = QPixmap(":/markers/tp.png")
        self.markerExec = QPixmap(":/markers/exec_pos.png")
        self.markerStack = QPixmap(":/markers/stack_pos.png")
        self.markerExecSignal = QPixmap(":/markers/exec_pos_signal.png")
        self.shown = False

        self.font = QFont("DejaVu Sans Mono", 10)
        self.font.setStyleHint(QFont.TypeWriter)
        self.lexer = Qsci.QsciLexerCPP()
        self.lexer.setFont(self.font)

        self.setToolTip("")
        self.setWhatsThis("")
        self.setLexer(self.lexer)
        self.setMarginLineNumbers(self.MARGIN_NUMBERS, True)
        # set sensitivity
        self.setMarginSensitivity(self.MARGIN_NUMBERS, True)
        self.setMarginSensitivity(self.MARGIN_MARKER_BP, True)
        self.setMarginSensitivity(self.MARGIN_MARKER_TP, True)
        # define symbol
        self.markerDefine(self.markerBp, self.MARGIN_MARKER_BP)
        self.markerDefine(self.markerBpDisabled, self.MARGIN_MARKER_BP_DIS)
        self.markerDefine(self.markerTp, self.MARGIN_MARKER_TP)
        self.markerDefine(self.markerExec, self.MARGIN_MARKER_EXEC)
        self.markerDefine(self.markerStack, self.MARGIN_MARKER_STACK)
        self.markerDefine(self.markerExecSignal,
                          self.MARGIN_MARKER_EXEC_SIGNAL)
        self.markerDefine(Qsci.QsciScintilla.Background,
                          self.MARKER_HIGHLIGHTED_LINE)

        # define width and mask to show margin
        self.setMarginWidth(self.MARGIN_MARKER_BP, 10)
        self.setMarginMarkerMask(
            self.MARGIN_MARKER_BP,
            1 << self.MARGIN_MARKER_BP | 1 << self.MARGIN_MARKER_BP_DIS)
        self.setMarginWidth(self.MARGIN_MARKER_TP, 10)
        self.setMarginMarkerMask(self.MARGIN_MARKER_TP,
                                 1 << self.MARGIN_MARKER_TP)
        self.setMarginWidth(self.MARGIN_MARKER_EXEC, 10)
        self.setMarginMarkerMask(
            self.MARGIN_MARKER_EXEC,
            1 << self.MARGIN_MARKER_EXEC | 1 << self.MARGIN_MARKER_EXEC_SIGNAL
            | 1 << self.MARGIN_MARKER_STACK)
        self.setMarginWidth(self.MARKER_HIGHLIGHTED_LINE, 0)
        self.setMarginMarkerMask(self.MARKER_HIGHLIGHTED_LINE,
                                 1 << self.MARKER_HIGHLIGHTED_LINE)

        self.INDICATOR_TOOLTIP = self.indicatorDefine(self.BoxIndicator)
        self.setIndicatorDrawUnder(True, self.INDICATOR_TOOLTIP)

        self.setReadOnly(False)

        if not (QtCore.QFile.exists(filename)):
            logging.error("Could not open file %s", filename)

        self.file_ = QtCore.QFile(filename)
        self.file_.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
        self.read(self.file_)
        self.file_.close()

        self.changed = False
        self.modificationChanged.connect(self.__setFileModified)

        self.setMarginWidthByLineNumbers()
        self.SendScintilla(Qsci.QsciScintilla.SCI_SETMOUSEDWELLTIME, 500)

        # override scintillas context menu with our own
        self.SendScintilla(Qsci.QsciScintilla.SCI_USEPOPUP, 0)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)

        self.marginClicked.connect(self.onMarginClicked)
        self.SCN_DOUBLECLICK.connect(self.editDoubleClicked)
        self.dwellStart.connect(self.onDwellStart)
        self.dwellEnd.connect(self.onDwellEnd)

        self.__bpModel.rowsInserted.connect(self.breakpointsInserted)
        # don't connect to rowsRemoved here since the breakpoint is already gone
        # from the model when it's emitted
        self.__bpModel.rowsAboutToBeRemoved.connect(self.breakpointsRemoved)
        self.__bpModel.dataChanged.connect(self.breakpointsModified)
        _model = self.tracepointController.model()
        _model.rowsInserted.connect(self.getTracepointsFromModel)
        _model.rowsRemoved.connect(self.getTracepointsFromModel)

        act = self.distributedObjects.actions
        act.ToggleTrace.triggered.connect(self.toggleTracepoint)

        self.distributedObjects.editorController.config.itemsHaveChanged.connect(
            self.updateConfig)
        self.updateConfig()

        # initially, read all breakpoints and tracepoints from the model
        self.getTracepointsFromModel()

        self.__allowToolTip = True
        self.__enableToolTip(True)

        self.__popupMenu = None

        self.__fileWatcher = QFileSystemWatcher([self.filename])
        self.__fileWatcher.fileChanged.connect(self.__fileChanged)

        # this timer is used for a workaround: QFileSystemWatcher will sometimes
        # report a change multiple times; therefore, in self.__fileChanged, we
        # simply start the timer on a notification and discard all notifications
        # while the timer is running
        self.__fileChangedTimer = QTimer()
        self.__fileChangedTimer.setSingleShot(True)
        self.__fileChangedTimer.setInterval(100)

        self.__wordHighlightTimer = QTimer()
        self.cursorPositionChanged.connect(
            lambda: self.__wordHighlightTimer.start())
        self.__wordHighlightTimer.setSingleShot(True)
        self.__wordHighlightTimer.setInterval(250)
        self.__wordHighlightTimer.timeout.connect(
            self.highlightWordFromCursorPosition)