コード例 #1
0
 def clearCacheReports(self):
     dirci = QDir(self.mDir + QDir.separator() + "tempReports")
     if dirci.exists():
         listFiles = []
         listFiles = dirci.entryList(QDir.Files)
         for sdfile in listFiles:
             QDir().remove(dirci.path() + QDir.separator() + sdfile)
コード例 #2
0
 def clearCacheScaleImage(self):
     dirci = QDir(self.mDir + QDir.separator() + "imagecache")
     if dirci.exists():
         listFiles = []
         listFiles = dirci.entryList(QDir.Files)
         for sdfile in listFiles:
             QDir().remove(dirci.path() + QDir.separator() + sdfile)
コード例 #3
0
    def scaleImage(self, pixels, path):
        dircache = QDir(self.mDir + QDir.separator() + "imagecache")
        if dircache.exists() == False:
            s = QDir(self.mDir)
            s.mkdir("imagecache")

        ima = QImage(path)
        wids = ima.width()
        heis = ima.height()
        if (wids > pixels or heis > pixels):
            imarescale = ima.scaledToWidth(
                pixels, Qt.SmoothTransformation) if (
                    wids > heis) else ima.scaledToHeight(
                        pixels, Qt.SmoothTransformation)

            newImagePath = dircache.path() + QDir.separator(
            ) + "_temp_scaled_" + QFileInfo(path).fileName()
            imawriter = QImageWriter()
            imawriter.setFileName(newImagePath)
            #    imawriter.setFormat("png");
            if (imawriter.write(imarescale)):
                #qDebug()<<"si path"<<newImagePath
                return newImagePath
            else:
                #qDebug()<<"no path"<<newImagePath;
                return path

        return path
コード例 #4
0
ファイル: qjsonnetwork.py プロジェクト: numaelis/thesa
    def runReport(self, pid, method, par):
        self.boolDirect = True
        self.mtypeCall = "report"
        self.mpid = pid
        self.mmethod = method
        self.mparams = par
        #
        bparams = self.prepareParams()
        request = self.prepareRequest()
        #
        reply = self.data_request(request, bparams)
        data = reply.readAll()
        parseError = QJsonParseError()
        resultObject = {}
        resultObject["data"] = "error"
        document = QJsonDocument.fromJson(data, parseError)
        if parseError.error == True:
            resultObject["data"] = "error"
        else:
            if document.isObject():
                jv = document.object()
                if jv.__contains__(
                        "result") == True and jv["result"].__class__() == []:
                    #tryton 4.0
                    #'result': ['pdf', {'base64':wwwwww, '__class__':'bytes'}, False,'Printis']
                    jre = jv["result"]
                    namesecs = "tryton_" + self.mpid + str(
                        QDateTime.currentMSecsSinceEpoch()) + "." + jre[0]

                    mdir = QDir(self.mDir + QDir.separator() + "tempReports")
                    if mdir.exists() == False:
                        s = QDir(self.mDir)
                        s.mkdir("tempReports")

                    filename = self.mDir + QDir.separator(
                    ) + "tempReports" + QDir.separator() + namesecs
                    file = QFile(filename)
                    if file.open(QIODevice.WriteOnly) == False:
                        #error
                        self.signalResponse.emit(self.mpid, 7, {})
                        print("error", filename, file.errorString())
                    else:
                        bafile = QByteArray.fromBase64(
                            jre[1]["base64"].encode())
                        file.write(bafile)
                        file.close()
                        QDesktopServices.openUrl(QUrl(filename))
            else:
                if document.isArray() == True:
                    self.signalResponse.emit(self.mpid, 7, {})
        self.processingData(data, reply)
コード例 #5
0
 def exportDipsToURL(self,
                     dipoles,
                     directoryURL,
                     fileName,
                     addDateToExport=True):
     dateStr = ("-" + QDate.currentDate().toString(Qt.ISODate)
                ) if addDateToExport else ""
     filename = QUrl(directoryURL).toLocalFile() + (
         QDir.separator() + fileName + dateStr + ".csv").replace(" ", "_")
     file = QSaveFile(filename)
     file.open(QIODevice.WriteOnly)
     file.write(
         QByteArray(
             bytearray("x,y,z,phi (°),theta (°),moment (mu_B)\n", 'utf-8')))
     for dip in dipoles:
         angles = anglesQuaternionToSph(dip.quaternion)
         line = str(dip.position.x()) + "," + str(
             dip.position.y()) + "," + str(dip.position.z()) + "," + str(
                 degrees(angles[0])) + "," + str(degrees(
                     angles[1])) + "," + str(dip.moment) + "\n"
         line = QByteArray(bytearray(line, 'utf-8'))
         file.write(line)
     file.commit()
     if (file.errorString() == "Unknown error"):
         return True
     else:
         return False
コード例 #6
0
 def selectSystemTranslation(self, language, typemodule):
     dirsystem = "systemnet" if typemodule == True else "system"
     dirsyslan = QDir(self.mDir + QDir.separator() + dirsystem)
     if dirsyslan.exists():
         if QFileInfo(dirsyslan.path() + QDir.separator() + language +
                      ".qm").exists():
             translator = QTranslator(self)
             translator.load(dirsyslan.path() + QDir.separator() + language)
             self.mApp.installTranslator(translator)
         else:
             language = language.split('_')[0]
             if len(language) == 2:
                 if QFileInfo(dirsyslan.path() + QDir.separator() +
                              language + ".qm").exists():
                     translator = QTranslator(self)
                     translator.load(dirsyslan.path() + QDir.separator() +
                                     language)
                     self.mApp.installTranslator(translator)
コード例 #7
0
    def initializePage(self):
        """Overridden: Prepare the page just before it is shown

        Launch import process if currentPage is ImportPage
        """
        # print("Current PED file", self.field("pedfile"))
        self.db_filename = (self.field("project_path") + QDir.separator() +
                            self.field("project_name") + ".db")
        self.run()
        self.import_button.setDisabled(False)
コード例 #8
0
 def selectCoreTranslation(self, language, settings):
     settings.setValue("translate", "en")
     dircorelan = QDir(self.mDir + QDir.separator() + "corelocale")
     if dircorelan.exists():
         if QFileInfo(dircorelan.path() + QDir.separator() + language +
                      ".qm").exists():
             settings.setValue("translate", language)
             translator = QTranslator(self)
             translator.load(dircorelan.path() + QDir.separator() +
                             language)
             self.mApp.installTranslator(translator)
         else:
             language = language.split('_')[0]
             if len(language) == 2:
                 if QFileInfo(dircorelan.path() + QDir.separator() +
                              language + ".qm").exists():
                     settings.setValue("translate", language)
                     translator = QTranslator(self)
                     translator.load(dircorelan.path() + QDir.separator() +
                                     language)
                     self.mApp.installTranslator(translator)
コード例 #9
0
    def new_project(self):
        """Slot to allow creation of a project with the Wizard"""
        wizard = ProjectWizard()
        if not wizard.exec_():
            return

        db_filename = (wizard.field("project_path") + QDir.separator() +
                       wizard.field("project_name") + ".db")
        try:
            self.open(db_filename)
        except Exception as e:
            self.status_bar.showMessage(e.__class__.__name__ + ": " + str(e))
            raise
コード例 #10
0
 def getListCoreTranslations(self):
     dircorelan = QDir(self.mDir + QDir.separator() + "corelocale")
     if dircorelan.exists():
         fileNames = dircorelan.entryList(["*.qm"])
         listLocale = QJsonArray()
         for i in range(len(fileNames)):
             locale = ""
             locale = fileNames[i]
             locale = locale.split('.')[0]
             listLocale.append(locale)
         listLocale.append("en")
         return listLocale
     return QJsonArray()
コード例 #11
0
ファイル: systemnet.py プロジェクト: numaelis/thesa
 def actionCacheOnCompleted(self):  #version 1.1 up thesamodule
     boolAction = False
     if self.actionCache_ == "deleteOnCompleted":
         sysdir = QDir(self.mDir + QDir.separator() + _dirSystem)
         DIR_QML_SYS = sysdir.path()
         for the_file in os.listdir(DIR_QML_SYS):
             file_path = os.path.join(DIR_QML_SYS, the_file)
             try:
                 if os.path.isfile(file_path):
                     if ".qml" in file_path:
                         os.unlink(file_path)
                 elif os.path.isdir(file_path):
                     shutil.rmtree(file_path)
                 boolAction = True
             except Exception as e:
                 boolAction = False
                 print(e)
     else:
         boolAction = True
     return boolAction
コード例 #12
0
ファイル: main.py プロジェクト: numaelis/thesa
    
    engine.rootContext().setContextProperty("QJsonNetworkQml", jchc)
    engine.rootContext().setContextProperty("ModelManagerQml", modelmanager)
    engine.rootContext().setContextProperty("SystemNet", systemnet)
    
    engine.rootContext().setContextProperty("ThesaVersion", ThesaVersion)
    
    engine.rootContext().setContextProperty("Tools", mtools)
    
    engine.rootContext().setContextProperty("DirParent", mDir)
    
    engine.rootContext().setContextProperty("ObjectMessageLast", mObjMsg)

    settings = QSettings()
    defaultLocale = settings.value("translate", "")
    if defaultLocale=="":
        defaultLocale = QLocale.system().name()
    mtools.selectCoreTranslation(defaultLocale, settings)
    
    engine.addImportPath(mDir + QDir.separator() + "tools")
	#engine.load(QUrl("qrc:/main.qml"))
    engine.load(QUrl.fromLocalFile('main.qml'))
    
    if not engine.rootObjects():
        msgBox = QMessageBox()
        msgBox.setText("Error rootObjects")
        msgBox.exec_()
        sys.exit(-1)
        
    sys.exit(app.exec_())
コード例 #13
0
ファイル: systemnet.py プロジェクト: numaelis/thesa
    def rechargeNet(self, preferences, username):
        #version 1.1 up thesamodule
        data = self.m_qjsonnetwork.callDirect(
            "version internal", "model.thesamodule.config.search_read",
            [[], 0, 1, [], ["internal_version"], preferences])
        if not data["data"] == "error":
            self.internal_version = data["data"]["result"][0][
                "internal_version"]
            if float(self.internal_version) > 1.0:
                data = self.m_qjsonnetwork.callDirect(
                    "cachedel", "model.thesamodule.config.search_read",
                    [[], 0, 1, [], ["deletecache"], preferences])
                if not data["data"] == "error":
                    if data["data"]["result"][0]["deletecache"] == True:
                        self.actionCache_ = "deleteOnCompleted"
                    else:
                        self.actionCache_ = "notDelete"
        sysdir = QDir(self.mDir + QDir.separator() + _dirSystem)
        DIR_QML_SYS = sysdir.path()
        DIR_QML_SYS_LOST = DIR_QML_SYS + QDir.separator() + "lost"
        sysdirlost = QDir(DIR_QML_SYS_LOST)
        #revisar folder systemnet
        if sysdir.exists() == False:
            s = QDir(self.mDir)
            s.mkdir(_dirSystem)
        #revisar folder systemnet lost
        if sysdirlost.exists() == False:
            sl = QDir(DIR_QML_SYS)
            sl.mkdir("lost")
        #find all files en folder net
        listSysFiles = os.listdir(DIR_QML_SYS)
        if "lost" in listSysFiles:
            listSysFiles.remove("lost")
        #
        data = {}
        data["data"] = "error"
        if float(self.internal_version) > 1.1:
            data = self.m_qjsonnetwork.callDirect(
                "findforuser", "model.thesamodule.usersfolder.search_read", [[
                    "AND", ["users.user.name", "=", username],
                    ["activefolder", "=", True]
                ], 0, 1, [], ["qmlfiles"], preferences])
            if not data["data"] == "error":
                result = data["data"]["result"]
                if len(result) > 0:
                    idfiles = result[0]["qmlfiles"]
                    data = self.m_qjsonnetwork.callDirect(
                        "rechargeNetStep1",
                        "model.thesamodule.thesamodule.read",
                        [idfiles, [
                            "checksum",
                            "filename",
                        ], preferences])
                    if len(idfiles) == 0:
                        self.m_qjsonnetwork.signalResponse.emit(
                            "systemnet", 15, {"noqmlfiles": ""})
                else:  #buscar default
                    data = self.m_qjsonnetwork.callDirect(
                        "findforuser",
                        "model.thesamodule.usersfolder.search_read", [[
                            "AND", ["type", "=", "default"],
                            ["activefolder", "=", True]
                        ], 0, 1, [], ["qmlfiles"], preferences])
                    if not data["data"] == "error":
                        result = data["data"]["result"]
                        if len(result) > 0:
                            idfiles = result[0]["qmlfiles"]
                            data = self.m_qjsonnetwork.callDirect(
                                "rechargeNetStep1",
                                "model.thesamodule.thesamodule.read", [
                                    idfiles, [
                                        "checksum",
                                        "filename",
                                    ], preferences
                                ])
                            if len(idfiles) == 0:
                                self.m_qjsonnetwork.signalResponse.emit(
                                    "systemnet", 15, {"noqmlfiles": ""})
                        else:
                            self.m_qjsonnetwork.signalResponse.emit(
                                "systemnet", 12, {"noqmlfiles": ""})
                    else:
                        self.m_qjsonnetwork.signalResponse.emit(
                            "systemnet", 13, {"error": ""})
            else:
                self.m_qjsonnetwork.signalResponse.emit(
                    "systemnet", 13, {"error": ""})

        else:
            data = self.m_qjsonnetwork.callDirect(
                "rechargeNetStep1",
                "model.thesamodule.thesamodule.search_read",
                [[], 0, 1000, [], ["checksum", "filename"], preferences])
        if not data["data"] == "error":
            resultnet = data["data"]["result"]
            mapnet = {}
            mapids = {}
            listNetFiles = []
            for file in resultnet:
                mapnet[file["filename"]] = file["checksum"]
                mapids[file["filename"]] = file["id"]
                listNetFiles.append(file["filename"])
            #buscar faltantes en system y los updates
            #buscar los que ya no deben estar
            mapsysnet = {}
            listToUpdate = set()  #new or update
            listToErase = []
            for file in listSysFiles:
                try:
                    with open(DIR_QML_SYS + QDir.separator() + file,
                              "rb") as binary_file:
                        data = binary_file.read()
                        chek = hashlib.md5(data).hexdigest()
                        mapsysnet[file] = chek
                except:
                    listToUpdate.add(file)

            for file in listNetFiles:
                if file in listSysFiles:
                    if mapnet[file] != mapsysnet[file]:
                        listToUpdate.add(file)  # update
                else:
                    listToUpdate.add(file)  # new
            for file in listSysFiles:
                if not file in listNetFiles:
                    listToErase.append(file)  # erase

            listToUpdate = list(listToUpdate)
            ids = []
            for file in listToUpdate:
                ids.append(mapids[file])

            data = self.m_qjsonnetwork.callDirect(
                "rechargeNetStep2", "model.thesamodule.thesamodule.read",
                [ids, [
                    "filebinary",
                    "filename",
                ], preferences])
            errors = []
            if not data["data"] == "error":
                resultnet = data["data"]["result"]
                for file in resultnet:
                    filename = DIR_QML_SYS + QDir.separator(
                    ) + file["filename"]
                    qfile = QFile(filename)
                    if qfile.open(QIODevice.WriteOnly) == False:
                        errors.append(filename)
                        print("error", filename, qfile.errorString())
                    else:
                        print("update", file["filename"])
                        bafile = QByteArray.fromBase64(
                            file["filebinary"]["base64"].encode())
                        qfile.write(bafile)
                        qfile.close()
            if len(errors) > 0:
                self.m_qjsonnetwork.signalResponse.emit(
                    "systemnet", 33, {"error": errors})
                return False

            #erase
            for file in listToErase:
                print("moviendo", file)
                shutil.move(DIR_QML_SYS + QDir.separator() + file,
                            DIR_QML_SYS_LOST + QDir.separator() + file)
            return True
        else:
            #erase all files, no conexion con thesa module
            for file in listSysFiles:
                print("moviendo", file)
                shutil.move(DIR_QML_SYS + QDir.separator() + file,
                            DIR_QML_SYS_LOST + QDir.separator() + file)
            self.m_qjsonnetwork.signalResponse.emit("systemnet", 34,
                                                    {"error": ""})
            return False
コード例 #14
0
def organize_files():
    separator = window.cmb_separator.currentText()

    target_dir = QDir(window.edit_target_dir.text())
    list_target_dirs = target_dir.entryList()

    progress = progress_window()
    progress.set_max(window.list_files.count())

    for index in range(window.list_files.count()):
        progress.set_value(index)

        #
        # STEP 1: Create target directory if necessary
        #

        # Get folder name for file
        fn_src = window.list_files.item(index).text()
        progress.set_text("Processing \"{0}\"".format(fn_src))

        md = pyexiv2.ImageMetadata(fn_src)

        image_ts = datetime.date
        try:
            md.read()
            image_ts = md['Exif.Photo.DateTimeOriginal'].value

        except:
            print("Cannot open file \"{0}\"".format(fn_src))
            continue

        # Makes sure the day and month are always two digits
        def correct_format(number):
            if number < 10:
                return "0" + str(number)
            else:
                return str(number)

        folder_name_trg = str(image_ts.year) + separator + correct_format(
            image_ts.month) + separator + correct_format(image_ts.day)
        dir_name_trg = target_dir.absolutePath() + QDir.separator(
        ) + folder_name_trg

        # Create folder for day if necessary
        target_folder = QDir(dir_name_trg)
        if not target_folder.exists():
            QDir.mkdir(target_dir, dir_name_trg)
            print("Created directory \"{0}\"".format(dir_name_trg))

        #
        # STEP 2: Move file
        #

        # absolute file name of the new file
        fn_trg_abs = dir_name_trg + QDir.separator() + fn_src.split(
            QDir.separator())[-1]
        file_trg = QFile(fn_trg_abs)

        # Don't overwrite existing files
        if file_trg.exists():
            print("Skipping file \"{0}\"".format(file_trg.fileName()))
            continue

        QFile.copy(fn_src, fn_trg_abs)
        print("Copied file from \"{0}\" to \"{1}\"".format(fn_src, fn_trg_abs))

    print("Finished!")