Пример #1
0
    def save_recent_projects(self, folder):
        settings = IDE.data_settings()
        recent_project_list = settings.value('recentProjects', {})
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

        if name == '':
            name = file_manager.get_basename(folder)

        if description == '':
            description = translations.TR_NO_DESCRIPTION

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open(
                    recent_project_list)]
        settings.setValue('recentProjects', recent_project_list)
Пример #2
0
    def SaveAnalyseResult(self):
        r = QMessageBox.warning(self, "注意!", "是否全部运行完?",
                                QMessageBox.Yes | QMessageBox.No)
        if r == QMessageBox.Yes:
            data_dist = {
                'EmitSignal': model.run1DB.get('EmitSignal'),
                'ClutterSignal': model.run1DB.get('ClutterSignal'),
                'ClutterSignalFFT': model.run1DB.get('ClutterSignalFFT'),
                'MTIout': model.run1DB.get('MTIout'),
                'MTDout': model.run1DB.get('MTDout'),
                'DetectionProbality': model.run1DB.get('DetectionProbality'),
                'CatchTime': model.run1DB.get('CatchTime'),
            }
            data_dist2 = {
                'N': model.run2DB.get('N'),
                'number': model.run2DB.get('number'),

                'SampleRate': model.run1DB.get('SampleRate'),
            }
            try:
                model.lastDB.append(data_dist)
                model.lastDB.append(data_dist2)
                model.lastDB.dump()
                self.parent().textBrowser.append(
                    QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次仿真结果---成功")
            except TypeError:
                QMessageBox.warning(self, "注意!", "数据类型错误或不存在")
                self.parent().textBrowser.append(
                    QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次仿真结果---失败(数据类型错误或不存在)")
        else:
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次仿真结果---失败(未运行所有结果)")
Пример #3
0
 def minimum( self ):
     """
     Returns the minimum value for this ruler.  If the cached value is None,
     then a default value will be specified based on the ruler type.
     
     :return     <variant>
     """
     if ( self._minimum is not None ):
         return self._minimum
     
     rtype = self.rulerType()
     
     if ( rtype == XChartRuler.Type.Number ):
         self._minimum = 0
         
     elif ( rtype == XChartRuler.Type.Date ):
         self._minimum = QDate.currentDate()
     
     elif ( rtype == XChartRuler.Type.Datetime ):
         self._minimum = QDateTime.currentDateTime()
     
     elif ( rtype == XChartRuler.Type.Time ):
         self._minimum = QDateTime.currentDateTime().time()
     
     else:
         notches = self.notches()
         if ( notches ):
             self._minimum = notches[0]
     
     return self._minimum
Пример #4
0
    def MissileMatTriggered(self):
        # 读取MAT
        self.parent().textBrowser.append(
            QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "读取导弹参数设定文件")
        self.LoadMissileMat = QFileDialog.getOpenFileName(self, "Load a missile Mat File!", ".", "MAT Files (*.mat)")
        self.lineEdit_7.setText(self.LoadMissileMat)
        self.textBrowser_5.clear()
        # 检查filename是否存在,内容是否合理!!
        if self.LoadMissileMat:
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString(
                    "yyyy.MM.dd hh:mm:ss:zzz ") + "尝试显示文件" + self.LoadMissileMat + "中具体参数内容")
            mat_content = sio.loadmat(self.LoadMissileMat)
            try:
                self.Missile_Data_dic = {
                    'mp_L': mat_content['mp_L'][0, 0], 'mp_B': mat_content['mp_B'][0, 0],
                    'mp_H': mat_content['mp_H'][0, 0],
                    'mv_x': mat_content['mv_x'][0, 0], 'mv_y': mat_content['mv_y'][0, 0],
                    'mv_z': mat_content['mv_z'][0, 0],
                    'ma_x': mat_content['ma_x'][0, 0], 'ma_y': mat_content['ma_y'][0, 0],
                    'ma_z': mat_content['ma_z'][0, 0],
                }
                content_string = ''.join('{}: {}\n'.format(key, var) for key, var in sorted(self.Missile_Data_dic.items()))
                self.textBrowser_5.setText(content_string)
                self.parent().textBrowser.append(
                    QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "显示"+ self.LoadMissileMat + "成功")
            except KeyError:
                self.LoadMissileMat=""
                self.textBrowser_5.setText('对不起,该参数文件已损坏,请尝试其他参数文件,或自行设定具体参数内容')
                self.parent().textBrowser.append(
                    QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "显示过程中发现参数设定文件已损坏")

        else:
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "导弹参数设定文件路径未设定")
Пример #5
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings().value('recentProjects', {})
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

        if name == '':
            name = file_manager.get_basename(folder)

        if description == '':
            description = self.tr('no description available')

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False,
                "lastopen": QDateTime.currentDateTime()
            }
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings().setValue('recentProjects', recent_project_list)
Пример #6
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings().value('recentProjects', {}).toMap()
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

        if name == '':
            name = file_manager.get_basename(folder)

        if description == '':
            description = self.tr('no description available')

        if QString(folder) in recent_project_list:
            properties = recent_project_list[QString(folder)].toMap()
            properties[QString("lastopen")] = QDateTime.currentDateTime()
            properties[QString("name")] = name
            properties[QString("description")] = description
            recent_project_list[QString(folder)] = properties
        else:
            recent_project_list[QString(folder)] = {
                "name": name,
                "description": description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings().setValue('recentProjects', recent_project_list)
Пример #7
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings(
            resources.SETTINGS_PATH, QSettings.IniFormat).value(
                'recentProjects', {})

        project = nproject.NProject(folder)
        #if already exist on the list update the date time
        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = project.name
            properties["description"] = project.description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": project.name,
                "description": project.description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings(resources.SETTINGS_PATH, QSettings.IniFormat).setValue(
            'recentProjects', recent_project_list)
Пример #8
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings().value("recentProjects", {})
        # if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get("name", "")
        description = projectProperties.get("description", "")

        if name == "":
            name = file_manager.get_basename(folder)

        if description == "":
            description = self.tr("no description available")

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False,
                "lastopen": QDateTime.currentDateTime(),
            }
            # if the length of the project list it's high that 10 then delete
            # the most old
            # TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings().setValue("recentProjects", recent_project_list)
Пример #9
0
    def IfGet(self):
        def plot1():
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "捕获时间分析-结束")
            CatchT = model.run1DB.get('CatchTime')
            if CatchT == 0:
                QMessageBox.information(self, "注意!", "星载雷达没有截获导弹",
                                        QMessageBox.Ok)
            else:
                self.lineEdit_24.setText('%d' % CatchT)

        def plot2():
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "捕获概率分析-结束")
            detectionP = model.run1DB.get('DetectionProbality')
            self.lineEdit_23.setText('%.7f' % detectionP)

        self.parent().textBrowser.append(
            QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "捕获时间分析-开始")
        with self.lock:
            self.newthread = PlotThread(Process.CatchTime, plot1)
            self.newthread.start()

        self.parent().textBrowser.append(
            QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "捕获概率分析-开始")
        with self.lock:
            self.newthread = PlotThread(Process.DetectionProbality, plot2)
            self.newthread.start()
Пример #10
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings(
            resources.SETTINGS_PATH, QSettings.IniFormat).value(
                'recentProjects', {})

        project = nproject.NProject(folder)
        #if already exist on the list update the date time
        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = project.name
            properties["description"] = project.description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": project.name,
                "description": project.description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open()]
        QSettings(resources.SETTINGS_PATH, QSettings.IniFormat).setValue(
            'recentProjects', recent_project_list)
Пример #11
0
 def emit_now(self):
     formatted_date = self.meet.daysTo(QDateTime.currentDateTime())
     one_day_seconds = (self.meet.secsTo(QDateTime.currentDateTime())
               - formatted_date *24 * 60 * 60)
     hours = one_day_seconds / 3600
     minutes = one_day_seconds / 60 - hours * 60 
     seconds = one_day_seconds % 60
     msgString = u'亲爱的,从我们相遇至今已经有 %s天 %s小时 %s分钟 %s秒了 \n\n\n你是我的天使,每一分钟,每一秒钟我都很宝贝.\n\n你呢 每天都要快快乐乐的知道么\n\n睡个好觉 做个好梦\n\n么么 wanan' \
                 % (unicode(formatted_date),unicode(hours),unicode(minutes),unicode(seconds),)
     self.now.emit(msgString)
Пример #12
0
        def plot1():
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "回波信号时域分析-分析结果生成完毕")
            ClutterSignal = model.run1DB.get('ClutterSignal')[0]

            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "回波信号时域分析-显示分析结果")
            plt.ion()
            plt.plot(np.real(ClutterSignal))
            plt.xlabel("采样点")
            plt.ylabel("幅度")
            plt.title("雷达回波时域波形分析")
    def btnEvaluate_Click(self):   #### ---------------  Export  -------------------###
        if ProcedureExportDlg.dataBase == None:
            return
        filePathDir = QFileDialog.getSaveFileName(self, "Save Data",QCoreApplication.applicationDirPath (),"XML Files (*.xml)")
        if filePathDir == "":
            return

        effectiveDate = ProcedureExportDlg.dataBase.EffectiveDate;
        resultDlg, effectiveDate = DlgAixmEffectiveDate.smethod_0(effectiveDate)
        if (not resultDlg):
            return;
        xmlDocument = QDomDocument()
        xmlDeclaration = xmlDocument.createProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\"" )
        xmlDocument.appendChild(xmlDeclaration)
        xmlElement = xmlDocument.createElement("AIXM-update")
        # xmlAttribute = xmlDocument.createAttribute("xsi")
        # xmlAttribute.setValue("http://www.w3.org/2001/XMLSchema-instance")
        xmlElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        xmlElement.setAttribute("xsi:noNamespaceSchemaLocation", "AIXM+Update.xsd");
    #     xmlAttribute.Value = "AIXM+Update.xsd";
        xmlElement.setAttribute("version", "4.5");
        xmlElement.setAttribute("origin", "ASAP s.r.o.");
        strS = QDateTime.currentDateTime().toString("yyyy-MM-dd");
        now = QDateTime.currentDateTime();
        xmlElement.setAttribute("created", String.Concat([strS, "T", now.toString("hh:mm:ss")]));
        xmlElement.setAttribute("effective", String.Concat([effectiveDate.toString("yyyy-MM-dd"), "T00:00:00"]));
        # xmlElement.Attributes.Append(xmlAttribute);
        xmlDocument.appendChild(xmlElement)
        xmlElement1 = xmlDocument.createElement("Group");
        xmlElement1.setAttribute("Name", "Group 1 of 1");
        ProcedureExportDlg.dataBase.ProcedureData.method_61(xmlElement1, self.newProcedurePointsInUse);
        ProcedureExportDlg.dataBase.ProcedureData.method_62(xmlElement1, ProcedureExportDlg.dataBase.SIDs.Select({"deleted":"True", "new":"False"}), DataBaseProcedureExportDlgType.Deleted);
        ProcedureExportDlg.dataBase.ProcedureData.method_62(xmlElement1, ProcedureExportDlg.dataBase.SIDs.Select({"deleted":"False", "changed":"True", "new":"False"}), DataBaseProcedureExportDlgType.Updated);
        ProcedureExportDlg.dataBase.ProcedureData.method_62(xmlElement1, ProcedureExportDlg.dataBase.SIDs.Select({"deleted":"False", "new":"True"}), DataBaseProcedureExportDlgType.Created);
        ProcedureExportDlg.dataBase.ProcedureData.method_63(xmlElement1, ProcedureExportDlg.dataBase.STARs.Select({"deleted":"True", "new":"False"}), DataBaseProcedureExportDlgType.Deleted);
        ProcedureExportDlg.dataBase.ProcedureData.method_63(xmlElement1, ProcedureExportDlg.dataBase.STARs.Select({"deleted":"False", "changed":"True", "new":"False"}), DataBaseProcedureExportDlgType.Updated);
        ProcedureExportDlg.dataBase.ProcedureData.method_63(xmlElement1, ProcedureExportDlg.dataBase.STARs.Select({"deleted":"False", "new":"True"}), DataBaseProcedureExportDlgType.Created);
        ProcedureExportDlg.dataBase.ProcedureData.method_64(xmlElement1, ProcedureExportDlg.dataBase.IAPs.Select({"deleted":"True", "new":"False"}), DataBaseProcedureExportDlgType.Deleted);
        ProcedureExportDlg.dataBase.ProcedureData.method_64(xmlElement1, ProcedureExportDlg.dataBase.IAPs.Select({"deleted":"False", "changed":"True", "new":"False"}), DataBaseProcedureExportDlgType.Updated);
        ProcedureExportDlg.dataBase.ProcedureData.method_64(xmlElement1, ProcedureExportDlg.dataBase.IAPs.Select({"deleted":"False", "new":"True"}), DataBaseProcedureExportDlgType.Created);
        ProcedureExportDlg.dataBase.ProcedureData.method_65(xmlElement1, ProcedureExportDlg.dataBase.Holdings.Select({"deleted":"True", "new":"False"}), DataBaseProcedureExportDlgType.Deleted);
        ProcedureExportDlg.dataBase.ProcedureData.method_65(xmlElement1, ProcedureExportDlg.dataBase.Holdings.Select({"deleted":"False", "changed":"True", "new":"False"}), DataBaseProcedureExportDlgType.Updated);
        ProcedureExportDlg.dataBase.ProcedureData.method_65(xmlElement1, ProcedureExportDlg.dataBase.Holdings.Select({"deleted":"False", "new":"True"}), DataBaseProcedureExportDlgType.Created);
        xmlElement.appendChild(xmlElement1);
    #     xmlDocument.Save(self.sfd.FileName);
    #     base.method_20(string.Format(Messages.X_SUCCESSFULLY_CREATED, self.pnlFile.Value));
        qFile = QFile(filePathDir)
        if qFile.open(QFile.WriteOnly):
            textStream = QTextStream(qFile)
            xmlDocument.save(textStream, 4)
            qFile.close()
        else:
            raise UserWarning, "can not open file:" + filePathDir
Пример #14
0
 def ReadAllMatTriggered(self):
     self.parent().textBrowser.append(
         QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "读取全部参数设定文件")
     self.Wzard3LoadFileName = QFileDialog.getOpenFileName(self, "Load a File!", ".", "MAT Files (*.mat)")
     self.lineEdit.setText(self.Wzard3LoadFileName)
     self.textBrowser_2.clear()
     if self.Wzard3LoadFileName:
         self.parent().textBrowser.append(
             QDateTime.currentDateTime().toString(
                 "yyyy.MM.dd hh:mm:ss:zzz ") + "尝试显示文件" + self.Wzard3LoadFileName + "中具体参数内容")
         mat_content = sio.loadmat(self.Wzard3LoadFileName)
         # 检查filename内容是否合理!!
         try:
             Data_dic = {
                 # 卫星参数
                 'sp_L': mat_content['sp_L'][0, 0], 'sp_B': mat_content['sp_B'][0, 0],
                 'sp_H': mat_content['sp_H'][0, 0],
                 'sv_x': mat_content['sv_x'][0, 0], 'sv_y': mat_content['sv_y'][0, 0],
                 'sv_z': mat_content['sv_z'][0, 0],
                 # 导弹参数
                 'mp_L': mat_content['mp_L'][0, 0], 'mp_B': mat_content['mp_B'][0, 0],
                 'mp_H': mat_content['mp_H'][0, 0],
                 'mv_x': mat_content['mv_x'][0, 0], 'mv_y': mat_content['mv_y'][0, 0],
                 'mv_z': mat_content['mv_z'][0, 0],
                 'ma_x': mat_content['ma_x'][0, 0], 'ma_y': mat_content['ma_y'][0, 0],
                 'ma_z': mat_content['ma_z'][0, 0],
                 # 雷达参数
                 'PeakPower': mat_content['PeakPower'][0, 0], 'PulseWidth': mat_content['PulseWidth'][0, 0],
                 'PRF': mat_content['PRF'][0, 0], 'WorkBand': mat_content['WorkBand'][0, 0],
                 'SampleRate': mat_content['SampleRate'][0, 0], 'Pfa': mat_content['Pfa'][0, 0],
                 'EmitChoose': mat_content['EmitChoose'][0, 0],
                 # 天线参数
                 'BeamWidth': mat_content['BeamWidth'][0, 0], 'PitchAngle': mat_content['PitchAngle'][0, 0],
                 'AzimuthAngle': mat_content['AzimuthAngle'][0, 0],
                 # 杂波参数
                 'ClutterChoose': mat_content['ClutterChoose'][0, 0],
             }
             comVar.simpleHandle(Data_dic)
             content_string = ''.join('{}: {}\n'.format(key, var) for key, var in sorted(Data_dic.items()))
             self.textBrowser_2.setText(content_string)
             self.parent().textBrowser.append(
                 QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "显示参数成功")
         except KeyError:
             self.Wzard3LoadFileName = ""
             self.textBrowser_2.setText('对不起,该参数文件已损坏,请尝试其他参数文件,或自行设定具体参数内容')
             self.parent().textBrowser.append(
                 QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "显示过程中发现参数设定文件已损坏")
     else:
         self.parent().textBrowser.append(
             QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "参数设定文件所在路径未设置")
Пример #15
0
    def __init__( self, parent = None ):
        super( FrmBalanceInicial, self ).__init__( parent )
        self.setupUi( self )
        self.__status = False
        self.database = QSqlDatabase.database()
        self.user = user.LoggedUser
        self.actionNuevo.setVisible(False)
        self.widget.setHidden(True)
        

#        self.setMaximumSize(600,300)
        try:
            if not self.database.isOpen():
                if not self.database.open():
                    raise UserWarning( "No se pudo abrir la base de datos" )

            self.editModel = BalanceInicialModel()
            self.editModel.insertRow( 1 )
            self.editModel.insertRow( 1 )
            self.editModel.lines[1].name= "CAPITAL"
            self.editModel.lines[1].code = "320 001 000 000 000"
            
            self.startUI()

            delegate = AccountsSelectorDelegate( QSqlQuery( """
            SELECT 
                c.idcuenta, 
                c.codigo, 
                c.descripcion 
            FROM cuentascontables c 
            JOIN cuentascontables p ON c.padre = p.idcuenta AND p.padre != 1
            """ ) )

            self.dtPicker.setDateTime( QDateTime.currentDateTime() )
            self.dtPicker.setMaximumDateTime( QDateTime.currentDateTime() )
            self.dtPicker.setReadOnly(False)

            self.tableDetails.setModel( self.editModel )
            self.tableDetails.setColumnHidden( IDCUENTA, True )
            self.tableDetails.setColumnHidden( IDDOCUMENTOC, True )
            self.tableDetails.setItemDelegate( delegate )
            self.tableDetails.resizeColumnsToContents()
        except UserWarning as inst:
            self.status = False
            QMessageBox.critical( self, qApp.organizationName(), unicode( inst ) )
            logging.error( unicode( inst ) )
        except Exception as inst:
            QMessageBox.critical( self, qApp.organizationName(), "Hubo un error al tratar de iniciar el Balance Inicial" )
            logging.critical( unicode( inst ) )
Пример #16
0
    def _init_options(self):
        PrinterBaseDialog._init_options(self)

        for label, value, selected in self.lasts:
            self.ui.lastEdit.addItem(label, QVariant(value))
            if selected:
                self.ui.lastEdit.setCurrentIndex(self.ui.lastEdit.count() - 1)
        for i, (label, func) in enumerate(self.contextual_intervals):
            # for each contextual interval, the data is a negative number to distinct
            # with intervals.
            # this is the negative number of indexes.
            self.ui.lastEdit.addItem(label, QVariant(-i))

        self.ui.startDate.setDateTime(QDateTime.currentDateTime().addDays(-1))
        self.ui.endDate.setDateTime(QDateTime.currentDateTime())
Пример #17
0
 def insertPhoto(self, db, photo_id, photo, number):
     table = self.DBConfig['table']
     linkcode = self.DBConfig['linkcode']
     date = QDateTime.currentDateTime().toLocalTime().toString()
     sql = "INSERT INTO '{0}' (linkid, photo, photo_id, timestamp, photo_number, linkname) VALUES ('{1}', '{2}', '{3}', '{4}', {5}, '{6}')".format(
         table, self.linkid, photo, photo_id, date, number, linkcode)
     db.execute(sql)
Пример #18
0
    def init_ui(self):
        """
        init ui
        :return:
        """
        QDialog.__init__(self)
        Ui_CraneTestDocWnd.__init__(self)
        self.setupUi(self)
        self.testcase_tree.clear()
        # 初始化下拉框
        self.test_person_combox.addItems(self.config[TEST_PERSON_KEY])
        self.test_cat_combox.addItems(self.config[TEST_CAT_KEY])
        self.test_env_combox.addItems(self.config[TEST_ENV_KEY])
        self.qualified_method_combox.addItems(self.config[TEST_REQ_METHOD_KEY])
        # 设置表格宽度
        self.test_procedure_tabel.setColumnWidth(0, 50)
        self.test_procedure_tabel.setColumnWidth(1, 300)
        self.test_procedure_tabel.setColumnWidth(2, 300)
        self.test_procedure_tabel.setColumnWidth(3, 300)
        self.test_procedure_tabel.setColumnWidth(6, 0)
        # 设置时间选择框
        self.test_date_timepickedit.setDateTime(QDateTime.currentDateTime())
        # 初始化进度条
        self.process_progressbar.setValue(0)

        # 设置窗口大小
        self.resize(1700, 900)
Пример #19
0
    def __init__(self, parent, directory, models):
        self._parent = parent
        self._models = None

        self.gui = self._parent._ui
        self._filters_values = {
            "afterWeekday": self.gui.afterWeekdayFilterComboBox.currentIndex,
            "beforeWeekday": self.gui.beforeWeekdayFilterComboBox.currentIndex,
            "beforeDate": self.gui.beforeDateFilterDateEdit.date,
            "afterDate": self.gui.afterDateFilterDateEdit.date,
            "beforeHour": self.gui.beforeHourFilterTimeEdit.time,
            "afterHour": self.gui.afterHourFilterTimeEdit.time,
            "message": self.gui.messageFilterLineEdit.text,
            "nameEmail": self.gui.nameEmailFilterLineEdit.text,
            "localOnly": None
        }

        self._shown_columns = []
        self._checkboxes = {}
        self._model = None

        self.reset_interface(models)

        self.connect_slots()

        # Initialize the dateEdit widgets
        dateedits = [self.gui.beforeDateFilterDateEdit,
                     self.gui.afterDateFilterDateEdit,
                     self.gui.reOrderMinDateEdit,
                     self.gui.reOrderMaxDateEdit]

        for dateedit in dateedits:
            dateedit.setDateTime(QDateTime.currentDateTime())
    def createRequest(self, op, req, outgoingData):
        do_action('NetworkAccessManagerCreateRequestPre')

        reply = QNetworkAccessManager.createRequest(self, op, req, outgoingData)

        if self.m_ignoreSslErrors:
            reply.ignoreSslErrors()

        headers = []
        for header in req.rawHeaderList():
            header = {
                'name': str(header),
                'value': str(req.rawHeader(header))
            }
            headers.append(header)

        self.m_idCounter += 1
        self.m_ids[reply] = self.m_idCounter

        data = {
            'id': self.m_idCounter,
            'url': req.url().toString(),
            'method': self.operationToString(op),
            'headers': headers,
            'time': QDateTime.currentDateTime()
        }

        reply.readyRead.connect(self.handleStarted)

        do_action('NetworkAccessManagerCreateRequestPost')

        self.resourceRequested.emit(data)
        return reply
Пример #21
0
    def EmitWaveAnalyse(self):
        def plot1():
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "雷达发射信号分析-完成信号生成")

            Esignal = model.run1DB.get('EmitSignal')
            N = model.run2DB.get('N')
            num = model.run2DB.get('number')

            signal_temp = np.zeros(N, dtype=complex)
            signal_temp[0: num] = Esignal
            In1signal = np.kron(np.ones((1, 18)), signal_temp)
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "雷达发射信号分析-显示生成的信号")
            plt.ion()
            plt.plot(np.real(In1signal[0]))
            plt.xlabel("采样点数")
            plt.ylabel("幅度")
            plt.title("雷达发射信号时域波形")

        with self.lock:
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "雷达发射信号分析-开始")
            self.newthread = PlotThread(Process.Transmit, plot1)
            self.newthread.start()
Пример #22
0
 def clear_case_content(self):
     """
     清除显示的内容
     :return:
     """
     self.test_caseidentify_edit.setText('')
     self.test_item_edit.setText('')
     self.test_cat_combox.setCurrentIndex(0)
     self.require_trace_edit.setText('')
     self.test_content_edit.setText('')
     self.sys_prepare_edit.setText('')
     self.precondation_edit.setText('')
     self.test_input_edit.setText('')
     for i in range(0, self.test_procedure_tabel.rowCount()):
         self.test_procedure_tabel.removeRow(0)
     self.estimate_rule_eidt.setText('')
     self.test_env_combox.setCurrentIndex(0)
     self.qualified_method_combox.setCurrentIndex(0)
     self.safe_secret_edit.setText('')
     self.test_person_combox.setCurrentIndex(0)
     self.test_person_join_edit.setText('')
     self.test_date_timepickedit.setDateTime(QDateTime.currentDateTime())
     self.test_data_edit.setText('')
     self.problem_sheet_edit.setText('')
     self.correct_sheet_edit.setText('')
     self.test_diff_edit.setText('')
Пример #23
0
    def postionupdated(self, position, info):
        if not self.logging or not self.layer or not self.layerprovider:
            return

        feature = QgsFeature()
        feature.setFields(self.fields)

        for field in self.fields:
            name = field.name()
            if name == 'time':
                value = self.gps.gpsinfo('utcDateTime').toString(Qt.ISODate)
            elif name == 'localtime':
                value = QDateTime.currentDateTime().toString(Qt.ISODate)
            elif name == 'user':
                value = getpass.getuser()
            else:
                try:
                    value = self.gps.gpsinfo(name)
                except AttributeError:
                    continue

            feature[name] = value

        geom = QgsGeometry.fromPoint(position)
        feature.setGeometry(geom)
        self.featurecache.append(feature)
        if len(self.featurecache) > 5:
            self.layerprovider.addFeatures(self.featurecache)
            self.featurecache = []
    def handleFinished(self, reply):
        headers = []
        for header in reply.rawHeaderList():
            header = {"name": str(header), "value": str(reply.rawHeader(header))}
            headers.append(header)

        data = {
            "stage": "end",
            "id": self.m_ids[reply],
            "url": reply.url().toString(),
            "status": reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
            "statusText": reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute),
            "contentType": reply.header(QNetworkRequest.ContentTypeHeader),
            "redirectURL": reply.header(QNetworkRequest.LocationHeader),
            "headers": headers,
            "time": QDateTime.currentDateTime(),
        }

        del self.m_ids[reply]
        if reply in self.m_started:
            del self.m_started[self.m_started.index(reply)]

        do_action("NetworkAccessManagerHandleFinished", Bunch(locals()))

        self.resourceReceived.emit(data)
Пример #25
0
    def start_logging (self):
        if self._logger is not None:
            return
        self._logger = logging.getLogger('Logger1')
        self._logger.setLevel(logging.DEBUG)
        log_full_path_file_name = '%s/log.log' % os.path.dirname(os.path.realpath(__file__))

        log_file_info = QFileInfo(log_full_path_file_name)
        if log_file_info.exists():
            log_created_qdatetime = log_file_info.created()
            current_qdatetime = QDateTime.currentDateTime()
            max_difference_secs = 60 * 60 * 24 * 7 # 7 giorni
            current_difference_secs = log_created_qdatetime.secsTo(current_qdatetime)
            if current_difference_secs > max_difference_secs:
                QFile.remove(log_full_path_file_name)

        self._log_handler = LogHandler(log_full_path_file_name)
        formatter = logging.Formatter('%(asctime)s - %(thread)d - %(name)s - %(levelname)s - %(message)s')
        self._log_handler.setFormatter(formatter)
        self._logger.addHandler(self._log_handler)

        # Do not raise logging system exceptions
        logging.raiseExceptions = False

        # Connect log signal
        self._log_handler.logged.connect (self.message_logged)

        self.logging_enabled = True
Пример #26
0
    def handleStarted(self):
        reply = self.sender()
        if not reply:
            return
        if reply in self.m_started:
            return

        self.m_started.append(reply)

        headers = []
        for header in reply.rawHeaderList():
            header = {
                'name': str(header),
                'value': str(reply.rawHeader(header))
            }
            headers.append(header)

        data = {
            'stage': 'start',
            'id': self.m_ids[reply],
            'url': str(reply.url()),
            'status': reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
            'statusText': reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute),
            'contentType': reply.header(QNetworkRequest.ContentTypeHeader),
            'bodySize': reply.size(),
            'redirectURL': reply.header(QNetworkRequest.LocationHeader),
            'headers': headers,
            'time': QDateTime.currentDateTime()
        }

        do_action('NetworkAccessManagerHandleStarted')

        self.resourceReceived.emit(data)
Пример #27
0
def certificate_postprocess(plot, plots):
    """
    Updates the certificate details and removes the layers after generation
    of the certificate.
    """
    cert_number = pg_certificate_number()
    user_name = stdm.data.app_dbconn.User.UserName
    curr_datetime = QDateTime.currentDateTime().toPyDateTime()
    curr_profile = current_profile()
    if not current_profile:
        return

    cert_entity = curr_profile.entity('Certificate')
    if not cert_entity:
        return
    cert_model = entity_model(cert_entity)
    cert_obj = cert_model()
    cert_obj.plot_id = plot.id
    cert_obj.scheme_id = plot.scheme_id
    cert_obj.certificate_number = cert_number
    cert_obj.production_date = curr_datetime
    cert_obj.prod_user = user_name
    cert_obj.save()

    # Remove certificate plot layer
    layers = QgsMapLayerRegistry.instance().mapLayersByName(CERTIFICATE_PLOT)
    if len(layers) > 0:
        QgsMapLayerRegistry.instance().removeMapLayer(layers[0])
Пример #28
0
    def accept(self):
        '''Accept the changes'''
        self.setStatusMsg(u'添加/修改无变化,已自动撤销', 3000)
        if not self.hasUpdates:
            return True

        model = self.listData.model()
        if self.mode == 'add':
            model.insertRow(model.rowCount(None))
            row = model.rowCount(None) - 1
            self.setStatusMsg(u'添加新交易已经成功,目前总共 %d 条记录'%(row + 1))
        else:
            self.ui.editTime.setDateTime(QDateTime.currentDateTime())
            row = self.listData.selectedIndexes()[0].row()
            self.setStatusMsg(u'修改记录已经成功', 3000)

        getEditText = lambda name: getattr(self.ui, name).toPlainText()
        getColTag = lambda tagName : model.getColTagByName(tagName)
        itemData = {
            getColTag('ID')       : getEditText('editID'),
            getColTag('Name')     : getEditText('editName'),
            getColTag('Type')     : getEditText('editType'),
            getColTag('Price')    : getEditText('editPrice'),
            getColTag('Time')     : self.ui.editTime.dateTime().toString("yyyy-MM-dd HH : mm : ss"),
            getColTag('Comments') : getEditText('editComments'),
            getColTag('Pic')      : getEditText('editPic'),
            getColTag('Category') : self.ui.comboCategory.currentText(), 
            }
        model.updateWholeRow(row, itemData)
        self.postAction()
        return True
Пример #29
0
 def _prepForAdd(self):
     model = self.listData.model()
     #Load id
     self.ui.editID.setText(str(model.getNewUnusedId()))
     self.ui.comboCategory.setCurrentIndex(0)
     #Set current time
     self.ui.editTime.setDateTime(QDateTime.currentDateTime())
Пример #30
0
	def __init__( self ):
		QDialog.__init__( self )

		self.ui = Ui_Dialog()
		self.ui.setupUi( self )

		self.cb = self.ui.exerciseComboBox
		self.sb = self.ui.weightSpinBox
		self.table = self.ui.exerciseTable
		self.splitbox = self.ui.splitplanComboBox

		self.ui.cancelButton.clicked.connect( self.reject )
		self.ui.okButton.clicked.connect( self.commit )
		self.ui.addButton.clicked.connect( self.addExerciseItem )
		self.ui.deleteButton.clicked.connect( self.deleteItem )
		self.splitbox.currentIndexChanged.connect( self.fillSplitTable )
		self.ui.updateButton.clicked.connect( self.fillSplitTable )

		self.ui.dateTimeEdit.setDateTime( QDateTime.currentDateTime() )

		self.weightPlot = QImage( "data/weight_plot.png" )
		self.ui.imageLabel = QLabel()
		self.ui.imageLabel.setPixmap( QPixmap.fromImage( self.weightPlot ) )
		self.ui.scrollArea.setWidget( self.ui.imageLabel )

		self.con = sqlite3.connect( "data/db" )
		self.con.row_factory = sqlite3.Row
		self.con.isolation_level = None
		self.cur = self.con.cursor()

		self.dbExercises()
		self.dbSplit()

		layout = QVBoxLayout(self)
		layout.addWidget(self.ui.tabWidget)
Пример #31
0
    def __init__(self):
        super(KardexModel, self).__init__()
        self.observations = ""
        """
        @ivar:Las observaciones del documento
        @type:string
        """

        self.lines = []
        """
        @ivar:Las lineas en esta devolucion
        @type: LineaKardex[]
        """
        self.printedDocumentNumber = ""
        """
        @ivar:El numero de este kardex
        @type:string
        """

        self.parentId = 0
        """
        @ivar: El  id del documento para el cual se realiza este kardex
        @type:int
        """
        self.parentPrinted = ""
        """
        @ivar: El numero impreso del padre
        @type: string 
        """

        self.datetime = QDateTime.currentDateTime()
        """
        @ivar:La hora y fecha del documento
        @type:string
        """

        self.uid = 0
        """
        @ivar: El id del usuario que realiza este kardex
        @type: int
        """

        self.warehouseId = 0
        """
        @ivar: El id de la bodega
        @type: int
        """
        self.warehouseName = ""
        """
        @ivar: El nombre de la bodega
        @type: string
        """

        self.exchangeRate = Decimal(0)
        """
        @ivar: El tipo de cambio
        @type: Decimal
        """
        self.exchangeRateId = 0
        """
Пример #32
0
	def refresh(self):
		self.RefreshTime = QDateTime.currentDateTime()
		self.updateRecords(self.getServiceList())
		self.HostServiceIndex.setCacheEnabled( False )
		for idx in ModelIter.collect(self):
			self.updateRecords(Service(self.getRecord(idx)).hostServices(),idx)
		self.HostServiceIndex.setCacheEnabled( True )
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)

        self.resize(290, 136)
        self.setWindowTitle("Effective Date")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox = GroupBox(self)
        verticalLayoutDlg.addWidget(self.groupBox)

        self.dtpDate = QDateTimeEdit(self.groupBox)
        self.dtpDate.setObjectName(("dtpDate"))
        self.dtpDate.setDateTime(QDateTime.currentDateTime())
        self.groupBox.Add = self.dtpDate

        self.calendar = QCalendarWidget(self.groupBox)
        self.groupBox.Add = self.calendar
        self.calendar.clicked.connect(self.calendar_clicked)

        self.btnBoxOkCancel = QDialogButtonBox(self)
        self.btnBoxOkCancel.setObjectName(("btnBoxOkCancel"))
        self.btnBoxOkCancel.setStandardButtons(QDialogButtonBox.Cancel
                                               | QDialogButtonBox.Ok)
        # btnOK = self.btnBoxOkCancel.button(QDialogButtonBox.Ok)
        # btnOK.setText("Create")
        self.connect(self.btnBoxOkCancel, SIGNAL("accepted()"), self.acceptDlg)
        self.connect(self.btnBoxOkCancel, SIGNAL("rejected()"), self.reject)

        verticalLayoutDlg.addWidget(self.btnBoxOkCancel)
Пример #34
0
	def __init__(self):
		self.signalFile = None
		self.eventFile = None
		filename = 'data/' + \
				QDateTime.currentDateTime().\
				toString('yyyy_MM_dd_hh_mm')
		self._fileName = str(filename)
Пример #35
0
    def __init__( self ):
        super( DocumentBase, self ).__init__()



        self.printedDocumentNumber = ""
        """
        @ivar:El numero de documento impreso del documento
        @type:string
        """

        self.datetime = QDateTime.currentDateTime()
        u"""
        @ivar:La fecha de la liquidación
        @type:QDateTime
        """



        self.observations = ""
        """
        @ivar:Las observaciones de este documento
        @type:string
        """

        self._valid_error = ""
        """
Пример #36
0
def from_datetime(datetime):

    if datetime is not None:
        return QDateTime(datetime.year, datetime.month, datetime.day,
                         datetime.hour, datetime.minute)
    else:
        return QDateTime.currentDateTime()
Пример #37
0
    def initProjects(self, projects=[], defaultProject=1):
        """
        Initialize projects
        """
        # init date and time
        self.schedAtDateTimeEdit.setDateTime(QDateTime.currentDateTime()) 

        self.projectReady = False

        self.repoTests.clear()
        self.prjCombo.clear()
        self.testsList.clear()

        self.prjCombo.setEnabled(True)
        
        # insert data
        pname = ''
        for p in projects:
            self.prjCombo.addItem ( p['name']  )
            if defaultProject == p['project_id']:
                pname = p['name']
        
        for i in xrange(self.prjCombo.count()):
            item_text = self.prjCombo.itemText(i)
            if str(pname) == str(item_text):
                self.prjCombo.setCurrentIndex(i)

        self.projectReady = True
        self.RefreshRepository.emit(pname)
	def makeTiff(self):
		global lastFrame
		print('Collecting Data Frames...')
		for i in range(1,lastFrame):
			    #print('Frame to Tiff: ' + str(i))
			    data = self.f_read[('image'+str(i))][:]
			    if i == 1:
				dataCollection = data
			    else:
				dataCollection = np.dstack((dataCollection,data))
			    i += 1
			    if i == lastFrame/2:
				print('Half Way Through File...')
		print('Completed Save')
		filename = ("Lepton TIFF Vid " + QDateTime.currentDateTime().toString())
		filename2 = filename.replace(" ", "_")
		filename3 = str(filename2.replace(":", "-"))
		print('File Name: ' + filename3)
		imsave((filename3 + '.tiff'), dataCollection)
		print('File Saved to .py or .exe directory')
		msgBox = QMessageBox()
		reply = msgBox.question(self, 'Message', (filename3 + " save to .py or .exe directory"), QMessageBox.Ok)
		print('Message Box Displayed')
		if reply == QMessageBox.Ok:
			print('Ok Clicked')
		else:
			event.ignore()
    def handleFinished(self, reply):
        headers = []
        for header in reply.rawHeaderList():
            header = {
                'name': str(header),
                'value': str(reply.rawHeader(header))
            }
            headers.append(header)

        data = {
            'stage': 'end',
            'id': self.m_ids[reply],
            'url': reply.url().toString(),
            'status': reply.attribute(QNetworkRequest.HttpStatusCodeAttribute),
            'statusText': reply.attribute(QNetworkRequest.HttpReasonPhraseAttribute),
            'contentType': reply.header(QNetworkRequest.ContentTypeHeader),
            'redirectURL': reply.header(QNetworkRequest.LocationHeader),
            'headers': headers,
            'time': QDateTime.currentDateTime()
        }

        del self.m_ids[reply]
        if reply in self.m_started:
            del self.m_started[self.m_started.index(reply)]

        do_action('NetworkAccessManagerHandleFinished')

        self.resourceReceived.emit(data)
Пример #40
0
    def postionupdated(self, position, info):
        if not self.logging or not self.layer or not self.layerprovider:
            return

        feature = QgsFeature()
        feature.setFields(self.fields)

        for field in self.fields:
            name = field.name()
            if name == 'time':
                value = self.gps.gpsinfo('utcDateTime').toString(Qt.ISODate)
            elif name == 'localtime':
                value = QDateTime.currentDateTime().toString(Qt.ISODate)
            elif name == 'user':
                value = getpass.getuser()
            else:
                try:
                    value = self.gps.gpsinfo(name)
                except AttributeError:
                    continue

            feature[name] = value

        geom = QgsGeometry.fromPoint(position)
        feature.setGeometry(geom)
        self.featurecache.append(feature)
        if len(self.featurecache) > 5:
            self.layerprovider.addFeatures(self.featurecache)
            self.featurecache = []
Пример #41
0
    def MTDanalyse(self):
        def plot1():
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "信号MTD分析-数据结果生成完毕")

            MTD_out = model.run1DB.get('MTDout')

            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "信号MTD分析-显示分析结果")

            fig = plt.figure()
            ax = fig.add_subplot(111, projection='3d')
            x = range(MTD_out.shape[0])
            y = range(MTD_out.shape[1])
            X, Y = np.meshgrid(x, y)
            surf = ax.plot_surface(X, Y, np.abs(MTD_out.T), cmap=cm.coolwarm)
            fig.colorbar(surf, shrink=0.5, aspect=10)
            plt.xlabel("距离维")
            plt.ylabel("多普勒维")
            plt.title("MTI结果图")
            plt.show()

        with self.lock:
            self.parent().textBrowser.append(
                QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "信号MTD分析-开始")
            self.newthread = PlotThread(Process.MTD, plot1)
            self.newthread.start()
Пример #42
0
 def saveLogFile(self):
     self.textBrowser.append(
         QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次日志结果")
     SaveFileName = QFileDialog.getSaveFileName(self, "保存本次日志结果!",
                                                ".", "Text Files (*.txt)")
     if SaveFileName:
         file = open(SaveFileName, 'w')
         text = self.textBrowser.toPlainText()
         file.write(text)
         file.close()
         self.textBrowser.append(
             QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次日志结果---成功")
     else:
         QMessageBox.warning(self, "注意!", "未指定文件名")
         self.textBrowser.append(
             QDateTime.currentDateTime().toString("yyyy.MM.dd hh:mm:ss:zzz ") + "保存本次参数设定---失败(未指定文件名)")
Пример #43
0
    def createRequest(self, op, req, outgoingData):
        do_action('NetworkAccessManagerCreateRequestPre')

        reply = QNetworkAccessManager.createRequest(self, op, req,
                                                    outgoingData)

        if self.m_ignoreSslErrors:
            reply.ignoreSslErrors()

        headers = []
        for header in req.rawHeaderList():
            header = {'name': str(header), 'value': str(req.rawHeader(header))}
            headers.append(header)

        self.m_idCounter += 1
        self.m_ids[reply] = self.m_idCounter

        data = {
            'id': self.m_idCounter,
            'url': req.url().toString(),
            'method': toString(op),
            'headers': headers,
            'time': QDateTime.currentDateTime()
        }

        reply.readyRead.connect(self.handleStarted)

        do_action('NetworkAccessManagerCreateRequestPost')

        self.resourceRequested.emit(data)
        return reply
 def _startImportSession(self):
     self.importid = str(uuid.uuid1())
     self.import_date = QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss')
     self.imported_layers = set()
     self.imported_extent=None
     self.features_errors=[]
     self.commit_errors=[]
Пример #45
0
    def run(self):

                
        date = QDateTime.currentDateTime()
        self.count_error = 0
        self.count_success = 0
        self.on_append_report.emit( QString( u"Запуск тестов " ).append( date.toString( "hh:mm:ss dd.MM.yyyy" ) ) )
        self.on_append_report.emit( QString( u"Колличество тестов: %1" ).arg( len( self.tests ) ) )
        self.on_append_report.emit( QString( u"Серийный номер ВИМ-3U-3: " ).append( self.nom ) )
        i = 0
        for test in self.tests :
            date = QDateTime.currentDateTime()
            self.on_append_report.emit( QString(u"%1 Тест %2: %3 - %4" ).arg( date.toString( "hh:mm:ss.zzz" ) ).arg( i ).arg( QString( self.test.name(test) ) ).arg( QString( self.get_result_string( 0 ) ) ) )
            self.current_test = test

            self.test.nom = self.nom
            self.test.mac1 = self.mac1
            self.test.mac2 = self.mac2
            self.test.mac3 = self.mac3




            
            res = self.test.run(test, self.on_append_report)
            self.current_test = -1
            date = QDateTime.currentDateTime()
            if (res==1):
                self.count_success+=1
            else:
                self.count_error+=1
                
            self.on_append_report.emit( QString(u"%1 Тест %2: %3 - %4" ).arg( date.toString( "hh:mm:ss.zzz" ) ).arg( i ).arg( QString( self.test.name(test) ) ).arg( QString( self.get_result_string( res ) ) ) )
            self.on_append_report.emit( QString(u"<hr/>") )
            i += 1
            self.on_update_process.emit( (i * 100) / len( self.tests ) )
            if (res == -2):
                break

        date = QDateTime.currentDateTime()
        self.on_append_report.emit( QString( u"Завершение тестов " ).append( date.toString( "hh:mm:ss dd.MM.yyyy" ) ) )
        self.on_append_report.emit( QString( u"успешно : %1 " ).arg( self.count_success ) )
        self.on_append_report.emit( QString( u"с ошибками : %1 " ).arg( self.count_error ) )
        self.on_append_report.emit( QString( u"не проведено : %1 " ).arg( len( self.tests ) - (self.count_success + self.count_error) ) )
        if self.count_error == 0:
            self.no_error.emit()
        self.on_end_tests.emit()
Пример #46
0
 def setToNow(self):
     spec = self._edit.timeSpec()
     t = QDateTime.currentDateTime()
     if t > self.maximumDateTime():
         t = self.maximumDateTime()
     elif t < self.minimumDateTime():
         t = self.minimumDateTime()
     self.setDateTime(t.toTimeSpec(spec))
 def _startImportSession(self):
     self.importid = str(uuid.uuid1())
     self.import_date = QDateTime.currentDateTime().toString(
         'yyyy-MM-dd hh:mm:ss')
     self.imported_layers = set()
     self.imported_extent = None
     self.features_errors = []
     self.commit_errors = []
Пример #48
0
 def __init__(self, childName=None):
     self.childName = childName
     self.children = []
     self.title = None
     self.reportTitle = None
     self.stamp = QDateTime.currentDateTime()
     self.colorCode = None
     self.Type = None
Пример #49
0
 def refresh(self):
     self.RefreshTime = QDateTime.currentDateTime()
     self.updateRecords(self.getServiceList())
     self.HostServiceIndex.setCacheEnabled(False)
     for idx in ModelIter.collect(self):
         self.updateRecords(
             Service(self.getRecord(idx)).hostServices(), idx)
     self.HostServiceIndex.setCacheEnabled(True)
Пример #50
0
    def method_16(self, binaryWriter_0, qafileVersion_0):
        num = 0
        numArray = []
        tempFileName = define.appPath + "/tempFile.txt"
        binaryWriter = file(tempFileName, "w")
        # using (TempFileStream tempFileStream = new TempFileStream())
        # {
        #     using (BinaryWriter binaryWriter = new BinaryWriter(tempFileStream))
        #     {
        num1 = self.method_0()
        if (qafileVersion_0 == QAFileVersion.V8_1
                or qafileVersion_0 == QAFileVersion.V10):
            binaryWriter.write(str(num1))
        count = len(self.sessions) - 1
        self.sessions[count].DwgSizeClosed = FileHelper.smethod_3(
            self.fileNameDWG)
        self.sessions[count].Closed = QDateTime.currentDateTime()
        for session in self.sessions:
            session.method_15(binaryWriter, qafileVersion_0)
        #TODO: UnCompleted
        # using (TempFileStream tempFileStream1 = new TempFileStream())
        # {
        #     using (Stream zlibStream = new ZlibStream(tempFileStream1, CompressionMode.Compress, CompressionLevel.BestCompression, true))
        #     {
        #         tempFileStream.Seek((long)0, SeekOrigin.Begin);
        #         num = -1;
        #         numArray = new byte[4096];
        #         while (true)
        #         {
        #             int num2 = tempFileStream.Read(numArray, 0, 4096);
        #             num = num2;
        #             if (num2 <= 0)
        #             {
        #                 break;
        #             }
        #             zlibStream.Write(numArray, 0, num);
        #         }
        #     }
        #     binaryWriter_0.Write(tempFileStream1.Length);
        #     tempFileStream1.Seek((long)0, SeekOrigin.Begin);
        #     num = -1;
        #     numArray = new byte[4096];
        #     while (true)
        #     {
        #         int num3 = tempFileStream1.Read(numArray, 0, 4096);
        #         num = num3;
        #         if (num3 <= 0)
        #         {
        #             break;
        #         }
        #         binaryWriter_0.Write(numArray, 0, num);

        try:
            binaryWriter_0.write(len(self.reportEntries))
            for reportEntry in self.reportEntries:
                reportEntry.method_1(binaryWriter_0, qafileVersion_0)
        except:
            pass
Пример #51
0
    def _replyFinished(self):
        reply = self.sender()
        url = reply.request().url().toString()
        if url not in self.fetchedFiles:
            self.fetchedFiles[url] = None

        if url in self.requestingReplies:
            del self.requestingReplies[url]

        httpStatusCode = reply.attribute(
            QNetworkRequest.HttpStatusCodeAttribute)
        if reply.error() == QNetworkReply.NoError:
            self._successes += 1

            if reply.attribute(QNetworkRequest.SourceIsFromCacheAttribute):
                self._cacheHits += 1

            elif not reply.hasRawHeader("Cache-Control"):
                cache = QgsNetworkAccessManager.instance().cache()
                if cache:
                    metadata = cache.metaData(reply.request().url())
                    if metadata.expirationDate().isNull():
                        metadata.setExpirationDate(
                            QDateTime.currentDateTime().addSecs(
                                self.defaultCacheExpiration * 3600))
                        cache.updateMetaData(metadata)
                        self.log(
                            "Default expiration date has been set: %s (%d h)" %
                            (url, self.defaultCacheExpiration))

            if reply.isReadable():
                data = reply.readAll()
                self.fetchedFiles[url] = data
            else:
                qDebug("http status code: " + str(httpStatusCode))

        else:
            self._errors += 1
            if self.errorStatus == self.NO_ERROR:
                self.errorStatus = self.UNKNOWN_ERROR

        self.replyFinished.emit(url)
        reply.deleteLater()

        if len(self.queue) + len(self.requestingReplies) == 0:
            # all replies have been received
            if self.sync:
                self.logT("eventLoop.quit()")
                self.eventLoop.quit()
            else:
                self.timer.stop()

            self.allRepliesFinished.emit()

        elif len(self.queue) > 0:
            # start fetching the next file
            self.fetchNext()
Пример #52
0
    def _photoDate(self, path):
        with open(path, 'rb') as imgFile:
            tags = exifread.process_file(imgFile, details=False)

        if 'EXIF GPS GPSDate' in tags:
            return QDateTime.fromString(tags['EXIF GPS GPSDate'].values,
                                        'yyyy:MM:dd')
        else:
            return QDateTime.currentDateTime()
Пример #53
0
 def updatePhoto(self, db, photo_id, photo):
     table = self.DBConfig['table']
     sql = """UPDATE '{0}' SET photo = '{2}',
                               timestamp = '{4}'
                               WHERE photo_id = '{3}'
                               AND linkid = '{1}'""".format(
         table, self.linkid, photo, photo_id,
         QDateTime.currentDateTime().toLocalTime().toString())
     db.execute(sql)
Пример #54
0
    def __init__(self, iface, layerId=None, featureId=None):
        QDialog.__init__(self)
        self.setupUi(self)
        self.settings = MySettings()
        SettingDialog.__init__(self, self.settings, False, True)  # column chooser, advanced search options

        #init variables
        self.layerId = layerId
        self.featureId = featureId
        self.layer = None
        self.rubber = QgsRubberBand(iface.mapCanvas())
        self.mapCanvas = iface.mapCanvas()
        self.resuts = dict()

        # connect "pan and show geometry" check box to draw in rubber band
        self.panShowGeometry.clicked.connect(self.displayGeomDifference)

        # reject properly showEvent if checking fails
        self.rejectShowEvent.connect(self.reject, Qt.QueuedConnection)
        # start search directly at the end of showEvent if enough params
        self.performSearchAtShowEvent.connect(self.on_searchButton_clicked, Qt.QueuedConnection)

        # setup layer - field combo, with primary key selector as field
        self.layerComboManager = VectorLayerCombo(self.layerCombo, layerId,
                                                  {"dataProvider": "postgres", "finishInit": False,
                                                   "skipLayers": [lambda: self.settings.value("logLayer")]})
        self.layerComboManager.finishInit()

        # log layer
        self.logLayer = LogLayer()
        self.logLayer.setProgressMax.connect(self.progressBar.setMaximum)
        self.logLayer.setProgressMin.connect(self.progressBar.setMinimum)
        self.logLayer.setProgressValue.connect(self.progressBar.setValue)

        # logged actions table
        self.loggedActionsLayout = QGridLayout(self.loggedActionsWidget)
        self.loggedActionsTable = LoggedActionsTable(self.loggedActionsWidget)
        self.loggedActionsLayout.addWidget(self.loggedActionsTable, 0, 0, 1, 1)
        self.loggedActionsTable.itemSelectionChanged.connect(self.displayDifference)

        # difference viewer
        self.differenceLayout = QGridLayout(self.differenceViewerWidget)
        self.differenceViewer = DifferenceViewer(self.differenceViewerWidget)
        self.differenceLayout.addWidget(self.differenceViewer, 0, 0, 1, 1)

        # set dates
        now = QDateTime.currentDateTime()
        self.searchBeforeDate.setDateTime(now)
        self.searchAfterDate.setDateTime(now.addDays(-7))

        # finish ui
        self.buttonDisplayMode(False)
        self.restoreButton.setEnabled(False)
        if featureId is not None:
            self.featureEdit.setText("%s" % featureId)
        self.adjustSize()
Пример #55
0
 def terminate( self ):
     if ( self.current_test != -1 ):
         self.test.stop( self.current_test )
         self.current_test = -1
     date = QDateTime.currentDateTime()
     self.on_append_report.emit( QString( u"Отмена " ).append( date.toString( "hh:mm:ss dd.MM.yyyy " ) ) )
     self.on_append_report.emit( QString( u"успешно : %1 " ).arg( self.count_success ) )
     self.on_append_report.emit( QString( u"с ошибками : %1 " ).arg( self.count_error ) )
     self.on_append_report.emit( QString( u"не проведено : %1 " ).arg( len( self.tests ) - (self.count_success + self.count_error) ) )
     super(TestThread, self).terminate()
Пример #56
0
    def run(self):
        date = QDateTime.currentDateTime()
        #self.on_ipmi_report.emit( QString( str(self.quick )) ) 
        res=0
        self.on_ipmi_report.emit( QString( u"Полная проверка EEPROM 10 минут." ).append( date.toString( "hh:mm:ss dd.MM.yyyy" ) ) )
        if (self.quick==0):
            res = self.test.run(self.on_ipmi_report)
        
        if (self.quick==1):
            res=1
        if (res==1):
            self.on_ipmi_report.emit( QString( u"Полная проверка EEPROM выполнена." ) )       
            date = QDateTime.currentDateTime()
            self.on_ipmi_report.emit( QString( u"Запись IPMI " ).append( date.toString( "hh:mm:ss dd.MM.yyyy" ) ) )
            res = self.write.run(self.on_ipmi_report)   
            if (res==1):
                self.on_ipmi_report.emit( QString( u"Запись IPMI выполнена." ) ) 

        self.on_end_write_ipmi.emit()
Пример #57
0
 def __init__(self):
     super().__init__()
     self.ui = interface_main_afc.Ui_MainWindow()
     self.ui.setupUi(self)
     self.ui.INICIAR_TESTE_BUTTON.clicked.connect(self.Start_Simulation)
     self.ui.CLOSE_BUTTON.clicked.connect(self.Stop_Simulation)
     self.SEGUNDA_JANELA = SEGUNDA_JANELA(self)
     self.TERCEIRA_JANELA = TERCEIRA_JANELA(self)
     start_time_general = QDateTime.currentDateTime()
     self.ui.dateTimeEdit.setDateTime(start_time_general)
Пример #58
0
 def __setitem__(self, url, data):
     assert isinstance(url, QUrl)
     assert isinstance(data, QByteArray)
     meta = QNetworkCacheMetaData()
     meta.setUrl(url)
     meta.setSaveToDisk(True)
     meta.setExpirationDate(QDateTime.currentDateTime().addDays(7))
     iodevice = self.prepare(meta)
     iodevice.write(data)
     self.insert(iodevice)
Пример #59
0
    def log_message(self, message_type, message):

        # TODO: set alignment
        row = self.tableWidget.rowCount()
        self.tableWidget.insertRow(row)
        self.tableWidget.setItem(
            row, 0,
            QTableWidgetItem(QDateTime.currentDateTime().toString(
                'yyyy.MM.dd hh:mm:ss.zzz')))
        self.tableWidget.setItem(row, 1, QTableWidgetItem(message_type))
        self.tableWidget.setItem(row, 2, QTableWidgetItem(message))
        self.tableWidget.resizeRowToContents(row)
Пример #60
0
    def process(self, msgType, msg):
        now = QDateTime.currentDateTime().toString(Qt.ISODate)

        if msgType == QtDebugMsg:
            if self.verbose:
                print '%s [DEBUG] %s' % (now, msg)
        elif msgType == QtWarningMsg:
            print >> sys.stderr, '%s [WARNING] %s' % (now, msg)
        elif msgType == QtCriticalMsg:
            print >> sys.stderr, '%s [CRITICAL] %s' % (now, msg)
        elif msgType == QtFatalMsg:
            print >> sys.stderr, '%s [FATAL] %s' % (now, msg)