コード例 #1
0
ファイル: XbelReader.py プロジェクト: testmana2/eric
    def __readBookmarkNode(self, node):
        """
        Private method to read and parse a bookmark subtree.
        
        @param node reference to the node to attach to (BookmarkNode)
        """
        if not self.isStartElement() and self.name() != "bookmark":
            return

        bookmark = BookmarkNode(BookmarkNode.Bookmark, node)
        bookmark.url = self.attributes().value("href")
        bookmark.added = QDateTime.fromString(self.attributes().value("added"), Qt.ISODate)
        bookmark.modified = QDateTime.fromString(self.attributes().value("modified"), Qt.ISODate)
        bookmark.visited = QDateTime.fromString(self.attributes().value("visited"), Qt.ISODate)

        while not self.atEnd():
            self.readNext()
            if self.isEndElement():
                break

            if self.isStartElement():
                if self.name() == "title":
                    self.__readTitle(bookmark)
                elif self.name() == "desc":
                    self.__readDescription(bookmark)
                elif self.name() == "info":
                    self.__readInfo()
                else:
                    self.__skipUnknownElement()

        if not bookmark.title:
            bookmark.title = QCoreApplication.translate("XbelReader", "Unknown title")
コード例 #2
0
ファイル: AdBlockSubscription.py プロジェクト: Darriall/eric
 def __parseUrl(self, url):
     """
     Private method to parse the AdBlock URL for the subscription.
     
     @param url AdBlock URL for the subscription (QUrl)
     """
     if url.scheme() != "abp":
         return
     
     if url.path() != "subscribe":
         return
     
     if qVersion() >= "5.0.0":
         from PyQt5.QtCore import QUrlQuery
         urlQuery = QUrlQuery(url)
         self.__title = urlQuery.queryItemValue("title")
         self.__enabled = urlQuery.queryItemValue("enabled") != "false"
         self.__location = QByteArray(urlQuery.queryItemValue("location"))
         
         # Check for required subscription
         self.__requiresLocation = urlQuery.queryItemValue(
             "requiresLocation")
         self.__requiresTitle = urlQuery.queryItemValue("requiresTitle")
         if self.__requiresLocation and self.__requiresTitle:
             import Helpviewer.HelpWindow
             Helpviewer.HelpWindow.HelpWindow.adBlockManager()\
                 .loadRequiredSubscription(self.__requiresLocation,
                                           self.__requiresTitle)
         
         lastUpdateString = urlQuery.queryItemValue("lastUpdate")
         self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                                  Qt.ISODate)
     else:
         self.__title = \
             QUrl.fromPercentEncoding(url.encodedQueryItemValue("title"))
         self.__enabled = QUrl.fromPercentEncoding(
             url.encodedQueryItemValue("enabled")) != "false"
         self.__location = QByteArray(QUrl.fromPercentEncoding(
             url.encodedQueryItemValue("location")))
         
         # Check for required subscription
         self.__requiresLocation = QUrl.fromPercentEncoding(
             url.encodedQueryItemValue("requiresLocation"))
         self.__requiresTitle = QUrl.fromPercentEncoding(
             url.encodedQueryItemValue("requiresTitle"))
         if self.__requiresLocation and self.__requiresTitle:
             import Helpviewer.HelpWindow
             Helpviewer.HelpWindow.HelpWindow.adBlockManager()\
                 .loadRequiredSubscription(self.__requiresLocation,
                                           self.__requiresTitle)
         
         lastUpdateByteArray = url.encodedQueryItemValue("lastUpdate")
         lastUpdateString = QUrl.fromPercentEncoding(lastUpdateByteArray)
         self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                                  Qt.ISODate)
     
     self.__loadRules()
コード例 #3
0
ファイル: XbelReader.py プロジェクト: testmana2/test
 def __readFolder(self, node):
     """
     Private method to read and parse a folder subtree.
     
     @param node reference to the node to attach to (BookmarkNode)
     """
     if not self.isStartElement() and self.name() != "folder":
         return
     
     folder = BookmarkNode(BookmarkNode.Folder, node)
     folder.expanded = self.attributes().value("folded") == "no"
     folder.added = QDateTime.fromString(
         self.attributes().value("added"), Qt.ISODate)
     
     while not self.atEnd():
         self.readNext()
         if self.isEndElement():
             break
         
         if self.isStartElement():
             if self.name() == "title":
                 self.__readTitle(folder)
             elif self.name() == "desc":
                 self.__readDescription(folder)
             elif self.name() == "folder":
                 self.__readFolder(folder)
             elif self.name() == "bookmark":
                 self.__readBookmarkNode(folder)
             elif self.name() == "separator":
                 self.__readSeparator(folder)
             elif self.name() == "info":
                 self.__readInfo()
             else:
                 self.__skipUnknownElement()
コード例 #4
0
ファイル: HelpDocsInstaller.py プロジェクト: pycom/EricShort
 def __installEric6Doc(self, engine):
     """
     Private method to install/update the eric6 help documentation.
     
     @param engine reference to the help engine (QHelpEngineCore)
     @return flag indicating success (boolean)
     """
     versionKey = "eric6_ide"
     info = engine.customValue(versionKey, "")
     lst = info.split('|')
     
     dt = QDateTime()
     if len(lst) and lst[0]:
         dt = QDateTime.fromString(lst[0], Qt.ISODate)
     
     qchFile = ""
     if len(lst) == 2:
         qchFile = lst[1]
     
     docsPath = QDir(getConfig("ericDocDir") + QDir.separator() + "Help")
     
     files = docsPath.entryList(["*.qch"])
     if not files:
         engine.setCustomValue(
             versionKey, QDateTime().toString(Qt.ISODate) + '|')
         return False
     
     for f in files:
         if f == "source.qch":
             fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
             if dt.isValid() and \
                fi.lastModified().toString(Qt.ISODate) == \
                 dt.toString(Qt.ISODate) and \
                qchFile == fi.absoluteFilePath():
                 return False
             
             namespace = QHelpEngineCore.namespaceName(
                 fi.absoluteFilePath())
             if not namespace:
                 continue
             
             if namespace in engine.registeredDocumentations():
                 engine.unregisterDocumentation(namespace)
             
             if not engine.registerDocumentation(fi.absoluteFilePath()):
                 self.errorMessage.emit(
                     self.tr(
                         """<p>The file <b>{0}</b> could not be"""
                         """ registered. <br/>Reason: {1}</p>""")
                     .format(fi.absoluteFilePath, engine.error())
                 )
                 return False
             
             engine.setCustomValue(
                 versionKey,
                 fi.lastModified().toString(Qt.ISODate) + '|' +
                 fi.absoluteFilePath())
             return True
     
     return False
コード例 #5
0
ファイル: SvnDiffDialog.py プロジェクト: paulmadore/Eric-IDE
 def __getVersionArg(self, version):
     """
     Private method to get a pysvn revision object for the given version
     number.
     
     @param version revision (integer or string)
     @return revision object (pysvn.Revision)
     """
     if isinstance(version, int):
         return pysvn.Revision(pysvn.opt_revision_kind.number, version)
     elif version.startswith("{"):
         dateStr = version[1:-1]
         secs = QDateTime.fromString(dateStr, Qt.ISODate).toTime_t()
         return pysvn.Revision(pysvn.opt_revision_kind.date, secs)
     elif version == "HEAD":
         return pysvn.Revision(pysvn.opt_revision_kind.head)
     elif version == "COMMITTED":
         return pysvn.Revision(pysvn.opt_revision_kind.committed)
     elif version == "BASE":
         return pysvn.Revision(pysvn.opt_revision_kind.base)
     elif version == "WORKING":
         return pysvn.Revision(pysvn.opt_revision_kind.working)
     elif version == "PREV":
         return pysvn.Revision(pysvn.opt_revision_kind.previous)
     else:
         return pysvn.Revision(pysvn.opt_revision_kind.unspecified)
コード例 #6
0
ファイル: settingseditor.py プロジェクト: Axel-Erfurt/pyqt5
    def setModelData(self, editor, model, index):
        if not editor.isModified():
            return

        text = editor.text()
        validator = editor.validator()
        if validator is not None:
            state, text, _ = validator.validate(text, 0)
            if state != QValidator.Acceptable:
                return

        originalValue = index.model().data(index, Qt.UserRole)

        if isinstance(originalValue, QColor):
            self.colorExp.exactMatch(text)
            value = QColor(min(int(self.colorExp.cap(1)), 255),
                           min(int(self.colorExp.cap(2)), 255),
                           min(int(self.colorExp.cap(3)), 255),
                           min(int(self.colorExp.cap(4)), 255))
        elif isinstance(originalValue, QDate):
            value = QDate.fromString(text, Qt.ISODate)
            if not value.isValid():
                return
        elif isinstance(originalValue, QDateTime):
            value = QDateTime.fromString(text, Qt.ISODate)
            if not value.isValid():
                return
        elif isinstance(originalValue, QTime):
            value = QTime.fromString(text, Qt.ISODate)
            if not value.isValid():
                return
        elif isinstance(originalValue, QPoint):
            self.pointExp.exactMatch(text)
            value = QPoint(int(self.pointExp.cap(1)),
                           int(self.pointExp.cap(2)))
        elif isinstance(originalValue, QRect):
            self.rectExp.exactMatch(text)
            value = QRect(int(self.rectExp.cap(1)),
                          int(self.rectExp.cap(2)),
                          int(self.rectExp.cap(3)),
                          int(self.rectExp.cap(4)))
        elif isinstance(originalValue, QSize):
            self.sizeExp.exactMatch(text)
            value = QSize(int(self.sizeExp.cap(1)),
                          int(self.sizeExp.cap(2)))
        elif isinstance(originalValue, list):
            value = text.split(',')
        else:
            value = type(originalValue)(text)

        model.setData(index, self.displayText(value), Qt.DisplayRole)
        model.setData(index, value, Qt.UserRole)
コード例 #7
0
ファイル: gallery.py プロジェクト: ImoutoChan/happypanda
		def column_checker():
			if current_column == self._TITLE:
				title = current_gallery.title
				return title
			elif current_column == self._ARTIST:
				artist = current_gallery.artist
				return artist
			elif current_column == self._TAGS:
				tags = utils.tag_to_string(current_gallery.tags)
				return tags
			elif current_column == self._TYPE:
				type = current_gallery.type
				return type
			elif current_column == self._FAV:
				if current_gallery.fav == 1:
					return u'\u2605'
				else:
					return ''
			elif current_column == self._CHAPTERS:
				return len(current_gallery.chapters)
			elif current_column == self._LANGUAGE:
				return current_gallery.language
			elif current_column == self._LINK:
				return current_gallery.link
			elif current_column == self._DESCR:
				return current_gallery.info
			elif current_column == self._DATE_ADDED:
				g_dt = "{}".format(current_gallery.date_added)
				qdate_g_dt = QDateTime.fromString(g_dt, "yyyy-MM-dd HH:mm:ss")
				return qdate_g_dt
			elif current_column == self._PUB_DATE:
				g_pdt = "{}".format(current_gallery.pub_date)
				qdate_g_pdt = QDateTime.fromString(g_pdt, "yyyy-MM-dd HH:mm:ss")
				if qdate_g_pdt.isValid():
					return qdate_g_pdt
				else:
					return 'No date set'
コード例 #8
0
 def read(self):
     header = self.fits_file[0].header
     self.name=header.get('OBJECT')
     self.names=header.get('NAMES')
     self.comment=header.get('NOTES')
     self.date=QDateTime.fromString(header.get('DATE', self.__def_value('date',QDateTime.currentDateTime()).toString(Qt.ISODate)), Qt.ISODate)
     #header.get('CTYPE2') TODO: get ra/dec from type
     ra=header.get('CRVAL2', 0)
     #header.get('CTYPE3')
     dec=header.get('CRVAL3', 0)
     self.type=header.get('OBJTYPE')
     self.sptype=header.get('SPTYPE')
     self.observer=header.get('OBSERVER', self.__def_value('observer'))
     self.equipment = header.get('EQUIPMENT', self.__def_value('equipment'))
     self.position=header.get('POSITION', self.__def_value('position'))
     self.coordinates = SkyCoord(ra, dec, unit=u.deg)
コード例 #9
0
ファイル: XbelReader.py プロジェクト: testmana2/eric
    def __readSeparator(self, node):
        """
        Private method to read a separator element.
        
        @param node reference to the bookmark node the separator belongs to
            (BookmarkNode)
        """
        sep = BookmarkNode(BookmarkNode.Separator, node)
        sep.added = QDateTime.fromString(self.attributes().value("added"), Qt.ISODate)

        # empty elements have a start and end element
        while not self.atEnd():
            self.readNext()
            if self.isEndElement():
                break

            if self.isStartElement():
                if self.name() == "info":
                    self.__readInfo()
                else:
                    self.__skipUnknownElement()
コード例 #10
0
    def __readSeparator(self, node):
        """
        Private method to read a separator element.
        
        @param node reference to the bookmark node the separator belongs to
            (BookmarkNode)
        """
        sep = BookmarkNode(BookmarkNode.Separator, node)
        sep.added = QDateTime.fromString(self.attributes().value("added"),
                                         Qt.ISODate)

        # empty elements have a start and end element
        while not self.atEnd():
            self.readNext()
            if self.isEndElement():
                break

            if self.isStartElement():
                if self.name() == "info":
                    self.__readInfo()
                else:
                    self.__skipUnknownElement()
コード例 #11
0
ファイル: write_off_query.py プロジェクト: zgj0607/Py-store
 def _clear_detail(self):
     self.buy_date.setDateTime(
         QDateTime.fromString(time_utils.get_now(), 'yyyy-MM-dd hh:mm:ss'))
     self.brand.clear()
     self.model.clear()
     self.sale_number.clear()
     self.buy_number.setValue(
         abs(
             int(
                 table_utils.get_table_current_index_info(
                     self.write_off_table, 5))))
     self.unit.clear()
     self.service.clear()
     self.price.setText('0.0')
     self.total.setText('0.0')
     self.paid.setText('0.0')
     self.unpaid.setText('0.0')
     self.sale_id = 0
     self.stock_id = 0
     self.brand_id = 0
     self.model_id = 0
     self.balance = 0
コード例 #12
0
ファイル: cookies.py プロジェクト: kizzlepc/TenThousandHours
    def har_cookie2qt(cls, cookie):
        qcookie = QNetworkCookie()
        qcookie.setName(to_bytes(cookie["name"]))
        qcookie.setValue(to_bytes(cookie["value"]))

        if 'domain' in cookie:
            qcookie.setDomain(cookie["domain"])

        if 'httpOnly' in cookie:
            qcookie.setHttpOnly(cookie["httpOnly"])

        if 'secure' in cookie:
            qcookie.setSecure(cookie["secure"])

        if 'path' in cookie:
            qcookie.setPath(cookie["path"])

        if cookie.get('expires'):
            expires = QDateTime.fromString(cookie["expires"], Qt.ISODate)
            qcookie.setExpirationDate(expires)

        return qcookie
コード例 #13
0
ファイル: cookies.py プロジェクト: Cloverseer/splash
    def har_cookie2qt(cls, cookie):
        qcookie = QNetworkCookie()
        qcookie.setName(to_bytes(cookie["name"]))
        qcookie.setValue(to_bytes(cookie["value"]))

        if 'domain' in cookie:
            qcookie.setDomain(cookie["domain"])

        if 'httpOnly' in cookie:
            qcookie.setHttpOnly(cookie["httpOnly"])

        if 'secure' in cookie:
            qcookie.setSecure(cookie["secure"])

        if 'path' in cookie:
            qcookie.setPath(cookie["path"])

        if cookie.get('expires'):
            expires = QDateTime.fromString(cookie["expires"], Qt.ISODate)
            qcookie.setExpirationDate(expires)

        return qcookie
コード例 #14
0
 def update_display(self, test_case):
     self.test_caseidentify_edit.setText(test_case.case_mark)
     self.test_item_edit.setText(test_case.case_name)
     self.test_cat_combox.setCurrentIndex(test_case.case_cat)
     self.require_trace_edit.setText(test_case.case_req_track)
     self.test_content_edit.setText(test_case.case_content)
     self.sys_prepare_edit.setText(test_case.case_sys_prepare)
     self.precondation_edit.setText(test_case.case_constraint)
     self.test_input_edit.setText(test_case.case_input)
     for index, item in enumerate(test_case.case_exec_procedure):
         self.test_procedure_tabel.insertRow(index)
         self.test_procedure_tabel.setItem(index, 0,
                                           QTableWidgetItem(item[0]))
         self.test_procedure_tabel.setItem(index, 1,
                                           QTableWidgetItem(item[1]))
         self.test_procedure_tabel.setItem(index, 2,
                                           QTableWidgetItem(item[2]))
         self.test_procedure_tabel.setItem(index, 3,
                                           QTableWidgetItem(item[3]))
         self.test_procedure_tabel.setItem(index, 4,
                                           QTableWidgetItem(item[4]))
         self.test_procedure_tabel.setItem(index, 5,
                                           QTableWidgetItem(item[5]))
         self.test_procedure_tabel.setItem(index, 6,
                                           QTableWidgetItem(item[6]))
     self.estimate_rule_eidt.setText(test_case.case_qualified_rule)
     self.test_env_combox.setCurrentIndex(test_case.case_env)
     self.qualified_method_combox.setCurrentIndex(
         test_case.case_qualified_method)
     self.safe_secret_edit.setText(test_case.case_safe_secret)
     self.test_person_combox.setCurrentIndex(test_case.test_person)
     self.test_person_join_edit.setText(test_case.test_join_person)
     self.test_date_timepickedit.setDateTime(
         QDateTime.fromString(test_case.test_date, 'yyyy-MM-dd'))
     self.test_data_edit.setText(test_case.case_data)
     self.problem_sheet_edit.setText(test_case.case_problem_sheet)
     self.correct_sheet_edit.setText(test_case.case_correct_sheet)
     self.test_diff_edit.setText(test_case.case_diff)
コード例 #15
0
ファイル: main.py プロジェクト: zxm1124/jd_seckill
    def show_info(self, info):
        info = Dict(json.loads(info))
        print('info', info)
        self.yuyue_info = info
        if not self.time.isActive():
            self.count = info.countdown
            self.start_count()
        else:
            self.add_log('倒计时已经开始')

        current_buy_time = self.dateTimeEdit.dateTime().toString(
            'yyyy-MM-dd hh:mm:ss')
        if '%s:00' % info.buy_time == current_buy_time:
            self.add_log('自动核对抢购时间无误')
        else:
            status = QMessageBox.information(None, '消息提示',
                                             '当前设置时间与抢购时间不一致,知否自动更新',
                                             QMessageBox.Yes | QMessageBox.No)
            if status == QMessageBox.Yes:
                self.dateTimeEdit.setDateTime(
                    QDateTime.fromString('%s:00' % info.buy_time,
                                         'yyyy-MM-dd hh:mm:ss'))
                self.add_log('自动更新抢购时间成功')
コード例 #16
0
ファイル: attractionstab.py プロジェクト: komarEX/Shinji
    def data_changed(self, index1, index2, roles):
        assert isinstance(index1, QModelIndex)
        if index1.column() == 1:
            if not index1.data():
                QMessageBox.critical(None,
                                     "Invalid data",
                                     "Field cannot be empty.",
                                     QMessageBox.Ok)
                self.model.revertRow(index1.row())
            elif len(str(index1.data())) != len(str(index1.data()).strip()):
                QMessageBox.critical(None,
                                     "Invalid data",
                                     "Unwanted whitespace character.",
                                     QMessageBox.Ok)

        if index1.column() in (3, 4):
            datetime = QDateTime.fromString(index1.data(), "yyyy-MM-dd HH:mm:ss")
            if not datetime.isValid():
                QMessageBox.critical(None,
                                     "Invalid data",
                                     "Datetime field is invalid.",
                                     QMessageBox.Ok)
                self.model.revertRow(index1.row())
コード例 #17
0
 def __parseUrl(self, url):
     """
     Private method to parse the AdBlock URL for the subscription.
     
     @param url AdBlock URL for the subscription
     @type QUrl
     """
     if url.scheme() != "abp":
         return
     
     if url.path() != "subscribe":
         return
     
     urlQuery = QUrlQuery(url)
     self.__title = QUrl.fromPercentEncoding(
         QByteArray(urlQuery.queryItemValue("title").encode()))
     self.__enabled = urlQuery.queryItemValue("enabled") != "false"
     self.__location = QByteArray(QUrl.fromPercentEncoding(
         QByteArray(urlQuery.queryItemValue("location").encode()))
         .encode("utf-8"))
     
     # Check for required subscription
     self.__requiresLocation = QUrl.fromPercentEncoding(
         QByteArray(urlQuery.queryItemValue(
             "requiresLocation").encode()))
     self.__requiresTitle = QUrl.fromPercentEncoding(
         QByteArray(urlQuery.queryItemValue("requiresTitle").encode()))
     if self.__requiresLocation and self.__requiresTitle:
         from WebBrowser.WebBrowserWindow import WebBrowserWindow
         WebBrowserWindow.adBlockManager().loadRequiredSubscription(
             self.__requiresLocation, self.__requiresTitle)
     
     lastUpdateString = urlQuery.queryItemValue("lastUpdate")
     self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                              Qt.ISODate)
     
     self.__loadRules()
コード例 #18
0
    def loadSettings(self):
        static = scctool.settings.config.parser.getboolean(
            "Countdown", "static")
        if static:
            self.rb_static.setChecked(True)
        else:
            self.rb_dynamic.setChecked(True)
        description = scctool.settings.config.parser.get(
            'Countdown', 'description')
        self.le_desc.setText(description.strip())
        restart = scctool.settings.config.parser.getboolean(
            "Countdown", "restart")
        self.cb_restart.setChecked(restart)

        duration = QTime()
        string = scctool.settings.config.parser.get('Countdown',
                                                    'duration').strip()
        duration = QTime.fromString(string, 'HH:mm:ss')
        self.te_duration.setTime(duration)

        string = scctool.settings.config.parser.get('Countdown',
                                                    'datetime').strip()
        datetime = QDateTime.fromString(string, 'yyyy-MM-dd HH:mm')
        self.te_datetime.setDateTime(datetime)
コード例 #19
0
def load():
    '''
    读取配置项
    :return:
    '''
    try:

        with open(dataPath, 'rb') as f:
            setting = pickle.load(f)

        sets = setting['items']
        length = len(sets)
        print(setting)
        if length > 0:
            #给这些控件初始化
            ui_main.ed_url.setText(setting['url'])

            ui_main.dte_time.setDateTime(
                QDateTime.fromString(setting['dte_time'], 'hh:mm:ss'))
            ui_main.cb_sfds.setChecked(setting['cb_sfds'])
            ui_main.cb_tqsx.setChecked(setting['cb_tqsx'])
            #清空
            ui_main.tab_mban.clearContents()
            ui_main.tab_mban.setRowCount(length)
            ui_main.tab_mban.setColumnCount(3)
            print(sets)
            for i, im in enumerate(sets):
                store = QTableWidgetItem(im['store'])
                ui_main.tab_mban.setItem(i, 0, store)
                text = QTableWidgetItem(im['text'])
                ui_main.tab_mban.setItem(i, 1, text)
                css = QTableWidgetItem(im['css'])
                ui_main.tab_mban.setItem(i, 2, css)

    except Exception as err:
        print(err)
コード例 #20
0
ファイル: main.py プロジェクト: 1314liuwei/PyQt5
 def on_pushButton_SetDateTime_clicked(self):
     dttmStr = self._ui.lineEdit_DateTime.text()
     dttm = QDateTime.fromString(dttmStr, 'yyyy/MM/dd hh:mm:ss')
     self._ui.dateTimeEdit.setDateTime(dttm)
コード例 #21
0
    def processAlgorithm(self, parameters, context, feedback):
        # Get Parameters and assign to variable to work with
        server_url = self.parameterAsString(parameters, self.SERVER_URL,
                                            context)
        source_layer = self.parameterAsLayer(parameters, self.SOURCE_LYR,
                                             context)
        startlat_field = self.parameterAsString(parameters,
                                                self.STARTLAT_FIELD, context)
        startlon_field = self.parameterAsString(parameters,
                                                self.STARTLON_FIELD, context)
        endlat_field = self.parameterAsString(parameters, self.ENDLAT_FIELD,
                                              context)
        endlon_field = self.parameterAsString(parameters, self.ENDLON_FIELD,
                                              context)
        date_field = self.parameterAsString(parameters, self.DATE_FIELD,
                                            context)
        time_field = self.parameterAsString(parameters, self.TIME_FIELD,
                                            context)
        travelmode = self.parameterAsString(parameters, self.MODE, context)
        modelist = [
            'WALK', 'CAR', 'BICYCLE', 'TRANSIT', 'WALK,TRANSIT', 'WALK,BICYCLE'
        ]
        travelmode = str(modelist[int(travelmode[0])])
        traveloptimize = self.parameterAsString(parameters, self.OPTIMIZE,
                                                context)
        optimizelist = [
            'QUICK', 'TRANSFERS', 'SAFE', 'FLAT', 'GREENWAYS', 'TRIANGLE'
        ]
        traveloptimize = str(optimizelist[int(traveloptimize[0])])

        additional_params = self.parameterAsString(parameters,
                                                   self.ADDITIONAL_PARAMS,
                                                   context)
        iterinaries = self.parameterAsInt(parameters, self.ITERINARIES,
                                          context)

        total = 100.0 / source_layer.featureCount(
        ) if source_layer.featureCount(
        ) else 0  # Initialize progress for progressbar

        fields = source_layer.fields()  # get all fields of the sourcelayer
        n_source_fields = source_layer.fields().count()

        fieldlist = [  # Master for attributes and varnames
            QgsField("Route_RouteID", QVariant.Int),
            QgsField("Route_RelationID", QVariant.Int),
            QgsField("Route_From", QVariant.String),  # !
            QgsField("Route_To", QVariant.String),  # !
            QgsField("Route_Error", QVariant.String),
            QgsField("Route_ErrorID", QVariant.Int),
            QgsField("Route_ErrorDescription", QVariant.String),
            QgsField("Route_URL", QVariant.String),
            QgsField("Route_From_Lat", QVariant.Double, len=4, prec=8),
            QgsField("Route_From_Lon", QVariant.Double, len=4, prec=8),
            QgsField("Route_From_StopId", QVariant.String),
            QgsField("Route_From_StopCode", QVariant.String),
            QgsField("Route_From_Name", QVariant.String),
            QgsField("Route_From_StartTime", QVariant.DateTime),
            QgsField("Route_To_Lat", QVariant.Double, len=4, prec=8),
            QgsField("Route_To_Lon", QVariant.Double, len=4, prec=8),
            QgsField("Route_To_StopId", QVariant.String),
            QgsField("Route_To_StopCode", QVariant.String),
            QgsField("Route_To_Name", QVariant.String),
            QgsField("Route_To_EndTime", QVariant.DateTime),
            QgsField("Route_Total_Mode", QVariant.String),
            QgsField("Route_Total_Duration", QVariant.Int),
            QgsField("Route_Total_Transfers", QVariant.Int),
        ]
        for field in fieldlist:
            fields.append(field)  # add fields from the list
        # Fieldindex as dictionary to avoid a mess
        fieldindexcounter = 0  # start with index 0
        fieldindexdict = {}  # empty dictionary
        for field in fields:  # iterate through field list we just created above
            x = str(field.name()).lower()  # convert to lowercase, string
            fieldindexdict[
                fieldindexcounter] = x  # assign index as key and fieldname as value
            if '_url' in x:
                fieldindex_position_of_last_alwaysneededfield = fieldindexcounter
            fieldindexcounter += 1
        len_fieldindexdict = len(fieldindexdict)

        # Counter
        route_routeid = 0
        route_relationid = 0
        route_from = ''
        route_to = ''
        notavailablestring = None  #'not available'
        notavailableint = None  #0
        notavailableothers = None

        # some general settings
        route_headers = {
            "accept": "application/json"
        }  # this plugin only works for json responses

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT,
                                               context, fields,
                                               source_layer.wkbType(),
                                               source_layer.sourceCrs())

        for current, source_feature in enumerate(
                source_layer.getFeatures()):  # iterate over source

            route_relationid += 1

            # Making Script compatible with earlier versions than QGIS 3.18: If date or time field is a string, do not convert it to a string...
            use_date = ''
            use_time = ''
            try:
                use_date = str(
                    source_feature[date_field].toString('yyyy-MM-dd'))
            except:
                use_date = str(source_feature[date_field])
            try:
                use_time = str(source_feature[time_field].toString('HH:mm:ss'))
            except:
                use_time = str(source_feature[time_field])

            # Create URL for current feature
            route_url = (
                str(server_url) + "plan?" +  # Add Plan request to server url
                "fromPlace=" + str(source_feature[startlat_field]) + "," +
                str(source_feature[startlon_field]) + "&toPlace=" +
                str(source_feature[endlat_field]) + "," +
                str(source_feature[endlon_field]) + "&mode=" + travelmode +
                "&date=" + use_date + "&time=" + use_time +
                "&numItineraries=" + str(iterinaries) + "&optimize=" +
                traveloptimize +
                additional_params  # Additional Parameters entered as OTP-Readable string -> User responsibility
            )

            #print(route_url)

            # Reset Error Indicators
            route_error = 'Success'
            route_error_bool = False
            route_errorid = None
            route_errordescription = None
            route_errormessage = None
            route_errornopath = None

            try:  # Try to request route
                route_request = urllib.request.Request(route_url,
                                                       headers=route_headers)
                try:  # Try to receive response
                    route_response = urllib.request.urlopen(route_request)
                    try:  # Try to read response data
                        response_data = route_response.read()
                        encoding = route_response.info().get_content_charset(
                            'utf-8')
                        route_data = json.loads(response_data.decode(encoding))
                        try:  # Check if response says Error
                            route_error = 'Error: No Route'
                            route_error_bool = True
                            route_errorid = route_data['error']['id']
                            route_errordescription = route_data['error']['msg']
                            try:  # not every error delivers this
                                route_errormessage = route_data['error'][
                                    'message']
                            except:
                                pass
                            try:  # not every error delivers this
                                route_errornopath = route_data['error'][
                                    'noPath']
                            except:
                                pass
                        except:
                            route_error = 'Success'
                            route_error_bool = False
                    except:
                        route_error = 'Error: Cannot read response data'
                        route_error_bool = True
                except:
                    route_error = 'Error: No response received'
                    route_error_bool = True
            except:
                route_error = 'Error: Requesting the route failed'
                route_error_bool = True

            #print(route_error)
            try:
                if not route_data['plan'][
                        'itineraries']:  # check if response is empty
                    route_error = 'Error: Empty response route'
                    route_error_bool = True
            except:
                pass

            #print(route_data)
            # Reading response
            if route_error_bool == False:
                # Get general informations. Note that not all are available in all responses: use try/except
                try:
                    route_from_lat = route_data['plan']['from']['lat']
                    route_from_lon = route_data['plan']['from']['lon']
                except:
                    route_from_lat = notavailableint
                    route_from_lon = notavailableint
                try:
                    route_from_stopid = route_data['plan']['from']['stopId']
                except:
                    route_from_stopid = notavailablestring
                try:
                    route_from_stopcode = route_data['plan']['from'][
                        'stopCode']
                except:
                    route_from_stopcode = notavailablestring
                try:
                    route_from_name = route_data['plan']['from']['name']
                except:
                    route_from_name = notavailablestring
                try:
                    route_to_lat = route_data['plan']['to']['lat']
                    route_to_lon = route_data['plan']['to']['lon']
                except:
                    route_to_lat = notavailableint
                    route_to_lon = notavailableint
                try:
                    route_to_stopid = route_data['plan']['to']['stopId']
                except:
                    route_to_stopid = notavailablestring
                try:
                    route_to_stopcode = route_data['plan']['to']['stopCode']
                except:
                    route_to_stopcode = notavailablestring
                try:
                    route_to_name = route_data['plan']['to']['name']
                except:
                    route_to_name = notavailablestring

                # loop through iterinaries
                for iter in route_data['plan']['itineraries']:
                    route_routeid += 1
                    new_feature = QgsFeature(fields)
                    try:
                        route_from_starttime = iter['startTime']
                        route_from_starttime = datetime.fromtimestamp(
                            int(route_from_starttime) / 1000)
                        route_from_starttime = QDateTime.fromString(
                            str(route_from_starttime), 'yyyy-MM-dd hh:mm:ss')
                    except:
                        route_from_starttime = notavailableothers
                    try:
                        route_to_endtime = iter['endTime']
                        route_to_endtime = datetime.fromtimestamp(
                            int(route_to_endtime) / 1000)
                        route_to_endtime = QDateTime.fromString(
                            str(route_to_endtime), 'yyyy-MM-dd hh:mm:ss')
                    except:
                        route_to_endtime = notavailableothers
                    try:
                        route_total_duration = iter['duration']
                    except:
                        route_total_duration = notavailableint
                    route_total_distance = 0  # set to 0 on start of each new route, well take the sum of all legs of a route
                    route_total_mode = travelmode
                    try:
                        route_total_transittime = iter['transitTime']
                    except:
                        route_total_transittime = notavailableint
                    try:
                        route_total_waitingtime = iter['waitingTime']
                    except:
                        route_total_waitingtime = notavailableint
                    try:
                        route_total_walktime = iter['walkTime']
                    except:
                        route_total_walktime = notavailableint
                    try:
                        route_total_walkdistance = iter['walkDistance']
                    except:
                        route_total_walkdistance = notavailableint
                    try:
                        route_total_transfers = iter['transfers']
                    except:
                        route_total_transfers = notavailableint

                    new_feature.setGeometry(source_feature.geometry())
                    # Adding the attributes to resultlayer
                    for key, value in fieldindexdict.items(
                    ):  # keys contain the fieldindex, values the variablename which is the same as the fieldname, just in lowercase
                        fieldindex = key
                        if key < n_source_fields:  # Copy source attributes from source layer
                            fieldvalue = source_feature[
                                fieldindex]  # source_feature = sourcelayer-feature, new_feature = new feature
                        else:  # Get the leg attributes from variables
                            fieldvalue = locals(
                            )[value]  # variables are named exactly as the fieldnames, just lowercase, we adjusted that before
                        new_feature.setAttribute(fieldindex, fieldvalue)
                    sink.addFeature(
                        new_feature,
                        QgsFeatureSink.FastInsert)  # add feature to the output
                    # END OF LOOP iterinaries

            # END OF if route_error_bool == False
            else:  # Create error-dummyfeature if no route has been returned
                route_routeid += 1
                new_feature = QgsFeature(fields)
                try:
                    route_errorid = route_data['error']['id']
                except:
                    route_errorid = notavailableint
                try:
                    route_errordescription = route_data['error']['msg']
                except:
                    route_errordescription = notavailablestring
                try:
                    route_errormessage = route_data['error']['message']
                except:
                    route_errormessage = notavailablestring
                try:
                    route_errornopath = route_data['error']['noPath']
                except:
                    route_errornopath = notavailablestring

                new_feature.setGeometry(source_feature.geometry())
                # Adding the attributes to resultlayer
                for key, value in fieldindexdict.items(
                ):  # keys contain the fieldindex, values the variablename which is the same as the fieldname, just in lowercase
                    fieldindex = key
                    if fieldindex < n_source_fields:  # copy attributes from source layer
                        fieldvalue = source_feature[fieldindex]
                        new_feature[fieldindex] = fieldvalue
                    elif fieldindex <= fieldindex_position_of_last_alwaysneededfield:  # Only fill the first fields on error
                        fieldvalue = locals()[value]
                        new_feature[fieldindex] = fieldvalue
                    else:  # Leave the others empty as there is no data available
                        fieldvalue = None
                        new_feature[fieldindex] = fieldvalue

                sink.addFeature(
                    new_feature,
                    QgsFeatureSink.FastInsert)  # add feature to the output
                # END OF errorroutecreation

            if feedback.isCanceled():  # Cancel algorithm if button is pressed
                break

            feedback.setProgress(int(current *
                                     total))  # Set Progress in Progressbar

        return {self.OUTPUT: dest_id}  # Return result of algorithm
コード例 #22
0
ファイル: Table.py プロジェクト: zazachubin/Money-tracker
    def importEvents(self, data):
        self.setRowCount(0)
        TimeStampsIndex = 0
        for key in data:
            self.rowNumb = self.rowCount()
            self.setRowCount(self.rowNumb + len(data[key]))

            timeStamp = QDateTimeEdit()
            timeStamp.setDisplayFormat("dd.MM.yyyy")
            timeStamp.setReadOnly(True)
            timeStampCell = QDateTime.currentDateTime()
            timeStampCell = QDateTime.fromString(key, "dd.MM.yyyy")
            timeStamp.setDateTime(timeStampCell)
            self.setCellWidget(TimeStampsIndex, 0, timeStamp)
            if len(data[key]) > 1:
                self.setSpan(TimeStampsIndex, 0, len(data[key]) , 1)
            
            for row in range(len(data[key])):
                cell_0 = QTableWidgetItem('')
                cell_0.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                cell_0.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled )

                cell_1 = QTableWidgetItem('')
                cell_1.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                cell_1.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled )

                cell_2 = QTableWidgetItem('')
                cell_2.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                cell_2.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled )

                cell_3 = QTableWidgetItem('')
                cell_3.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                cell_3.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled )

                cell_4 = QTableWidgetItem('')
                if data[key][row][4]['cell_4']:
                    cell_4.setIcon(QtGui.QIcon('icon/cash.svg'))
                else:
                    cell_4.setIcon(QtGui.QIcon('icon/card.svg'))
                
                cell_4.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
                cell_4.setFlags( Qt.ItemIsSelectable | Qt.ItemIsEnabled )

                self.setItem(TimeStampsIndex + row, 1, cell_0)
                self.setItem(TimeStampsIndex + row, 2, cell_1)
                self.setItem(TimeStampsIndex + row, 3, cell_2)
                self.setItem(TimeStampsIndex + row, 4, cell_3)
                self.setItem(TimeStampsIndex + row, 5, cell_4)

                self.item(TimeStampsIndex + row, 1).setText(data[key][row][0]['cell_0'])
                if self._units[data[key][row][1]['cell_1.2']] == "--":
                    self.item(TimeStampsIndex + row, 2).setText(self._units[data[key][row][1]['cell_1.2']])
                else:
                    self.item(TimeStampsIndex + row, 2).setText(data[key][row][1]['cell_1.1'] + self._units[data[key][row][1]['cell_1.2']])
                self.item(TimeStampsIndex + row, 3).setText(self._category[data[key][row][2]['cell_2.1']])
                try:
                    if data[key][row][3]['cell_3.3'] == "--" or data[key][row][3]['cell_3.3'] == "":
                        self.item(TimeStampsIndex + row, 4).setText("%.2f" % round(float(data[key][row][3]['cell_3.1']), 2) + self._CurrencyIndex[data[key][row][3]['cell_3.2']])
                    else:
                        self.item(TimeStampsIndex + row, 4).setText("%.2f" % round(float(data[key][row][3]['cell_3.1']), 2) + self._CurrencyIndex[data[key][row][3]['cell_3.2']] + " ---> " + "%.2f" % round(float(data[key][row][3]['cell_3.3']), 2) + self._CurrencyIndex[data[key][row][3]['cell_3.4']])
                except ValueError:
                    pass
                if data[key][row][4]['cell_4']:
                    self.item(TimeStampsIndex + row, 5).setText("ნაღდი")
                else:
                    self.item(TimeStampsIndex + row, 5).setText("გადარიცხვა")
            
            TimeStampsIndex = TimeStampsIndex + len(data[key])

        self.horizontalHeader().setSectionResizeMode(0, QHeaderView.ResizeToContents)
        self.horizontalHeader().setSectionResizeMode(1, QHeaderView.Stretch)
        self.horizontalHeader().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.horizontalHeader().setSectionResizeMode(3, QHeaderView.ResizeToContents)
        self.horizontalHeader().setSectionResizeMode(4, QHeaderView.ResizeToContents)
        self.horizontalHeader().setSectionResizeMode(5, QHeaderView.ResizeToContents)
        self.scrollToBottom()
コード例 #23
0
    def __parseUrl(self, url):
        """
        Private method to parse the AdBlock URL for the subscription.
        
        @param url AdBlock URL for the subscription (QUrl)
        """
        if url.scheme() != "abp":
            return

        if url.path() != "subscribe":
            return

        if qVersion() >= "5.0.0":
            from PyQt5.QtCore import QUrlQuery
            urlQuery = QUrlQuery(url)
            self.__title = QUrl.fromPercentEncoding(
                QByteArray(urlQuery.queryItemValue("title").encode()))
            self.__enabled = urlQuery.queryItemValue("enabled") != "false"
            self.__location = QByteArray(
                QUrl.fromPercentEncoding(
                    QByteArray(urlQuery.queryItemValue(
                        "location").encode())).encode("utf-8"))

            # Check for required subscription
            self.__requiresLocation = QUrl.fromPercentEncoding(
                QByteArray(
                    urlQuery.queryItemValue("requiresLocation").encode()))
            self.__requiresTitle = QUrl.fromPercentEncoding(
                QByteArray(urlQuery.queryItemValue("requiresTitle").encode()))
            if self.__requiresLocation and self.__requiresTitle:
                import Helpviewer.HelpWindow
                Helpviewer.HelpWindow.HelpWindow.adBlockManager()\
                    .loadRequiredSubscription(self.__requiresLocation,
                                              self.__requiresTitle)

            lastUpdateString = urlQuery.queryItemValue("lastUpdate")
            self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                                     Qt.ISODate)
        else:
            self.__title = \
                QUrl.fromPercentEncoding(url.encodedQueryItemValue(b"title"))
            self.__enabled = QUrl.fromPercentEncoding(
                url.encodedQueryItemValue(b"enabled")) != "false"
            self.__location = QByteArray(
                QUrl.fromPercentEncoding(
                    url.encodedQueryItemValue(b"location")).encode("utf-8"))

            # Check for required subscription
            self.__requiresLocation = QUrl.fromPercentEncoding(
                url.encodedQueryItemValue(b"requiresLocation"))
            self.__requiresTitle = QUrl.fromPercentEncoding(
                url.encodedQueryItemValue(b"requiresTitle"))
            if self.__requiresLocation and self.__requiresTitle:
                import Helpviewer.HelpWindow
                Helpviewer.HelpWindow.HelpWindow.adBlockManager()\
                    .loadRequiredSubscription(self.__requiresLocation,
                                              self.__requiresTitle)

            lastUpdateByteArray = url.encodedQueryItemValue(b"lastUpdate")
            lastUpdateString = QUrl.fromPercentEncoding(lastUpdateByteArray)
            self.__lastUpdate = QDateTime.fromString(lastUpdateString,
                                                     Qt.ISODate)

        self.__loadRules()
コード例 #24
0
    def __installQtDoc(self, name, version, engine):
        """
        Private method to install/update a Qt help document.
        
        @param name name of the Qt help document (string)
        @param version Qt version of the help documens (integer)
        @param engine reference to the help engine (QHelpEngineCore)
        @return flag indicating success (boolean)
        """
        versionKey = "qt_version_{0}@@{1}".format(version, name)
        info = engine.customValue(versionKey, "")
        lst = info.split('|')

        dt = QDateTime()
        if len(lst) and lst[0]:
            dt = QDateTime.fromString(lst[0], Qt.ISODate)

        qchFile = ""
        if len(lst) == 2:
            qchFile = lst[1]

        if version == 4:
            docsPath = QDir(
                QLibraryInfo.location(QLibraryInfo.DocumentationPath) +
                QDir.separator() + "qch")
        elif version == 5:
            docsPath = QLibraryInfo.location(QLibraryInfo.DocumentationPath)
            if (not os.path.isdir(docsPath)
                    or len(QDir(docsPath).entryList(["*.qch"])) == 0):
                # Qt installer is a bit buggy; it's missing a symbolic link
                docsPathList = QDir.fromNativeSeparators(docsPath).split("/")
                docsPath = os.sep.join(
                    docsPathList[:-3] +
                    ["Docs", "Qt-{0}.{1}".format(*qVersionTuple())])
            docsPath = QDir(docsPath)
        else:
            # unsupported Qt version
            return False

        files = docsPath.entryList(["*.qch"])
        if not files:
            engine.setCustomValue(versionKey,
                                  QDateTime().toString(Qt.ISODate) + '|')
            return False

        for f in files:
            if f.startswith(name + "."):
                fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
                namespace = QHelpEngineCore.namespaceName(
                    fi.absoluteFilePath())
                if not namespace:
                    continue

                if (dt.isValid()
                        and namespace in engine.registeredDocumentations()
                        and (fi.lastModified().toString(Qt.ISODate)
                             == dt.toString(Qt.ISODate))
                        and qchFile == fi.absoluteFilePath()):
                    return False

                if namespace in engine.registeredDocumentations():
                    engine.unregisterDocumentation(namespace)

                if not engine.registerDocumentation(fi.absoluteFilePath()):
                    self.errorMessage.emit(
                        self.tr(
                            """<p>The file <b>{0}</b> could not be"""
                            """ registered. <br/>Reason: {1}</p>""").format(
                                fi.absoluteFilePath, engine.error()))
                    return False

                engine.setCustomValue(
                    versionKey,
                    fi.lastModified().toString(Qt.ISODate) + '|' +
                    fi.absoluteFilePath())
                return True

        return False
コード例 #25
0
 def set_default_data(self, data):
     if data is None:
         return
     self.widget: QDateTimeEdit
     self.widget.setDateTime(QDateTime.fromString(data, self.format))
コード例 #26
0
def format_sql_cmd(sql_dict):
    highlight_words = {'Name':[],'Path':[]}         # List:[[ case, word], .....]
    def escape_str(text):
        return '''"%s"''' % text.replace("\"", "\"\"")

    # 'path': table['path'],
    # 'uuid': table['uuid'],
    # 'sql_text': sql_text,
    # 'rowid_low': rowid_low,
    # 'rowid_high': rowid_high,
    # ======================================
    path        = sql_dict['path']
    uuid        = sql_dict['uuid']
    sql_text    = sql_dict['sql_text']
    rowid_low   = sql_dict['rowid_low']
    rowid_high  = sql_dict['rowid_high']

    # match_section = GlobalVar.MATCH_OPTION

    sql_text = sql_text.strip()

    header_list = QUERY_HEADER_LIST[:]
    path_idx = header_list.index('Path')
    header_list[path_idx] = '''"%s"''' % path.replace("\"", "\"\"") +\
                            "||Path"
    sql_mask = " SELECT " + ",".join(header_list) + (' FROM `%s` ' % uuid)

    match_section = GlobalVar.MATCH_OPTION
    # print "GlobalVar.MATCH_OPTION:",GlobalVar.MATCH_OPTION
    # print "match_section:", match_section
    #============================ default field===========================
    if match_section == 1:      # match Filename only
        default_field = 'Filename'
    elif match_section == 2:    # match path (without dev location) only
        default_field = 'Path'
    elif match_section == 1|2:  # match path(without dev location) + filename
        default_field = '''Path||"/"||Filename'''
    elif match_section == 4:    # match path(WITH dev location) only
        default_field = header_list[path_idx]
    elif match_section == 1|4:  # match path(WITH dev location) + filename
        default_field = header_list[path_idx] + '''||"/"||Filename'''

    # ============================ default verb===========================
    default_verb = 'LIKE'

    # ============================ default case===========================
    # default_case = ''       # 'COLLATE  nocase'
    case_sensitive_like_flag_ON = True
    if GlobalVar.CASE_SENSTITIVE:
        default_case = ''
    else:
        default_case = ' COLLATE  nocase '
        if not (' case:' in sql_text or ':case:' in sql_text):
            case_sensitive_like_flag_ON = False




    # ====================================================================
    sql_cmd = ''
    sql_cmd_list = []
    word_list = []
    tmp_section = ''
    quot_flag = False
    i = 0
    last_verb = ''
    last_field = ''
    last_word = ''

    field_stack = []
    verb_stack = []
    word_stack = []
    case_stack = []

    field_stack.append(default_field)
    verb_stack.append(default_verb)
    case_stack.append(default_case)
    phase_count_stack = [0]

    def get_highlight_word():
        field = field_stack[-1]
        verb = verb_stack[-1]
        case = case_stack[-1]
        regexp_flag = verb == "REGEXP"

        if verb == "REGEXP":
            return

        word_stack_tmp = word_stack[:]
        if word_stack_tmp[0] == '"' and word_stack_tmp[-1] == '"':
            word_stack_tmp[:] = word_stack_tmp[1:-1]
        word_temp = ''.join(word_stack_tmp)

        if '*' in word_temp or '?' in word_temp:
            return

        if field.endswith('Filename'):
            if case == '':
                highlight_words['Name'].append([1, word_temp])
            else:
                highlight_words['Name'].append([0, word_temp])

        if field.endswith('Path||"/"||Filename') or field.endswith('Path'):
            if case == '':
                highlight_words['Path'].append([1, word_temp])
            else:
                highlight_words['Path'].append([0, word_temp])

    def parser_word():
        verb = verb_stack[-1]
        regexp_flag = verb == "REGEXP"
        exact_match = False
        wildcard  = False
        word_tmp = ''
        if word_stack[0] == '"' and word_stack[-1] == '"':
            exact_match = True
            word_stack[:] = word_stack[1:-1]

        if regexp_flag and exact_match:
            word_tmp = ''.join(word_stack).replace('\\"','""')
            return [exact_match, wildcard, word_tmp]

        i = 0
        while i < len(word_stack):
            c = word_stack[i]
            if c == '\\' and i < len(word_stack) - 1:
                if word_stack[i + 1] == '"':
                    word_tmp += '""'
                else:
                    word_tmp += word_stack[i] + word_stack[i + 1]
                i += 1
            elif c == '"':
                word_tmp += '""'
            elif c == '%' or c == '_':
                word_tmp += '\\' + c
            elif c == '*':
                wildcard = True
                word_tmp += '%'
            elif c == '?':
                wildcard = True
                word_tmp += '_'
            else:
                word_tmp += word_stack[i]

            i += 1
        word_stack[:] = []
        return [exact_match, wildcard, word_tmp]

    def build_query():
        field = field_stack[-1]
        verb  = verb_stack[-1]
        case  = case_stack[-1]
        regexp_flag = verb == "REGEXP"

        # highlight list
        get_highlight_word()

        # sql parser
        exact_match, wildcard,  word = parser_word()       # any wildcard will enable LIKE matach -- exact_match = False.

        if ( regexp_flag and exact_match):
            sql_cmd = '(' + field + ' REGEXP "' + word + '" ' + case + ')'
            return sql_cmd

        # http://stackoverflow.com/questions/543580/equals-vs-like
        # if exact_match and (not wildcard):
        #     verb = '='
        # if wildcard:
        #     verb = 'LIKE'
        ##  overwrite ALL '='. '=" does not support ESCAPE.
        verb = 'LIKE'
        if verb == 'LIKE' and (not exact_match):
            word = "%" + word + "%"


        sql_cmd = '(' + field + ' ' + verb + ' "' + word + r'" ESCAPE "\" ' + case + ')'

        if verb == 'LIKE':
            if case_sensitive_like_flag_ON:
                if case == '':  # case sensitive
                    pass
                else:        #   ' COLLATE  nocase '
                    sql_cmd = '( UPPER(' + field + ') ' + verb + ' "' + word.upper() + r'" ESCAPE "\" ' + case + ')'
            else:
                # global no case
                pass


        return sql_cmd

    sql_cmd = ''
    sql = ''
    word = ''
    qutoe_flag = False
    logical_tmp = [False ,False]  #  is OR, is NOT

    try:
        while i < len(sql_text):
            c = sql_text[i]
            if c in ' |' and word != '' and (not qutoe_flag):
                phase_segment_flag = True
                # phase_count_stack[-1] += 1
            else:
                phase_segment_flag = False

            if c == '>' and sql_text[i-1] == ' ' and (not qutoe_flag):
                phase_count_stack[-2] += 1

            if c == '\"':
                # exact-match
                if qutoe_flag:
                    # qutoe end
                    word += c
                    qutoe_flag = False
                    phase_segment_flag = True
                else:
                    qutoe_flag = True
                    # word_stack = list(word.strip())
                    word += c
            elif c  == '\\' and i <len(sql_text)-1:
                word += sql_text[i] + sql_text[i + 1]
                i += 1
            elif qutoe_flag:
                word += c
                i += 1
                continue
            elif c == ':':
                if word == 'f':
                    field_stack[-1] = 'Filename'
                elif word == 'p':
                    field_stack[-1] = 'Path'
                elif word == 'pf':
                    field_stack[-1] = '''Path||"/"||Filename'''
                elif word == 'dp':
                    field_stack[-1] = header_list[path_idx]
                elif word == 'ff':
                    field_stack[-1] = header_list[path_idx] + '''||"/"||Filename'''
                elif word == 'reg':
                    verb_stack[-1] = 'REGEXP'
                elif word == 'noreg':
                    verb_stack[-1] = 'LIKE'
                elif word == 'case':
                    case_stack[-1] = ''
                elif word == 'nocase':
                    case_stack[-1] = ' COLLATE  nocase '
                elif word == 'size':
                    size_start = i + 1
                    while size_start < len(sql_text) and not (sql_text[size_start] in '0123456789'):
                        size_start += 1

                    verb = sql_text[i + 1: size_start]
                    assert verb in ['<', '=', '>', '!=', '<=', '>=']

                    size_end = size_start
                    while size_end < len(sql_text) and sql_text[size_end] in '0123456789' :
                        size_end += 1
                    size = int(sql_text[size_start:size_end])
                    if size_end < len(sql_text) and sql_text[size_end] in 'kKmMgGtT' :
                        if sql_text[size_end] in 'kK':
                            size *= 1024
                        elif sql_text[size_end] in 'mM':
                            size *= 1024 * 1024
                        elif sql_text[size_end] in 'Gg':
                            size *= 1024 * 1024 * 1024
                        elif sql_text[size_end] in 'tT':
                            size *= 1024 * 1024 * 1024 * 1024
                        i = size_end +1
                    else:
                        i = size_end

                    phase_count_stack[-1] += 1
                    if phase_count_stack[-1] > 1:
                        if logical_tmp[0]:  # is OR
                            sql_cmd += ' OR '
                        else:
                            sql_cmd += ' AND '
                    if logical_tmp[1]:
                        sql_cmd += ' NOT '
                    logical_tmp[:] = [False, False]

                    sql_cmd += '(' + 'Size' + verb + str(size) + ')'

                elif word == 'folder' or word == 'file':
                    phase_count_stack[-1] += 1
                    if phase_count_stack[-1] > 1:
                        if logical_tmp[0]:  # is OR
                            sql_cmd += ' OR '
                        else:
                            sql_cmd += ' AND '
                    if logical_tmp[1]:
                        sql_cmd += ' NOT '

                    if word == 'folder':
                        sql_cmd +=  '( IsFolder)'
                    elif word == 'file':
                        sql_cmd += '(NOT IsFolder)'
                    logical_tmp[:] = [False, False]
                    word = ''
                    i += 1
                    continue

                elif word == "mtime" or word == "atime" or word == "ctime":
                    date_string_start = sql_text.index('"', i + 1)
                    date_string_end = sql_text.index('"', date_string_start + 1)
                    verb = sql_text[i + 1 : date_string_start]


                    assert verb in ['<','=','>','!=','<=','>=']
                    date_string = sql_text[date_string_start+1 : date_string_end]

                    try:
                        unixtime = int(date_string)
                    except:
                        unixtime = None
                    if unixtime is None:
                        date = QDateTime.fromString(date_string, GlobalVar.DATETIME_FORMAT)
                        if date.toString() == '':
                            raise Exception('Fail to format date string:\n%s\n%s' % (GlobalVar.DATETIME_FORMAT,
                                                                                     date_string) )
                        unixtime = date.toTime_t()

                    phase_count_stack[-1] += 1
                    if phase_count_stack[-1] > 1:
                        if logical_tmp[0]:  # is OR
                            sql_cmd += ' OR '
                        else:
                            sql_cmd += ' AND '
                    if logical_tmp[1]:
                        sql_cmd += ' NOT '

                    sql_cmd += '(' + word + verb + str(unixtime) + ')'
                    logical_tmp[:] = [False, False]

                    i = date_string_end

                word = ''
                i += 1
                continue
            elif c == '|':
                logical_tmp[0] = True  # is OR
                # if word != '':
                    # word_stack = list(word.strip())
                    # word = ''
                    # sql_cmd += build_query()
                while sql_text[i + 1] == '|' or sql_text[i + 1] == ' ':
                    i += 1
            elif c == ' ':
                # if logical_tmp == '':           #   <SPACE>|<SPACE>
                #     logical_tmp = ' AND '
                # if word != '':
                #     word_stack = list(word.strip())
                #     word = ''
                #     sql_cmd += build_query()
                while sql_text[i+1] == ' ':
                    i += 1
            elif c == '!':
                logical_tmp[1] = not logical_tmp[1]
            elif c == '<':
                if word == '':
                    if phase_count_stack[-1] > 0:
                        if logical_tmp[0]:  # is OR
                            sql_cmd += ' OR '
                        else:
                            sql_cmd += ' AND '
                    if logical_tmp[1]:
                        sql_cmd += ' NOT '
                    logical_tmp[:] = [False, False]
                    sql_cmd += ' ( '
                    field_stack.append(field_stack[-1])
                    verb_stack.append(verb_stack[-1])
                    case_stack.append(case_stack[-1])
                    phase_count_stack.append(0)
                else:
                    pass    # larger, less than

            elif c == '>':      # insert ")" after sql_cmd inserted.
                pass

            else:
                word += c

            if i == len(sql_text)-1 and ( (not quot_flag) and c != '"' ):        # Text end
                phase_segment_flag = True
                # phase_count_stack[-1]+=1

            if (phase_segment_flag and word != ''):
                phase_count_stack[-1] += 1
                word_stack = list(word.strip())
                word = ''
                if phase_count_stack[-1]>1:
                    if logical_tmp[0]:      # is OR
                        sql_cmd += ' OR '
                    else:
                        sql_cmd += ' AND '
                if logical_tmp[1]:
                    sql_cmd += ' NOT '



                sql_cmd += build_query()
                logical_tmp[:] = [False,False]

            if c == '>' :
                field_stack.pop()
                verb_stack.pop()
                case_stack.pop()
                phase_count_stack.pop()
                sql_cmd += ' ) '

            i+=1

        # print sql_mask
        # print sql_text
        # print sql_cmd
        # print word_list
        sql = sql_mask + ' WHERE ' + ' (ROWID BETWEEN %s AND %s) AND' % (rowid_low, rowid_high)\
              + ' (' + sql_cmd + ') ' + " LIMIT %d" % GlobalVar.QUERY_LIMIT

        # if case_sensitive_like_flag_ON:
        #     sql = ' PRAGMA case_sensitive_like=ON; ' + sql
        # else:
        #     sql = ' PRAGMA case_sensitive_like=OFF; ' + sql

        # OK_flag
        return True, sql_mask, sql_cmd,sql , case_sensitive_like_flag_ON, highlight_words
    except Exception as e:
        return False, None, str(e), None, case_sensitive_like_flag_ON, highlight_words
コード例 #27
0
def generate_BRLog_items(each_log) -> list:
    """
    :param each_log:
    :return: list[PyQt5.QtWidgets.QTableWidgetItem],返回一个全是item的列表,用于设置到表格中
    """
    item_list = list()
    cur_reader_ID = each_log.get_readerID()
    item_reader_ID = QTableWidgetItem(
        cur_reader_ID if cur_reader_ID != '' else '无',
        CellType_BRLog.ctReader_ID.value)
    item_reader_ID.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_reader_ID)

    cur_borrowTime = each_log.get_borrowTime()
    item_borrowTime = QTableWidgetItem(
        cur_borrowTime if cur_borrowTime != '' else '无',
        CellType_BRLog.ctBT.value)
    item_borrowTime.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_borrowTime)

    cur_borrowPlace = each_log.get_borrowPlace()
    item_borrowPlace = QTableWidgetItem(
        cur_borrowPlace if cur_borrowPlace != '' else '无',
        CellType_BRLog.ctBP.value)
    item_borrowPlace.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_borrowPlace)

    cur_lending_period = int(''.join(
        re.findall(r'\d+', each_log.get_lending_period())))  # 90天 把天去掉
    item_lending_period = QTableWidgetItem(
        str(cur_lending_period) + '天', CellType_BRLog.ctPeriod.value)
    item_lending_period.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_lending_period)

    cur_dueDate = QDate.fromString(
        cur_borrowTime,
        'yyyy-MM-dd').addDays(cur_lending_period).toString('yyyy-MM-dd')
    item_dueDate = QTableWidgetItem(cur_dueDate, CellType_BRLog.ctDue.value)
    item_dueDate.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_dueDate)

    cur_IsReturn = each_log.get_IsReturn()
    item_IsReturn = QTableWidgetItem('已归还', CellType_BRLog.ctIsReturn.value)
    if cur_IsReturn == False:
        item_IsReturn = QTableWidgetItem('未归还',
                                         CellType_BRLog.ctIsReturn.value)
    item_IsReturn.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_IsReturn)

    cur_returnTime = each_log.get_returnTime()
    item_returnTime = QTableWidgetItem(
        cur_returnTime if cur_returnTime != '' else '(未归还)',
        CellType_BRLog.ctRT.value)
    item_returnTime.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_returnTime)

    cur_returnPlace = each_log.get_returnPlace()
    item_returnPlace = QTableWidgetItem(
        cur_returnPlace if cur_returnPlace != '' else '(未归还)',
        CellType_BRLog.ctRP.value)
    item_returnPlace.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_returnPlace)

    cur_real_lendingPeriod = '(未归还)'
    if cur_borrowTime != '无' and cur_returnTime != '(未归还)':
        # 必须先转换为QDate
        cur_borrowTime += ' 00:00:00'
        cur_returnTime += ' 00:00:00'  # 必须要转为QDateTime
        cur_borrowDate = QDateTime.fromString(cur_borrowTime,
                                              'yyyy-MM-dd hh:mm:ss')
        cur_returnDate = QDateTime.fromString(cur_returnTime,
                                              'yyyy-MM-dd hh:mm:ss')
        seconds = cur_borrowDate.secsTo(cur_returnDate) / (24 * 3600)
        cur_real_lendingPeriod = str(int(seconds)) + '天'
    item_real_lendingPeriod = QTableWidgetItem(
        cur_real_lendingPeriod, CellType_BRLog.ctRealPeriod.value)
    item_real_lendingPeriod.setTextAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
    item_list.append(item_real_lendingPeriod)
    return item_list
コード例 #28
0
ファイル: plugintodo.py プロジェクト: lycying/seeking
 def evt_click(self, item, pos):
     self.todonote.fill(item.text(4))
     self.titleeditor.setText(item.text(0))
     self.dateeditor.setDateTime(QDateTime.fromString(item.text(1), "yyyyMMddhhmmss"))
     self.percenteditor.setValue(int(item.text(2)))
     self.leveleditor.setValue(int(item.text(3)))
コード例 #29
0
ファイル: project.py プロジェクト: GuLinux/PySpectrum
 def decode_obj(self, obj):
     if 'datetime' in obj and len(obj.keys()) == 1:
         return QDateTime.fromString(obj['datetime'], Qt.ISODate)
     return obj
コード例 #30
0
ファイル: aillio.py プロジェクト: roundfile/new-builds
def extractProfileBulletDict(data, aw):
    try:
        res = {}  # the interpreted data set

        if "celsius" in data and not data["celsius"]:
            res["mode"] = 'F'
        else:
            res["mode"] = 'C'
        if "comments" in data:
            res["roastingnotes"] = data["comments"]
        try:
            if "dateTime" in data:
                try:
                    dateQt = QDateTime.fromString(
                        data["dateTime"], Qt.ISODate)  # RFC 3339 date time
                except:
                    dateQt = QDateTime.fromMSecsSinceEpoch(data["dateTime"])
                if dateQt.isValid():
                    res["roastdate"] = encodeLocal(dateQt.date().toString())
                    res["roastisodate"] = encodeLocal(dateQt.date().toString(
                        Qt.ISODate))
                    res["roasttime"] = encodeLocal(dateQt.time().toString())
                    res["roastepoch"] = int(dateQt.toTime_t())
                    res["roasttzoffset"] = time.timezone
        except:
            pass
        try:
            res["title"] = data["beanName"]
        except:
            pass
        if "roastName" in data:
            res["title"] = data["roastName"]
        try:
            if "roastNumber" in data:
                res["roastbatchnr"] = int(data["roastNumber"])
        except:
            pass
        if "beanName" in data:
            res["beans"] = data["beanName"]
        elif "bean" in data and "beanName" in data["bean"]:
            res["beans"] = data["bean"]["beanName"]
        try:
            if "weightGreen" in data or "weightRoasted" in data:
                wunit = aw.qmc.weight_units.index(aw.qmc.weight[2])
                if wunit in [1, 3]:  # turn Kg into g, and lb into oz
                    wunit = wunit - 1
                wgreen = 0
                if "weightGreen" in data:
                    wgreen = float(data["weightGreen"])
                wroasted = 0
                if "weightRoasted" in data:
                    wroasted = float(data["weightRoasted"])
                res["weight"] = [wgreen, wroasted, aw.qmc.weight_units[wunit]]
        except:
            pass
        try:
            if "agtron" in data:
                res["ground_color"] = int(round(data["agtron"]))
                res["color_system"] = "Agtron"
        except:
            pass
        try:
            if "roastMasterName" in data:
                res["operator"] = data["roastMasterName"]
        except:
            pass
        res["roastertype"] = "Aillio Bullet R1"

        if "ambient" in data:
            res['ambientTemp'] = data["ambient"]
        if "humidity" in data:
            res["ambient_humidity"] = data["humidity"]

        if "beanTemperature" in data:
            bt = data["beanTemperature"]
        else:
            bt = []
        if "drumTemperature" in data:
            dt = data["drumTemperature"]
        else:
            dt = []
        # make dt the same length as bt
        dt = dt[:len(bt)]
        dt.extend(-1 for _ in range(len(bt) - len(dt)))

        if "exitTemperature" in data:
            et = data["exitTemperature"]
        else:
            et = None
        if et is not None:
            # make et the same length as bt
            et = et[:len(bt)]
            et.extend(-1 for _ in range(len(bt) - len(et)))

        if "beanDerivative" in data:
            ror = data["beanDerivative"]
        else:
            ror = None
        if ror is not None:
            # make et the same length as bt
            ror = ror[:len(bt)]
            ror.extend(-1 for _ in range(len(bt) - len(ror)))

        if "sampleRate" in data:
            sr = data["sampleRate"]
        else:
            sr = 2.
        res["samplinginterval"] = 1.0 / sr
        tx = [x / sr for x in range(len(bt))]
        res["timex"] = tx
        res["temp1"] = dt
        res["temp2"] = bt

        timeindex = [-1, 0, 0, 0, 0, 0, 0, 0]
        if "roastStartIndex" in data:
            timeindex[0] = min(max(data["roastStartIndex"], 0), len(tx) - 1)
        else:
            timeindex[0] = 0

        labels = [
            "indexYellowingStart", "indexFirstCrackStart",
            "indexFirstCrackEnd", "indexSecondCrackStart",
            "indexSecondCrackEnd"
        ]
        for i in range(1, 6):
            try:
                idx = data[labels[i - 1]]
                # RoastTime seems to interpret all index values 1 based, while Artisan takes the 0 based approach. We substruct 1
                if idx > 1:
                    timeindex[i] = max(min(idx - 1, len(tx) - 1), 0)
            except:
                pass

        if "roastEndIndex" in data:
            timeindex[6] = max(0, min(data["roastEndIndex"], len(tx) - 1))
        else:
            timeindex[6] = max(0, len(tx) - 1)
        res["timeindex"] = timeindex

        # extract events from newer JSON format
        specialevents = []
        specialeventstype = []
        specialeventsvalue = []
        specialeventsStrings = []

        # extract events from older JSON format
        try:
            eventtypes = [
                "blowerSetting", "drumSpeedSetting", "--",
                "inductionPowerSetting"
            ]
            for j in range(len(eventtypes)):
                eventname = eventtypes[j]
                if eventname != "--":
                    last = None
                    ip = data[eventname]
                    for i in range(len(ip)):
                        v = ip[i] + 1
                        if last is None or last != v:
                            specialevents.append(i)
                            specialeventstype.append(j)
                            specialeventsvalue.append(v)
                            specialeventsStrings.append("")
                            last = v
        except:
            pass

        # extract events from newer JSON format
        try:
            for action in data["actions"]["actionTimeList"]:
                time_idx = action["index"] - 1
                value = action["value"] + 1
                if action["ctrlType"] == 0:
                    event_type = 3
                elif action["ctrlType"] == 1:
                    event_type = 0
                elif action["ctrlType"] == 2:
                    event_type = 1
                specialevents.append(time_idx)
                specialeventstype.append(event_type)
                specialeventsvalue.append(value)
                specialeventsStrings.append(str(value))
        except:
            pass
        if len(specialevents) > 0:
            res["specialevents"] = specialevents
            res["specialeventstype"] = specialeventstype
            res["specialeventsvalue"] = specialeventsvalue
            res["specialeventsStrings"] = specialeventsStrings

        if (ror is not None
                and len(ror) == len(tx)) or (et is not None
                                             and len(et) == len(tx)):
            # add one (virtual) extra device
            res["extradevices"] = [25]
            res["extratimex"] = [tx]

            temp3_visibility = True
            temp4_visibility = False
            if et is not None and len(et) == len(tx):
                res["extratemp1"] = [et]
            else:
                res["extratemp1"] = [[-1] * len(tx)]
                temp3_visibility = False
            if ror is not None and len(ror) == len(tx):
                res["extratemp2"] = [ror]
            else:
                res["extratemp2"] = [[-1] * len(tx)]
                temp4_visibility = False
            res["extraname1"] = ["Exhaust"]
            res["extraname2"] = ["RoR"]
            res["extramathexpression1"] = [""]
            res["extramathexpression2"] = [""]
            res["extraLCDvisibility1"] = [temp3_visibility]
            res["extraLCDvisibility2"] = [temp4_visibility]
            res["extraCurveVisibility1"] = [temp3_visibility]
            res["extraCurveVisibility2"] = [temp4_visibility]
            res["extraDelta1"] = [False]
            res["extraDelta2"] = [True]
            res["extraFill1"] = [False]
            res["extraFill2"] = [False]
            res["extradevicecolor1"] = ['black']
            res["extradevicecolor2"] = ['black']
            res["extramarkersizes1"] = [6.0]
            res["extramarkersizes2"] = [6.0]
            res["extramarkers1"] = [None]
            res["extramarkers2"] = [None]
            res["extralinewidths1"] = [1.0]
            res["extralinewidths2"] = [1.0]
            res["extralinestyles1"] = ['-']
            res["extralinestyles2"] = ['-']
            res["extradrawstyles1"] = ['default']
            res["extradrawstyles2"] = ['default']

        return res
    except:
        #        import traceback
        #        import sys
        #        traceback.print_exc(file=sys.stdout)
        return {}
コード例 #31
0
def xmlToMetadataElementDict(xml):
    """słownik metadataElementDict na podstawie pliku XML"""
    metadataElementDict = {}

    ns = {'gco': "http://www.isotc211.org/2005/gco",
          'gmx': "http://www.isotc211.org/2005/gmx",
          'gmd': "http://www.isotc211.org/2005/gmd",
          'gml': "http://www.opengis.net/gml",
          'srv': "http://www.isotc211.org/2005/srv",
          'xlink': "http://www.w3.org/1999/xlink",
          'xs': "http://www.w3.org/2001/XMLSchema",
          'xsi': "http://www.w3.org/2001/XMLSchema-instance"
          }
    root = ET.parse(xml)

    # E1
    element = root.find('//gmd:MD_DataIdentification/*/gmd:CI_Citation/gmd:title/gco:CharacterString', ns)
    if element is not None:
        data = {'e1_lineEdit': element.text}
        metadataElementDict['e1'] = data

    # E2
    element = root.find('//gmd:MD_DataIdentification/gmd:abstract/gco:CharacterString', ns)
    if element is not None:
        data = {'e2_lineEdit': element.text}
        metadataElementDict['e2'] = data

    # E4
    itemsList = []
    for element in root.findall('//gmd:transferOptions//gmd:linkage/gmd:URL', ns):
        if element.text not in itemsList:
            itemsList.append({'e4_lineEdit': element.text})
    metadataElementDict['e4'] = itemsList

    # E5
    itemsList = []
    for element in root.findall('//gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:identifier//gco:CharacterString', ns):
        idIppUri = element.text
        idIpp = '/'.join(idIppUri.strip().strip('/').split('/')[-2:])
        if idIpp not in itemsList:
            itemsList.append({'e5_lineEdit': idIpp})
    metadataElementDict['e5'] = itemsList

    # E6
    itemsList = []
    for element in root.findall(
            '//gmd:MD_DataIdentification/gmd:language/gmd:LanguageCode', ns):
        if element.text not in itemsList and element.text in dictionaries.languages:
            itemsList.append({'e6_cmbbx': element.text})
    metadataElementDict['e6'] = itemsList

    # E7
    itemsList = []
    for element in root.findall(
            '/gmd:characterSet/gmd:MD_CharacterSetCode', ns):
        if element.attrib['codeListValue'] not in itemsList:
            itemsList.append({'e7_cmbbx': element.attrib['codeListValue']})
    metadataElementDict['e7'] = itemsList

    # E9 E10
    itemsList = []
    for descriptiveKeywords in root.findall(
            '//gmd:MD_DataIdentification/gmd:descriptiveKeywords', ns):
        data = {}

        keyword = descriptiveKeywords.find('.//gmd:keyword/gmx:Anchor', ns) # złożony KeyWord
        keywordSimple = descriptiveKeywords.find('.//gmd:keyword/gco:CharacterString', ns)   # prosty KeyWord
        if keyword is not None and keyword.text not in data:
            data['e9_lineEdit'] = keyword.text
        elif keywordSimple is not None and keywordSimple.text not in data:
            data['e9_lineEdit'] = keywordSimple.text

        thesaurus = descriptiveKeywords.find('.//gmd:thesaurusName', ns)
        if thesaurus is not None:
            thesaurus_title = thesaurus.find('.//gmd:title/gmx:Anchor', ns)
            if thesaurus_title is None:
                thesaurus_title = thesaurus.find('.//gmd:title/gco:CharacterString', ns)
            try:
                data['e10_lineEdit'] = thesaurus_title.text
            except AttributeError:
                pass
            try:
                data['xlink'] = thesaurus_title.attrib['{%s}href' % ns['xlink']]
            except KeyError:
                pass
            date = thesaurus.find('.//gco:Date', ns)
            data['e10_dateTimeEdit'] = QDateTime.fromString(date.text, "yyyy-MM-dd")
            dateTypeCode = thesaurus.find('.//gmd:CI_DateTypeCode', ns)
            data['e10_cmbbx'] = utils.getKeyByValue(translation, dateTypeCode.attrib['codeListValue'])

        itemsList.append(data)
    metadataElementDict['e9'] = itemsList

    # E11
    itemsList = []
    for extent in root.findall(
            '//gmd:extent', ns):
        xmin = extent.find('.//gmd:westBoundLongitude/gco:Decimal', ns)
        xmax = extent.find('.//gmd:eastBoundLongitude/gco:Decimal', ns)
        ymin = extent.find('.//gmd:southBoundLatitude/gco:Decimal', ns)
        ymax = extent.find('.//gmd:northBoundLatitude/gco:Decimal', ns)
        itemsList.append({'e11_lineEdit': "%s,%s,%s,%s" % (xmin.text, xmax.text, ymin.text, ymax.text)})
    metadataElementDict['e11'] = itemsList

    # E12
    itemsList = []
    for element in root.findall(
            '/gmd:referenceSystemInfo//gco:CharacterString', ns):
        if element.text not in itemsList:
            itemsList.append({'e12_cmbbx': element.text})
    metadataElementDict['e12'] = itemsList

    # E13 i E14
    for date in root.findall('//gmd:MD_DataIdentification/*/gmd:CI_Citation/gmd:date', ns):
        _date = date.find('.//gco:Date', ns)
        dateType = date.find('.//gmd:CI_DateTypeCode', ns)
        if dateType.attrib['codeListValue'] == "creation":  #E13
            metadataElementDict['e13'] = {'e13_dateTimeEdit': QDateTime.fromString(_date.text, "yyyy-MM-dd")}
        if dateType.attrib['codeListValue'] == "publication":  #E14
            metadataElementDict['e14'] = {'e14_dateTimeEdit': QDateTime.fromString(_date.text, "yyyy-MM-dd")}

    # E15
    element = root.find('/gmd:dataQualityInfo/*/gmd:lineage//gco:CharacterString', ns)
    if element is not None:
        data = {'e15_lineEdit': element.text}
        metadataElementDict['e15'] = data

    # E16
    itemsList = []
    for element in root.findall(
            '//gmd:MD_DataIdentification/gmd:spatialResolution//gmd:denominator/gco:Integer', ns):
        if element.text not in itemsList:
            itemsList.append({'e16_lineEdit': element.text})
    metadataElementDict['e16'] = itemsList

    # E18 i E19
    itemsList = []
    for report in root.findall(
            '/gmd:dataQualityInfo/gmd:DQ_DataQuality/gmd:report', ns):
        data = {}
        title = report.find('.//gmd:specification/gmd:CI_Citation/gmd:title/gco:CharacterString', ns)
        title_anchor = report.find('.//gmd:specification/gmd:CI_Citation/gmd:title/gmx:Anchor', ns)
        date = report.find('.//gmd:specification/gmd:CI_Citation/gmd:date//gco:Date', ns)
        dateType = report.find('.//gmd:specification/gmd:CI_Citation//gmd:dateType/gmd:CI_DateTypeCode', ns)
        exp_anchor = report.find('.//gmd:explanation/gmx:Anchor', ns)
        # _pass = report.find('.//gmd:pass/gco:Boolean', ns)
        if title is not None:
            data['e18_lineEdit'] = title.text
        elif title_anchor is not None:
            data['e18_lineEdit'] = title_anchor.text
            data['xlink'] = title_anchor.attrib['{%s}href' % ns['xlink']]
        else:
            data['e18_lineEdit'] = ""
        data['e18_dateTimeEdit'] = QDateTime.fromString(date.text, "yyyy-MM-dd")
        data['e18_cmbbx'] = utils.getKeyByValue(translation, dateType.attrib['codeListValue'])
        data['e19_cmbbx'] = utils.getKeyByValue(dictionaries.zgodnoscAnchors, exp_anchor.attrib['{%s}href' % ns['xlink']])
        itemsList.append(data)
    metadataElementDict['e18'] = itemsList

    # E20
    itemsList = []
    for element in root.findall(
            '//gmd:MD_DataIdentification/gmd:resourceConstraints//gmd:useConstraints/../gmd:otherConstraints/gmx:Anchor', ns):
        itemsList.append({'e20_lineEdit': element.text})
    metadataElementDict['e20'] = itemsList

    # E22 i E23
    itemsList = []
    for pointOfContact in root.findall(
            '//gmd:MD_DataIdentification/gmd:pointOfContact', ns):
        organisationName = pointOfContact.find('.//gmd:organisationName/gco:CharacterString', ns)
        mail = pointOfContact.find('.//gmd:contactInfo//gmd:electronicMailAddress/gco:CharacterString', ns)
        role = pointOfContact.find('.//gmd:CI_RoleCode', ns)
        itemsList.append({
            'e22_name_lineEdit': organisationName.text,
            'e22_mail_lineEdit': mail.text,
            'e23_cmbbx': utils.getKeyByValue(translation, role.attrib['codeListValue'])
        })
    metadataElementDict['e22'] = itemsList

    # E24/E25
    itemsList = []
    for distributionFormat in root.findall('//gmd:MD_Distribution/gmd:distributionFormat', ns):
        name = distributionFormat.find('.//gmd:name/gco:CharacterString', ns)
        version = distributionFormat.find('.//gmd:version/gco:CharacterString', ns)
        itemsList.append({
            'e24_lineEdit': name.text,
            'e25_lineEdit': version.text,
        })
    metadataElementDict['e24'] = itemsList

    # E27
    itemsList = []
    for element in root.findall(
            '//gmd:MD_DataIdentification/gmd:resourceMaintenance//gmd:maintenanceNote/gco:CharacterString',
            ns):
        itemsList.append({'e27_lineEdit': element.text})
    metadataElementDict['e27'] = itemsList

    # E29
    itemsList = []
    for contact in root.findall('/gmd:contact', ns):
        organisationName = contact.find('.//gmd:organisationName/gco:CharacterString', ns)
        mail = contact.find('.//gmd:contactInfo//gmd:electronicMailAddress/gco:CharacterString', ns)
        itemsList.append({
            'e29_name_lineEdit': organisationName.text,
            'e29_mail_lineEdit': mail.text,
            'e29_cmbbx': 'Punkt kontaktowy (pointOfContact)'
        })
    metadataElementDict['e29'] = itemsList

    # E32
    element = root.find('/gmd:fileIdentifier/gco:CharacterString', ns)
    if element is not None:
        metadataElementDict['e32'] = {'e32_lineEdit': element.text}


    return metadataElementDict
コード例 #32
0
ファイル: new_bet.py プロジェクト: carlossRA/betcon
    def initData(self):
        # dtDate
        sDate = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        date = QDateTime.fromString(sDate, "yyyy-MM-dd hh:mm:ss")
        self.dtDate.setDateTime(date)

        # cmbSport
        bd = Bbdd()
        data = bd.select("sport", "name")

        self.sportIndexToId = {}
        index = 0
        for i in data:
            id = i[0]
            name = i[1]
            self.cmbSport.addItem(name)
            self.sportIndexToId[index] = id
            index += 1

        # cmbBookie
        data = bd.select("bookie", "name")

        self.bookieIndexToId = {}
        index = 0
        for i in data:
            id = i[0]
            name = i[1]
            self.cmbBookie.addItem(name)
            self.bookieIndexToId[index] = id
            index += 1

        # cmbMarket
        data = bd.select("market", "name")

        self.marketIndexToId = {}
        index = 0
        for i in data:
            id = i[0]
            name = i[1]
            self.cmbMarket.addItem(name)
            self.marketIndexToId[index] = id
            index += 1

        # cmbTipster
        data = bd.select("tipster", "name")

        self.tipsterIndexToId = {}
        index = 0
        for i in data:
            id = i[0]
            name = i[1]
            self.cmbTipster.addItem(name)
            self.tipsterIndexToId[index] = id
            index += 1

        self.players = bd.executeQuery(
            "SELECT player1 as player FROM bet UNION SELECT player2 as player FROM bet ORDER BY player"
        )
        self.players = [row[0] for row in self.players]

        self.txtPlayer1.addItems(self.players)
        self.txtPlayer2.addItems(self.players)
        bd.close()

        # cmbCompetition
        self.setRegion()

        #Combined
        self.contComb = 0
        self.dates = []
        self.sports = []
        self.regions = []
        self.competitions = []
        self.players1 = []
        self.players2 = []
        self.picks = []
        self.results = []
        self.buttons = []

        self.regionIndexToIdCmb = []
        self.competitionIndexToIdCmb = []
        self.calcStake()
コード例 #33
0
ファイル: HelpDocsInstaller.py プロジェクト: testmana2/test
    def __installQtDoc(self, name, version, engine):
        """
        Private method to install/update a Qt help document.
        
        @param name name of the Qt help document (string)
        @param version Qt version of the help documens (integer)
        @param engine reference to the help engine (QHelpEngineCore)
        @return flag indicating success (boolean)
        """
        versionKey = "qt_version_{0}@@{1}".format(version, name)
        info = engine.customValue(versionKey, "")
        lst = info.split("|")

        dt = QDateTime()
        if len(lst) and lst[0]:
            dt = QDateTime.fromString(lst[0], Qt.ISODate)

        qchFile = ""
        if len(lst) == 2:
            qchFile = lst[1]

        if version == 4:
            docsPath = QDir(QLibraryInfo.location(QLibraryInfo.DocumentationPath) + QDir.separator() + "qch")
        elif version == 5:
            docsPath = QDir(QLibraryInfo.location(QLibraryInfo.DocumentationPath))
        else:
            # unsupported Qt version
            return False

        files = docsPath.entryList(["*.qch"])
        if not files:
            engine.setCustomValue(versionKey, QDateTime().toString(Qt.ISODate) + "|")
            return False

        for f in files:
            if f.startswith(name):
                fi = QFileInfo(docsPath.absolutePath() + QDir.separator() + f)
                namespace = QHelpEngineCore.namespaceName(fi.absoluteFilePath())
                if not namespace:
                    continue

                if (
                    dt.isValid()
                    and namespace in engine.registeredDocumentations()
                    and fi.lastModified().toString(Qt.ISODate) == dt.toString(Qt.ISODate)
                    and qchFile == fi.absoluteFilePath()
                ):
                    return False

                if namespace in engine.registeredDocumentations():
                    engine.unregisterDocumentation(namespace)

                if not engine.registerDocumentation(fi.absoluteFilePath()):
                    self.errorMessage.emit(
                        self.tr(
                            """<p>The file <b>{0}</b> could not be""" """ registered. <br/>Reason: {1}</p>"""
                        ).format(fi.absoluteFilePath, engine.error())
                    )
                    return False

                engine.setCustomValue(versionKey, fi.lastModified().toString(Qt.ISODate) + "|" + fi.absoluteFilePath())
                return True

        return False
コード例 #34
0
    def setupUi(self, MainWindow):

        self.scene = QGraphicsScene(self)
        item = QGraphicsPixmapItem()
        self.scene.addItem(item)

        self.conn = cx_Oracle.connect('TJOCR/[email protected]/orcl')
        # conn = cx_Oracle.connect('airport', 'jcfj2017', '10.92.172.110:1521/orcl')
        # self.conn= cx_Oracle.connect('airport/[email protected]:1521/orcl')
        # self.conn = cx_Oracle.connect('airport','jcfj2017','10.92.172.110:1521/orcl')
        self.cursor = self.conn.cursor()
        self.sqlstring = "select * from(select * from PSG_AJ_OCR order by NO desc)where rownum=1 AND"
        self.sqlstring1 = "select * from(select * from PSG_AJ_ZC order by ID desc)where rownum=1 AND"
        self.sqlstring2 = "select * from PSG_AJ_IDCARD_FACE where"
        self.sqlstring4 = "select * from PSG_AJ_OCR e,PSG_AJ_ZC d where rownum=1 AND"

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(856, 574)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setContentsMargins(0, 0, 0, 2)
        self.gridLayout.setObjectName("gridLayout")
        self.tabWidget = QtWidgets.QTabWidget(self.centralwidget)
        self.tabWidget.setObjectName("tabWidget")
        self.tab = QtWidgets.QWidget()
        self.tab.setObjectName("tab")
        stylesheet = """ 
                         QTabBar::tab:selected {background: gray;}
                         QTabWidget>QWidget>QWidget{background: gray;}
                        """
        self.setStyleSheet(stylesheet)
        self.gridLayout_3 = QtWidgets.QGridLayout(self.tab)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.groupBox = QtWidgets.QGroupBox(self.tab)
        self.groupBox.setTitle("")
        self.groupBox.setObjectName("groupBox")
        self.gridLayout_4 = QtWidgets.QGridLayout(self.groupBox)
        self.gridLayout_4.setObjectName("gridLayout_4")
        self.lineEdit_4 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_4.setObjectName("lineEdit_4")
        self.gridLayout_4.addWidget(self.lineEdit_4, 4, 1, 1, 1)
        self.label_14 = QtWidgets.QLabel(self.groupBox)
        self.label_14.setObjectName("label_14")
        self.gridLayout_4.addWidget(self.label_14, 4, 2, 1, 2)
        self.label_5 = QtWidgets.QLabel(self.groupBox)
        self.label_5.setObjectName("label_5")
        self.gridLayout_4.addWidget(self.label_5, 5, 0, 1, 1)
        self.lineEdit_5 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_5.setObjectName("lineEdit_5")
        self.gridLayout_4.addWidget(self.lineEdit_5, 5, 1, 1, 1)
        self.label_15 = QtWidgets.QLabel(self.groupBox)
        self.label_15.setObjectName("label_15")
        self.gridLayout_4.addWidget(self.label_15, 5, 3, 1, 1)
        self.lineEdit_14 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_14.setObjectName("lineEdit_14")
        self.gridLayout_4.addWidget(self.lineEdit_14, 4, 4, 1, 2)
        self.lineEdit_15 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_15.setObjectName("lineEdit_15")
        self.gridLayout_4.addWidget(self.lineEdit_15, 5, 4, 1, 2)
        self.label_4 = QtWidgets.QLabel(self.groupBox)
        self.label_4.setObjectName("label_4")
        self.gridLayout_4.addWidget(self.label_4, 4, 0, 1, 1)
        self.lineEdit_3 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_3.setObjectName("lineEdit_3")
        self.gridLayout_4.addWidget(self.lineEdit_3, 3, 1, 1, 1)
        self.lineEdit_12 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_12.setObjectName("lineEdit_12")
        self.gridLayout_4.addWidget(self.lineEdit_12, 2, 4, 1, 2)
        self.label_3 = QtWidgets.QLabel(self.groupBox)
        self.label_3.setObjectName("label_3")
        self.gridLayout_4.addWidget(self.label_3, 3, 0, 1, 1)
        self.label_13 = QtWidgets.QLabel(self.groupBox)
        self.label_13.setObjectName("label_13")
        self.gridLayout_4.addWidget(self.label_13, 3, 3, 1, 1)
        self.lineEdit_13 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_13.setObjectName("lineEdit_13")
        self.gridLayout_4.addWidget(self.lineEdit_13, 3, 4, 1, 2)
        self.label_12 = QtWidgets.QLabel(self.groupBox)
        self.label_12.setObjectName("label_12")
        self.gridLayout_4.addWidget(self.label_12, 2, 3, 1, 1)
        self.lineEdit_16 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_16.setObjectName("lineEdit_16")
        self.gridLayout_4.addWidget(self.lineEdit_16, 6, 4, 1, 2)
        self.lineEdit_7 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_7.setObjectName("lineEdit_7")
        self.gridLayout_4.addWidget(self.lineEdit_7, 7, 1, 1, 1)
        self.label_7 = QtWidgets.QLabel(self.groupBox)
        self.label_7.setObjectName("label_7")
        self.gridLayout_4.addWidget(self.label_7, 7, 0, 1, 1)
        self.label_16 = QtWidgets.QLabel(self.groupBox)
        self.label_16.setObjectName("label_16")
        self.gridLayout_4.addWidget(self.label_16, 6, 2, 1, 2)
        self.label_6 = QtWidgets.QLabel(self.groupBox)
        self.label_6.setObjectName("label_6")
        self.gridLayout_4.addWidget(self.label_6, 6, 0, 1, 1)
        self.lineEdit_6 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_6.setObjectName("lineEdit_6")
        self.gridLayout_4.addWidget(self.lineEdit_6, 6, 1, 1, 1)
        self.label_17 = QtWidgets.QLabel(self.groupBox)
        self.label_17.setObjectName("label_17")
        self.gridLayout_4.addWidget(self.label_17, 7, 3, 1, 1)
        self.lineEdit_17 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_17.setObjectName("lineEdit_17")
        self.gridLayout_4.addWidget(self.lineEdit_17, 7, 4, 1, 2)
        self.label_8 = QtWidgets.QLabel(self.groupBox)
        self.label_8.setObjectName("label_8")
        self.gridLayout_4.addWidget(self.label_8, 8, 0, 1, 1)
        self.lineEdit_8 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_8.setObjectName("lineEdit_8")
        self.gridLayout_4.addWidget(self.lineEdit_8, 8, 1, 1, 1)
        self.label_18 = QtWidgets.QLabel(self.groupBox)
        self.label_18.setObjectName("label_18")
        self.gridLayout_4.addWidget(self.label_18, 8, 2, 1, 2)
        self.lineEdit_18 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_18.setObjectName("lineEdit_18")
        self.gridLayout_4.addWidget(self.lineEdit_18, 8, 4, 1, 2)
        self.lineEdit_2 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.gridLayout_4.addWidget(self.lineEdit_2, 2, 1, 1, 1)
        self.label = QtWidgets.QLabel(self.groupBox)
        self.label.setObjectName("label")
        self.gridLayout_4.addWidget(self.label, 0, 0, 1, 1)
        self.lineEdit_11 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_11.setObjectName("lineEdit_11")
        self.gridLayout_4.addWidget(self.lineEdit_11, 0, 5, 1, 1)
        self.lineEdit = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit.setObjectName("lineEdit")
        self.gridLayout_4.addWidget(self.lineEdit, 0, 1, 1, 2)
        self.label_2 = QtWidgets.QLabel(self.groupBox)
        self.label_2.setObjectName("label_2")
        self.gridLayout_4.addWidget(self.label_2, 2, 0, 1, 1)
        self.label_9 = QtWidgets.QLabel(self.groupBox)
        self.label_9.setObjectName("label_9")
        self.gridLayout_4.addWidget(self.label_9, 9, 0, 1, 1)
        self.lineEdit_9 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_9.setObjectName("lineEdit_9")
        self.gridLayout_4.addWidget(self.lineEdit_9, 9, 1, 1, 1)
        self.label_19 = QtWidgets.QLabel(self.groupBox)
        self.label_19.setObjectName("label_19")
        self.gridLayout_4.addWidget(self.label_19, 9, 2, 1, 2)
        self.lineEdit_19 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_19.setObjectName("lineEdit_19")
        self.gridLayout_4.addWidget(self.lineEdit_19, 9, 4, 1, 2)
        self.lineEdit_10 = QtWidgets.QLineEdit(self.groupBox)
        self.lineEdit_10.setObjectName("lineEdit_10")
        self.gridLayout_4.addWidget(self.lineEdit_10, 10, 1, 1, 1)
        self.label_10 = QtWidgets.QLabel(self.groupBox)
        self.label_10.setObjectName("label_10")
        self.gridLayout_4.addWidget(self.label_10, 10, 0, 1, 1)
        self.label_11 = QtWidgets.QLabel(self.groupBox)
        self.label_11.setObjectName("label_11")
        self.gridLayout_4.addWidget(self.label_11, 0, 3, 1, 1)
        self.gridLayout_3.addWidget(self.groupBox, 0, 0, 1, 1)
        self.groupBox_2 = QtWidgets.QGroupBox(self.tab)
        self.groupBox_2.setTitle("")
        self.groupBox_2.setObjectName("groupBox_2")
        self.verticalLayout = QtWidgets.QVBoxLayout(self.groupBox_2)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label_21 = QtWidgets.QLabel(self.groupBox_2)
        self.label_21.setObjectName("label_21")
        self.verticalLayout.addWidget(self.label_21)
        self.graphicsView = QtWidgets.QGraphicsView(self.groupBox_2)
        self.graphicsView.setObjectName("graphicsView")
        self.verticalLayout.addWidget(self.graphicsView)
        self.label_22 = QtWidgets.QLabel(self.groupBox_2)
        self.label_22.setObjectName("label_22")
        self.verticalLayout.addWidget(self.label_22)
        self.graphicsView_2 = QtWidgets.QGraphicsView(self.groupBox_2)
        self.graphicsView_2.setObjectName("graphicsView_2")
        self.verticalLayout.addWidget(self.graphicsView_2)
        self.gridLayout_3.addWidget(self.groupBox_2, 0, 1, 1, 1)
        self.gridLayout_3.setColumnStretch(0, 3)
        self.gridLayout_3.setColumnStretch(1, 1)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QtWidgets.QWidget()
        self.tab_2.setObjectName("tab_2")
        stylesheet = """ 
                         QTabBar::tab:selected {background: gray;}
                         QTabWidget>QWidget>QWidget{background: gray;}
                        """
        self.tab_2.setStyleSheet(stylesheet)
        self.gridLayout_7 = QtWidgets.QGridLayout(self.tab_2)
        self.gridLayout_7.setObjectName("gridLayout_7")
        self.groupBox_5 = QtWidgets.QGroupBox(self.tab_2)
        self.groupBox_5.setTitle("")
        self.groupBox_5.setObjectName("groupBox_5")
        self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.groupBox_5)
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label_20 = QtWidgets.QLabel(self.groupBox_5)
        self.label_20.setObjectName("label_20")
        self.verticalLayout_2.addWidget(self.label_20)
        self.graphicsView_3 = QtWidgets.QGraphicsView(self.groupBox_5)
        self.graphicsView_3.setObjectName("graphicsView_3")
        self.verticalLayout_2.addWidget(self.graphicsView_3)
        self.gridLayout_7.addWidget(self.groupBox_5, 0, 2, 1, 1)
        self.groupBox_6 = QtWidgets.QGroupBox(self.tab_2)
        self.groupBox_6.setObjectName("groupBox_6")
        self.gridLayout_6 = QtWidgets.QGridLayout(self.groupBox_6)
        self.gridLayout_6.setObjectName("gridLayout_6")
        self.checkBox_5 = QtWidgets.QCheckBox(self.groupBox_6)
        self.checkBox_5.setObjectName("checkBox_5")
        self.gridLayout_6.addWidget(self.checkBox_5, 2, 0, 1, 1)
        self.label_25 = QtWidgets.QLabel(self.groupBox_6)
        self.label_25.setObjectName("label_25")
        self.gridLayout_6.addWidget(self.label_25, 3, 0, 1, 1)
        self.lineEdit_22 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_22.setObjectName("lineEdit_22")
        self.gridLayout_6.addWidget(self.lineEdit_22, 0, 1, 1, 2)
        self.lineEdit_24 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_24.setObjectName("lineEdit_24")
        self.gridLayout_6.addWidget(self.lineEdit_24, 2, 1, 1, 2)
        self.lineEdit_25 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_25.setObjectName("lineEdit_25")
        self.gridLayout_6.addWidget(self.lineEdit_25, 3, 1, 1, 2)
        self.lineEdit_23 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_23.setObjectName("lineEdit_23")
        self.gridLayout_6.addWidget(self.lineEdit_23, 1, 1, 1, 2)
        self.checkBox_3 = QtWidgets.QCheckBox(self.groupBox_6)
        self.checkBox_3.setObjectName("checkBox_3")
        self.gridLayout_6.addWidget(self.checkBox_3, 0, 0, 1, 1)
        self.checkBox_4 = QtWidgets.QCheckBox(self.groupBox_6)
        self.checkBox_4.setObjectName("checkBox_4")
        self.gridLayout_6.addWidget(self.checkBox_4, 1, 0, 1, 1)
        self.lineEdit_30 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_30.setObjectName("lineEdit_30")
        self.gridLayout_6.addWidget(self.lineEdit_30, 8, 2, 1, 1)
        self.label_27 = QtWidgets.QLabel(self.groupBox_6)
        self.label_27.setObjectName("label_27")
        self.gridLayout_6.addWidget(self.label_27, 6, 0, 1, 1)
        self.lineEdit_28 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_28.setObjectName("lineEdit_28")
        self.gridLayout_6.addWidget(self.lineEdit_28, 6, 1, 1, 2)
        self.checkBox_6 = QtWidgets.QCheckBox(self.groupBox_6)
        self.checkBox_6.setObjectName("checkBox_6")
        self.gridLayout_6.addWidget(self.checkBox_6, 4, 0, 1, 1)
        self.lineEdit_26 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_26.setObjectName("lineEdit_26")
        self.gridLayout_6.addWidget(self.lineEdit_26, 4, 1, 1, 2)
        self.lineEdit_29 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_29.setObjectName("lineEdit_29")
        self.gridLayout_6.addWidget(self.lineEdit_29, 7, 2, 1, 1)
        self.label_29 = QtWidgets.QLabel(self.groupBox_6)
        self.label_29.setObjectName("label_29")
        self.gridLayout_6.addWidget(self.label_29, 8, 0, 1, 1)
        self.label_26 = QtWidgets.QLabel(self.groupBox_6)
        self.label_26.setObjectName("label_26")
        self.gridLayout_6.addWidget(self.label_26, 5, 0, 1, 1)
        self.lineEdit_27 = QtWidgets.QLineEdit(self.groupBox_6)
        self.lineEdit_27.setObjectName("lineEdit_27")
        self.gridLayout_6.addWidget(self.lineEdit_27, 5, 1, 1, 2)
        self.label_28 = QtWidgets.QLabel(self.groupBox_6)
        self.label_28.setObjectName("label_28")
        self.gridLayout_6.addWidget(self.label_28, 7, 0, 1, 1)
        self.gridLayout_7.addWidget(self.groupBox_6, 0, 0, 3, 1)
        self.groupBox_4 = QtWidgets.QGroupBox(self.tab_2)
        self.groupBox_4.setTitle("")
        self.groupBox_4.setObjectName("groupBox_4")
        self.gridLayout_5 = QtWidgets.QGridLayout(self.groupBox_4)
        self.gridLayout_5.setObjectName("gridLayout_5")
        self.label_23 = QtWidgets.QLabel(self.groupBox_4)
        self.label_23.setObjectName("label_23")
        self.gridLayout_5.addWidget(self.label_23, 0, 0, 1, 1)
        self.checkBox = QtWidgets.QCheckBox(self.groupBox_4)
        self.checkBox.setObjectName("checkBox")
        self.gridLayout_5.addWidget(self.checkBox, 1, 0, 1, 1)
        self.lineEdit_21 = QtWidgets.QLineEdit(self.groupBox_4)
        self.lineEdit_21.setObjectName("lineEdit_21")
        self.gridLayout_5.addWidget(self.lineEdit_21, 4, 1, 1, 1)
        self.checkBox_2 = QtWidgets.QCheckBox(self.groupBox_4)
        self.checkBox_2.setObjectName("checkBox_2")
        self.gridLayout_5.addWidget(self.checkBox_2, 4, 0, 1, 1)
        self.dateTimeEdit_2 = QtWidgets.QDateTimeEdit(self.groupBox_4)
        self.dateTimeEdit_2.setObjectName("dateTimeEdit_2")
        self.now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.dateTimeEdit_2.setDateTime(
            QDateTime.fromString(self.now_time, 'yyyy-MM-dd hh:mm:ss'))
        self.gridLayout_5.addWidget(self.dateTimeEdit_2, 3, 1, 1, 1)
        self.dateTimeEdit = QtWidgets.QDateTimeEdit(self.groupBox_4)
        self.dateTimeEdit.setObjectName("dateTimeEdit")
        self.now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        self.dateTimeEdit.setDateTime(
            QDateTime.fromString(self.now_time, 'yyyy-MM-dd hh:mm:ss'))
        self.gridLayout_5.addWidget(self.dateTimeEdit, 1, 1, 1, 1)
        self.gridLayout_7.addWidget(self.groupBox_4, 1, 2, 1, 1)
        self.groupBox_3 = QtWidgets.QGroupBox(self.tab_2)
        self.groupBox_3.setTitle("")
        self.groupBox_3.setObjectName("groupBox_3")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox_3)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.pushButton_6 = QtWidgets.QPushButton(self.groupBox_3)
        self.pushButton_6.setObjectName("pushButton_6")
        self.gridLayout_2.addWidget(self.pushButton_6, 5, 2, 1, 1)
        self.pushButton = QtWidgets.QPushButton(self.groupBox_3)
        self.pushButton.setObjectName("pushButton")
        self.gridLayout_2.addWidget(self.pushButton, 1, 0, 1, 1)
        self.pushButton_5 = QtWidgets.QPushButton(self.groupBox_3)
        self.pushButton_5.setObjectName("pushButton_5")
        self.gridLayout_2.addWidget(self.pushButton_5, 5, 0, 1, 1)
        self.label_24 = QtWidgets.QLabel(self.groupBox_3)
        self.label_24.setObjectName("label_24")
        self.gridLayout_2.addWidget(self.label_24, 0, 0, 1, 1)
        self.pushButton_3 = QtWidgets.QPushButton(self.groupBox_3)
        self.pushButton_3.setObjectName("pushButton_3")
        self.gridLayout_2.addWidget(self.pushButton_3, 2, 0, 1, 1)
        self.pushButton_4 = QtWidgets.QPushButton(self.groupBox_3)
        self.pushButton_4.setObjectName("pushButton_4")
        self.gridLayout_2.addWidget(self.pushButton_4, 2, 2, 1, 1)
        self.pushButton_2 = QtWidgets.QPushButton(self.groupBox_3)
        self.pushButton_2.setObjectName("pushButton_2")
        self.gridLayout_2.addWidget(self.pushButton_2, 1, 2, 1, 1)
        self.gridLayout_7.addWidget(self.groupBox_3, 2, 2, 1, 1)
        self.groupBox_7 = QtWidgets.QGroupBox(self.tab_2)
        self.groupBox_7.setObjectName("groupBox_7")
        self.gridLayout_8 = QtWidgets.QGridLayout(self.groupBox_7)
        self.gridLayout_8.setObjectName("gridLayout_8")
        self.checkBox_7 = QtWidgets.QCheckBox(self.groupBox_7)
        self.checkBox_7.setObjectName("checkBox_7")
        self.gridLayout_8.addWidget(self.checkBox_7, 0, 0, 1, 1)
        self.lineEdit_31 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_31.setObjectName("lineEdit_31")
        self.gridLayout_8.addWidget(self.lineEdit_31, 0, 1, 1, 1)
        self.checkBox_8 = QtWidgets.QCheckBox(self.groupBox_7)
        self.checkBox_8.setObjectName("checkBox_8")
        self.gridLayout_8.addWidget(self.checkBox_8, 1, 0, 1, 1)
        self.lineEdit_32 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_32.setObjectName("lineEdit_32")
        self.gridLayout_8.addWidget(self.lineEdit_32, 1, 1, 1, 1)
        self.checkBox_9 = QtWidgets.QCheckBox(self.groupBox_7)
        self.checkBox_9.setObjectName("checkBox_9")
        self.gridLayout_8.addWidget(self.checkBox_9, 2, 0, 1, 1)
        self.lineEdit_33 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_33.setObjectName("lineEdit_33")
        self.gridLayout_8.addWidget(self.lineEdit_33, 2, 1, 1, 1)
        self.checkBox_10 = QtWidgets.QCheckBox(self.groupBox_7)
        self.checkBox_10.setObjectName("checkBox_10")
        self.gridLayout_8.addWidget(self.checkBox_10, 3, 0, 1, 1)
        self.lineEdit_34 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_34.setObjectName("lineEdit_34")
        self.gridLayout_8.addWidget(self.lineEdit_34, 3, 1, 1, 1)
        self.label_30 = QtWidgets.QLabel(self.groupBox_7)
        self.label_30.setObjectName("label_30")
        self.gridLayout_8.addWidget(self.label_30, 4, 0, 1, 1)
        self.lineEdit_35 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_35.setObjectName("lineEdit_35")
        self.gridLayout_8.addWidget(self.lineEdit_35, 4, 1, 1, 1)
        self.label_31 = QtWidgets.QLabel(self.groupBox_7)
        self.label_31.setObjectName("label_31")
        self.gridLayout_8.addWidget(self.label_31, 5, 0, 1, 1)
        self.lineEdit_36 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_36.setObjectName("lineEdit_36")
        self.gridLayout_8.addWidget(self.lineEdit_36, 5, 1, 1, 1)
        self.label_32 = QtWidgets.QLabel(self.groupBox_7)
        self.label_32.setObjectName("label_32")
        self.gridLayout_8.addWidget(self.label_32, 6, 0, 1, 1)
        self.lineEdit_37 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_37.setObjectName("lineEdit_37")
        self.gridLayout_8.addWidget(self.lineEdit_37, 6, 1, 1, 1)
        self.label_33 = QtWidgets.QLabel(self.groupBox_7)
        self.label_33.setObjectName("label_33")
        self.gridLayout_8.addWidget(self.label_33, 7, 0, 1, 1)
        self.lineEdit_38 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_38.setObjectName("lineEdit_38")
        self.gridLayout_8.addWidget(self.lineEdit_38, 7, 1, 1, 1)
        self.label_34 = QtWidgets.QLabel(self.groupBox_7)
        self.label_34.setObjectName("label_34")
        self.gridLayout_8.addWidget(self.label_34, 8, 0, 1, 1)
        self.lineEdit_39 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_39.setObjectName("lineEdit_39")
        self.gridLayout_8.addWidget(self.lineEdit_39, 8, 1, 1, 1)
        self.label_35 = QtWidgets.QLabel(self.groupBox_7)
        self.label_35.setObjectName("label_35")
        self.gridLayout_8.addWidget(self.label_35, 9, 0, 1, 1)
        self.lineEdit_40 = QtWidgets.QLineEdit(self.groupBox_7)
        self.lineEdit_40.setObjectName("lineEdit_40")
        self.gridLayout_8.addWidget(self.lineEdit_40, 9, 1, 1, 1)
        self.gridLayout_7.addWidget(self.groupBox_7, 0, 1, 3, 1)
        self.gridLayout_7.setColumnStretch(0, 2)
        self.gridLayout_7.setColumnStretch(1, 2)
        self.gridLayout_7.setColumnStretch(2, 1)
        self.gridLayout_7.setRowStretch(0, 3)
        self.gridLayout_7.setRowStretch(1, 2)
        self.gridLayout_7.setRowStretch(2, 2)
        self.tabWidget.addTab(self.tab_2, "")
        self.tab_3 = QtWidgets.QWidget()
        self.tab_3.setObjectName("tab_3")
        stylesheet = """ 
                         QTabBar::tab:selected {background: gray;}
                         QTabWidget>QWidget>QWidget{background: gray;}
                        """
        self.tab_3.setStyleSheet(stylesheet)
        self.tabWidget.addTab(self.tab_3, "")
        self.gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 856, 23))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        self.tabWidget.setCurrentIndex(1)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
コード例 #35
0
ファイル: myWidget.py プロジェクト: likeke201/qt_code
 def on_btnSetDateTime_clicked(self):  ##“设置日期时间”按钮
     dttmStr = self.ui.editDateTime.text()
     dttm = QDateTime.fromString(dttmStr, "yyyy-MM-dd hh:mm:ss")
     self.ui.dateTimeEdit.setDateTime(dttm)
コード例 #36
0
def string2QDateTime(date_time_str):
    return QDateTime.fromString(date_time_str, "yyyy-MM-dd hh:mm")
コード例 #37
0
ファイル: setmain.py プロジェクト: Arg0s1080/pycket
    def set_config(self):
        if exists(MAIN_CFG):
            self.config.read(MAIN_CFG)

            # Section: Geometry
            set_geometry(self.config, self.setGeometry)

            # Section: General
            self.setWindowFlag(Qt.WindowStaysOnTopHint,
                               self.config.getboolean("General", "on_top"))
            self.setStyle(
                QtWidgets.QApplication.setStyle(
                    self.config.get("General", "qstyle")))
            self.ui.dateTimeEditAtTime.setDisplayFormat(
                self.config.get("General", "date_time_format"))
            scale = self.config.get("General", "temp_scale")
            self.temp_scale = scale.lower()
            self.temp_symbol = "%s%s" % (u"\u00B0", scale[0])
            self.ui.progressBar.setTextVisible(
                self.config.getboolean("General", "progressbar_text"))

            # Section: Main
            self.action = Action[self.config.get("Main", "actions")]
            if self.action == Action.Shutdown:
                self.ui.radioButtonShutdown.setChecked(True)
            elif self.action == Action.Reboot:
                self.ui.radioButtonReboot.setChecked(True)
            elif self.action == Action.CloseSession:
                self.ui.radioButtonCloseSesion.setChecked(True)
            elif self.action == Action.Lock:
                self.ui.radioButtonLock.setChecked(True)
            elif self.action == Action.Suspend:
                self.ui.radioButtonSuspend.setChecked(True)
            elif self.action == Action.Hibernate:
                self.ui.radioButtonHibernate.setChecked(True)
            elif self.action == Action.Notify:
                self.ui.radioButtonNotify.setChecked(True)
            elif self.action == Action.Execute:
                self.ui.radioButtonExecute.setChecked(True)
            else:
                self.ui.radioButtonSendMail.setChecked(True)

            self.condition = Condition[self.config.get("Main", "conditions")]
            if self.condition == Condition.AtTime:
                self.ui.tabWidget.setCurrentIndex(0)
            elif self.condition == Condition.Countdown:
                self.ui.tabWidget.setCurrentIndex(1)
            elif self.condition == Condition.SystemLoad:
                self.ui.tabWidget.setCurrentIndex(2)
            elif self.condition == Condition.Network:
                self.ui.tabWidget.setCurrentIndex(3)
            elif self.condition == Condition.Power:
                self.ui.tabWidget.setCurrentIndex(4)
            elif self.condition == Condition.Partitions:
                self.ui.tabWidget.setCurrentIndex(5)

            # Section: AtTime
            d = QDateTime.fromString(self.config.get("AtTime", "date_time"),
                                     "yyyy/MM/dd hh:mm:ss")
            self.ui.dateTimeEditAtTime.setDateTime(d)

            # Section: CountDown
            self.ui.spinBoxCountdownHours.setValue(
                self.config.getint("CountDown", "hours"))
            self.ui.spinBoxCountdownMinutes.setValue(
                self.config.getint("CountDown", "minutes"))
            self.ui.spinBoxCountdownSeconds.setValue(
                self.config.getint("CountDown", "seconds"))

            # Section SystemLoad
            sli = int(self.config.get("SystemLoad", "group_index"))
            if sli == 0:
                self.ui.radioButtonSystemLoadRAMUsed.setChecked(True)
            elif sli == 1:
                self.ui.radioButtonSystemLoadCPUFrequency.setChecked(True)
            elif sli == 2:
                self.ui.radioButtonSystemLoadCPU.setChecked(True)
            else:
                self.ui.radioButtonSystemLoadCPUTemp.setChecked(True)
            self.ui.comboBoxSystemLoad.setCurrentIndex(
                self.config.getboolean("SystemLoad", "combo"))
            self.ui.spinBoxSystemLoadMinutes.setValue(
                self.config.getint("SystemLoad", "spin_min"))
            self.ui.spinBoxSystemLoadUnit.setValue(
                self.config.getint("SystemLoad", "spin_unit"))
            self.ui.checkBoxSystemLoadFor.setChecked(
                self.config.getboolean("SystemLoad", "check_for"))
            self.button_group_sl_clicked()

            # Section Network
            if self.config.getboolean("Network", "group_index"):
                self.ui.radioButtonNetworkUploadDownloadSpeed.setChecked(True)
            else:
                self.ui.radioButtonNetworkIsUpDownloading.setChecked(True)
            self.ui.comboBoxNetworkInterface.setCurrentIndex(
                self.config.getint("Network", "combo_interface"))
            self.ui.comboBoxNetworkSpeed.setCurrentIndex(
                self.config.getboolean("Network", "combo_speed"))
            self.ui.comboBoxNetworkMoreLess.setCurrentIndex(
                self.config.getboolean("Network", "combo_more_less"))
            self.ui.comboBoxNetworkUnitSpeed.setCurrentIndex(
                self.config.getint("Network", "combo_unit_speed"))
            self.ui.comboBoxNetworkFinished.setCurrentIndex(
                self.config.getboolean("Network", "combo_finished"))
            self.ui.comboBoxNetworkUnit.setCurrentIndex(
                self.config.getint("Network", "combo_unit"))
            self.ui.checkBoxNetworkFor.setChecked(
                self.config.getboolean("Network", "check_for"))
            self.ui.spinBoxNetworkUnitSpeed.setValue(
                self.config.getint("Network", "spin_unit_speed"))
            self.ui.spinBoxNetworkMinutes.setValue(
                self.config.getint("Network", "spin_minutes"))
            self.ui.spinBoxNetworkUnit.setValue(
                self.config.getint("Network", "spin_unit"))

            # Section Power
            self.ui.radioButtonPowerTheBatteryHas.setChecked(
                self.config.getboolean("Power", "group_index_1"))
            self.ui.radioButtonPowerBatteryPercent.setChecked(
                self.config.getboolean("Power", "group_index_2"))
            self.ui.comboBoxPowerMoreLess.setCurrentIndex(
                self.config.getboolean("Power", "combo_more_less"))
            self.ui.comboBoxPowerACDC.setCurrentIndex(
                self.config.getboolean("Power", "combo_acdc"))
            self.ui.spinBoxPowerMinutes.setValue(
                self.config.getint("Power", "spin_minutes"))
            self.ui.spinBoxPowerPercent.setValue(
                self.config.getint("Power", "spin_percent"))
            self.ui.checkBoxPowerFor.setChecked(
                self.config.getboolean("Power", "check_for"))
            self.ui.timeEditPower.setDateTime(
                QDateTime.fromString(self.config.get("Power", "time_edit"),
                                     "h:mm"))

            # Section Partitions
            self.ui.radioButtonPttIOPS.setChecked(
                self.config.getboolean("Partitions", "group_index"))
            self.ui.comboBoxPttPartitions.setCurrentText(
                self.config.get("Partitions", "combo_partitions"))
            self.ui.comboBoxPttSpace.setCurrentIndex(
                self.config.getint("Partitions", "combo_space"))
            self.ui.comboBoxPttSpaceLessMore.setCurrentIndex(
                self.config.getboolean("Partitions", "combo_spc_less_more"))
            self.ui.comboBoxPttSpaceUnit.setCurrentIndex(
                self.config.getint("Partitions", "combo_spc_unit"))
            self.ui.comboBoxPttIOPS.setCurrentIndex(
                self.config.getboolean("Partitions", "combo_iops"))
            self.ui.comboBoxPttIOPSLessMore.setCurrentIndex(
                self.config.getboolean("Partitions", "combo_iops_less_more"))
            self.ui.comboBoxPttIOPSUnit.setCurrentIndex(
                self.config.getint("Partitions", "combo_iops_unit"))
            self.ui.spinBoxPttSpace.setValue(
                self.config.getint("Partitions", "spin_space_unit"))
            self.ui.spinBoxPttIOPS.setValue(
                self.config.getint("Partitions", "spin_iops_unit"))
            self.ui.spinBoxPttMinutes.setValue(
                self.config.getint("Partitions", "spin_minutes"))
            self.ui.checkBoxPttFor.setChecked(
                self.config.getboolean("Partitions", "check_for"))

        else:
            make_cfg_folder(MAIN_CFG)
            make_geometry(self.config, 657, 424)
            make_geometry(self.config, 350, 430, "Geometry_Settings")
            self.config.add_section("General")
            self.config.set("General", "qstyle", QStyleFactory.keys()[0])
            self.config.set("General", "temp_scale", "Celsius")
            self.config.set("General", "date_time_format",
                            self.tr("MM/dd/yyyy - hh:mm:ss"))
            self.config.set("General", "progressbar_text", "False")
            self.config.set("General", "on_top", "False")
            self.config.add_section("Main")
            self.config.set("Main", "actions", "Shutdown")
            self.config.set("Main", "conditions", "AtTime")
            self.config.add_section("AtTime")
            self.config.set(
                "AtTime", "date_time",
                QDateTime.currentDateTime().addSecs(3600).toString(
                    "yyyy/MM/dd hh:mm:ss"))
            self.config.add_section("CountDown")
            self.config.set("CountDown", "hours", "0")
            self.config.set("CountDown", "minutes", "0")
            self.config.set("CountDown", "seconds", "0")
            self.config.add_section("SystemLoad")
            self.config.set("SystemLoad", "group_index", "0")
            self.config.set("SystemLoad", "combo", "False")
            self.config.set("SystemLoad", "spin_min", "0")
            self.config.set("SystemLoad", "spin_unit", "0")
            self.config.set("SystemLoad", "check_for", "False")
            self.config.add_section("Network")
            self.config.set("Network", "group_index", "False")
            self.config.set("Network", "combo_interface", "0")
            self.config.set("Network", "combo_speed", "False")
            self.config.set("Network", "combo_more_less", "False")
            self.config.set("Network", "combo_unit_speed", "0")
            self.config.set("Network", "combo_finished", "False")
            self.config.set("Network", "combo_unit", "0")
            self.config.set("Network", "spin_unit_speed", "0")
            self.config.set("Network", "spin_minutes", "0")
            self.config.set("Network", "spin_unit", "0")
            self.config.set("Network", "check_for", "False")
            self.config.add_section("Power")
            self.config.set("Power", "group_index_1", "False")
            self.config.set("Power", "group_index_2", "False")
            self.config.set("Power", "combo_acdc", "False")
            self.config.set("Power", "combo_more_less", "False")
            self.config.set("Power", "spin_minutes", "0")
            self.config.set("Power", "spin_percent", "0")
            self.config.set("Power", "check_for", "False")
            self.config.set("Power", "time_edit", "0:00")
            self.config.add_section("Partitions")
            self.config.set("Partitions", "group_index", "False")
            self.config.set("Partitions", "combo_partitions",
                            list(mounted_partitions().keys())[0])
            self.config.set("Partitions", "combo_space", "0")
            self.config.set("Partitions", "combo_spc_less_more", "False")
            self.config.set("Partitions", "combo_spc_unit", "0")
            self.config.set("Partitions", "combo_iops", "False")
            self.config.set("Partitions", "combo_iops_less_more", "False")
            self.config.set("Partitions", "combo_iops_unit", "0")
            self.config.set("Partitions", "spin_space_unit", "0")
            self.config.set("Partitions", "spin_iops_unit", "0")
            self.config.set("Partitions", "spin_minutes", "0")
            self.config.set("Partitions", "check_for", "False")
            self.config.add_section("Commands")
            # Note: There is the possibility to import statux.system values as commands typing the method name
            # between number signs (E.g: echo Linux #kernel_version# #architecture# -> "Linux 4.15.0 x86_64")
            self.config.set("Commands", "shutdown", "systemctl poweroff")
            self.config.set("Commands", "reboot", "systemctl reboot")
            self.config.set(
                "Commands", "close_session",
                "%s %s" % ("loginctl terminate-session", "#session_id#"))
            self.config.set(
                "Commands", "lock_screen",
                "%s %s" % ("loginctl lock-session", "#session_id#"))
            self.config.set("Commands", "suspend", "systemctl suspend")
            self.config.set("Commands", "hibernate", "systemctl hibernate")
            self.config.set("Commands", "execute", "")

            self.temp_symbol = "°C"
            self.temp_scale = "celsius"
            write_config(self.config, MAIN_CFG)
コード例 #38
0
 def on_qPushButton4_clicked(self):
     datetime = QDateTime.fromString(self.ui.qLineEdit3.text(), "yyyy-MM-dd hh:mm:ss")
     self.ui.qDateTimeEdit.setDateTime(datetime)
コード例 #39
0
ファイル: ikawa.py プロジェクト: roundfile/new-builds
def extractProfileIkawaCSV(file,_):
    res = {} # the interpreted data set

    res["samplinginterval"] = 1.0

    # set profile date from the file name if it has the format "IKAWA yyyy-mm-dd hhmmss.csv"
    filename = os.path.basename(file)
    p = re.compile('IKAWA \d{4,4}-\d{2,2}-\d{2,2} \d{6,6}.csv')
    if p.match(filename):
        s = filename[6:-4] # the extracted date time string
        date = QDateTime.fromString(s,"yyyy-MM-dd HHmmss")
        res["roastdate"] = encodeLocal(date.date().toString())
        res["roastisodate"] = encodeLocal(date.date().toString(Qt.ISODate))
        res["roasttime"] = encodeLocal(date.time().toString())
        res["roastepoch"] = int(date.toTime_t())
        res["roasttzoffset"] = libtime.timezone

    csvFile = io.open(file, 'r', newline="",encoding='utf-8')
    data = csv.reader(csvFile,delimiter=',')
    #read file header
    header = next(data)
    
    fan = None # holds last processed fan event value
    fan_last = None # holds the fan event value before the last one
    heater = None # holds last processed heater event value
    heater_last = None # holds the heater event value before the last one
    fan_event = False # set to True if a fan event exists
    heater_event = False # set to True if a heater event exists
    specialevents = []
    specialeventstype = []
    specialeventsvalue = []
    specialeventsStrings = []
    timex = []
    temp1 = []
    temp2 = []
    extra1 = []
    extra2 = []
    timeindex = [-1,0,0,0,0,0,0,0] #CHARGE index init set to -1 as 0 could be an actal index used
    i = 0
    for row in data:
        i = i + 1
        items = list(zip(header, row))
        item = {}
        for (name, value) in items:
            item[name] = value.strip()
        # take i as time in seconds
        timex.append(i)
        if 'inlet temp' in item:
            temp1.append(float(item['inlet temp']))
        elif 'temp below' in item:
            temp1.append(float(item['temp below']))
        else:
            temp1.append(-1)
        # we map IKAWA Exhaust to BT as main events like CHARGE and DROP are marked on BT in Artisan
        if 'exaust temp' in item:
            temp2.append(float(item['exaust temp']))
        elif 'temp above' in item:
            temp2.append(float(item['temp above']))
        else:
            temp2.append(-1)
        # mark CHARGE
        if not timeindex[0] > -1 and 'state' in item and item['state'] == 'doser open':
            timeindex[0] = max(0,i)
        # mark DROP
        if timeindex[6] == 0 and 'state' in item and item['state'] == 'cooling':
            timeindex[6] = max(0,i)
        # add SET and RPM
        if 'temp set' in item:
            extra1.append(float(item['temp set']))
        elif 'setpoint' in item:
            extra1.append(float(item['setpoint']))
        else:
            extra1.append(-1)
        if 'fan speed (RPM)' in item:
            rpm = float(item['fan speed (RPM)'])
            extra2.append(rpm/100)
        elif 'fan speed' in item:
            rpm = float(item['fan speed'])
            extra2.append(rpm/100)
        else:
            extra2.append(-1)
        
        if "fan set (%)" in item or "fan set" in item:
            try:
                if "fan set (%)" in item:
                    v = float(item["fan set (%)"])
                elif "fan set" in item:
                    v = float(item["fan set"])
                if v != fan:
                    # fan value changed
                    if v == fan_last:
                        # just a fluctuation, we remove the last added fan value again
                        fan_last_idx = next(i for i in reversed(range(len(specialeventstype))) if specialeventstype[i] == 0)
                        del specialeventsvalue[fan_last_idx]
                        del specialevents[fan_last_idx]
                        del specialeventstype[fan_last_idx]
                        del specialeventsStrings[fan_last_idx]
                        fan = fan_last
                        fan_last = None
                    else:
                        fan_last = fan
                        fan = v
                        fan_event = True
                        v = v/10. + 1
                        specialeventsvalue.append(v)
                        specialevents.append(i)
                        specialeventstype.append(0)
                        specialeventsStrings.append("{}".format(fan) + "%")
                else:
                    fan_last = None
            except:
                pass
        if "heater power (%)" in item or "heater" in item:
            try:
                if "heater power (%)" in item:
                    v = float(item["heater power (%)"])
                elif "heater" in item:
                    v = float(item["heater"])
                if v != heater:
                    # heater value changed
                    if v == heater_last:
                        # just a fluctuation, we remove the last added heater value again
                        heater_last_idx = next(i for i in reversed(range(len(specialeventstype))) if specialeventstype[i] == 3)
                        del specialeventsvalue[heater_last_idx]
                        del specialevents[heater_last_idx]
                        del specialeventstype[heater_last_idx]
                        del specialeventsStrings[heater_last_idx]
                        heater = heater_last
                        heater_last = None
                    else:
                        heater_last = heater
                        heater = v
                        heater_event = True
                        v = v/10. + 1
                        specialeventsvalue.append(v)
                        specialevents.append(i)
                        specialeventstype.append(3)
                        specialeventsStrings.append("{}".format(heater) + "%")
                else:
                    heater_last = None
            except:
                pass
    csvFile.close()
    
    res["mode"] = 'C'
            
    res["timex"] = timex
    res["temp1"] = temp1
    res["temp2"] = temp2
    res["timeindex"] = timeindex
    
    res["extradevices"] = [25]
    res["extratimex"] = [timex[:]]
    
    res["extraname1"] = ["SET"]
    res["extratemp1"] = [extra1]
    res["extramathexpression1"] = [""]
    
    res["extraname2"] = ["RPM"]
    res["extratemp2"] = [extra2]
    res["extramathexpression2"] = ["x/100"]
    
    if len(specialevents) > 0:
        res["specialevents"] = specialevents
        res["specialeventstype"] = specialeventstype
        res["specialeventsvalue"] = specialeventsvalue
        res["specialeventsStrings"] = specialeventsStrings
        if heater_event or fan_event:
            # first set etypes to defaults
            res["etypes"] = [QApplication.translate("ComboBox", "Air",None),
                             QApplication.translate("ComboBox", "Drum",None),
                             QApplication.translate("ComboBox", "Damper",None),
                             QApplication.translate("ComboBox", "Burner",None),
                             "--"]
            # update
            if fan_event:
                res["etypes"][0] = "Fan"
            if heater_event:
                res["etypes"][3] = "Heater"
    return res
                
コード例 #40
0
ファイル: roastpath.py プロジェクト: seckar/artisan
def extractProfileRoastPathHTML(url):
    res = {}  # the interpreted data set
    try:
        s = requests.Session()
        s.mount('file://', FileAdapter())
        page = s.get(url.toString())
        tree = html.fromstring(page.content)

        title = ""
        date = tree.xpath(
            '//div[contains(@class, "roast-top")]/*/*[local-name() = "h5"]/text()'
        )
        if date and len(date) > 0:
            date_str = date[0].strip().split()
            if len(date_str) > 2:
                dateQt = QDateTime.fromString(date_str[-2] + date_str[-1],
                                              "yyyy-MM-ddhh:mm")
                if dateQt.isValid():
                    res["roastdate"] = encodeLocal(dateQt.date().toString())
                    res["roastisodate"] = encodeLocal(dateQt.date().toString(
                        Qt.ISODate))
                    res["roasttime"] = encodeLocal(dateQt.time().toString())
                    res["roastepoch"] = int(dateQt.toTime_t())
                    res["roasttzoffset"] = libtime.timezone
                title = "".join(date_str[:-2]).strip()
                if len(title
                       ) > 0 and title[-1] == "-":  # we remove a trailing -
                    title = title[:-1].strip()
            elif len(date_str) > 0:
                title = "".join(date_str)

        coffee = ""
        for m in [
                "Roasted By", "Coffee", "Batch Size", "Notes", "Organization"
        ]:
            s = '//*[@class="ml-2" and normalize-space(text())="Details"]/following::table[1]/tbody/tr[*]/td/*[normalize-space(text())="{}"]/following::td[1]/text()'.format(
                m)
            value = tree.xpath(s)
            if len(value) > 0:
                meta = value[0].strip()
                try:
                    if m == "Roasted By":
                        res["operator"] = meta
                    elif m == "Coffee":
                        coffee = meta
                        if title == "" or title == "Roast":
                            res["title"] = coffee
                    elif m == "Notes":
                        res["roastingnotes"] = meta
                    elif m == "Batch Size":
                        v, u = meta.split()
                        res["weight"] = [
                            float(v), 0, ("Kg" if u.strip() == "kg" else "lb")
                        ]
                    elif m == "Organization":
                        res["organization"] = meta
                except:
                    pass

        beans = ""
        for m in [
                "Nickname", "Country", "Region", "Farm", "Varietal", "Process"
        ]:
            s = '//*[@class="ml-2" and normalize-space(text())="Greens"]/following::table[1]/tbody/tr/td[count(//table/thead/tr/th[normalize-space(text())="{}"]/preceding-sibling::th)+1]/text()'.format(
                m)
            value = tree.xpath(s)
            if len(value) > 0:
                meta = value[0].strip()
                if meta != "":
                    if beans == "":
                        beans = meta
                    else:
                        beans += ", " + meta
        if coffee != "" and title in res:  # we did not use the "coffee" as title
            if beans == "":
                beans = coffee
            else:
                beans = coffee + "\n" + beans
        if beans != "":
            res["beans"] = beans
        if not "title" in res and title != "":
            res["title"] = title

        data = {}
        for e in [
                "btData", "etData", "atData", "eventData", "rorData",
                "noteData"
        ]:
            d = re.findall("var {} = JSON\.parse\('(.+?)'\);".format(e),
                           page.content.decode("utf-8"), re.S)
            bt = []
            if d:
                data[e] = json.loads(d[0])

        if "btData" in data and len(
                data["btData"]) > 0 and "Timestamp" in data["btData"][0]:
            # BT
            bt = data["btData"]
            baseTime = dateutil.parser.parse(bt[0]["Timestamp"]).timestamp()
            res["mode"] = 'C'
            res["timex"] = [
                dateutil.parser.parse(d["Timestamp"]).timestamp() - baseTime
                for d in bt
            ]
            res["temp2"] = [d["StandardValue"] for d in bt]

            # ET
            if "etData" in data and len(data["btData"]) == len(data["etData"]):
                et = data["etData"]
                res["temp1"] = [d["StandardValue"] for d in et]
            else:
                res["temp1"] = [-1] * len(res["temp2"])

            # Events
            timeindex = [-1, 0, 0, 0, 0, 0, 0, 0]
            if "eventData" in data:
                marks = {
                    "Charge": 0,
                    "Green > Yellow": 1,
                    "First Crack": 2,
                    "Second Crack": 4,
                    "Drop": 6
                }
                for d in data["eventData"]:
                    if "EventName" in d and d[
                            "EventName"] in marks and "Timestamp" in d:
                        tx = dateutil.parser.parse(
                            d["Timestamp"]).timestamp() - baseTime
                        try:
                            #                            tx_idx = res["timex"].index(tx) # does not cope with dropouts as the next line:
                            tx_idx = next(
                                i for i, item in enumerate(res["timex"])
                                if item >= tx)
                            timeindex[marks[d["EventName"]]] = tx_idx
                        except:
                            pass
            res["timeindex"] = timeindex

            # Notes
            if "noteData" in data:
                specialevents = []
                specialeventstype = []
                specialeventsvalue = []
                specialeventsStrings = []
                noteData = data["noteData"]
                for n in noteData:
                    if "Timestamp" in n and "NoteTypeId" in n and "Note" in n:
                        c = dateutil.parser.parse(
                            n["Timestamp"]).timestamp() - baseTime
                        try:
                            timex_idx = res["timex"].index(c)
                            specialevents.append(timex_idx)
                            note_type = n["NoteTypeId"]
                            if note_type == 0:  # Fuel
                                specialeventstype.append(3)
                            elif note_type == 1:  # Fan
                                specialeventstype.append(0)
                            elif note_type == 2:  # Drum
                                specialeventstype.append(1)
                            else:  # n == 3: # Notes
                                specialeventstype.append(4)
                            try:
                                v = float(n["Note"])
                                v = v / 10. + 1
                                specialeventsvalue.append(v)
                            except:
                                specialeventsvalue.append(0)
                            specialeventsStrings.append(n["Note"])
                        except:
                            pass
                if len(specialevents) > 0:
                    res["specialevents"] = specialevents
                    res["specialeventstype"] = specialeventstype
                    res["specialeventsvalue"] = specialeventsvalue
                    res["specialeventsStrings"] = specialeventsStrings

            if "atData" in data or "rorData" in data:
                res["extradevices"] = []
                res["extratimex"] = []
                res["extratemp1"] = []
                res["extratemp2"] = []
                res["extraname1"] = []
                res["extraname2"] = []
                res["extramathexpression1"] = []
                res["extramathexpression2"] = []
                res["extraLCDvisibility1"] = []
                res["extraLCDvisibility2"] = []
                res["extraCurveVisibility1"] = []
                res["extraCurveVisibility2"] = []
                res["extraDelta1"] = []
                res["extraDelta2"] = []
                res["extraFill1"] = []
                res["extraFill2"] = []
                res["extradevicecolor1"] = []
                res["extradevicecolor2"] = []
                res["extramarkersizes1"] = []
                res["extramarkersizes2"] = []
                res["extramarkers1"] = []
                res["extramarkers2"] = []
                res["extralinewidths1"] = []
                res["extralinewidths2"] = []
                res["extralinestyles1"] = []
                res["extralinestyles2"] = []
                res["extradrawstyles1"] = []
                res["extradrawstyles2"] = []

                # AT
                if "atData" in data:
                    res["extradevices"].append(25)
                    res["extraname1"].append("AT")
                    res["extraname2"].append("")
                    res["extramathexpression1"].append("")
                    res["extramathexpression2"].append("")
                    res["extraLCDvisibility1"].append(True)
                    res["extraLCDvisibility2"].append(False)
                    res["extraCurveVisibility1"].append(True)
                    res["extraCurveVisibility2"].append(False)
                    res["extraDelta1"].append(False)
                    res["extraDelta2"].append(False)
                    res["extraFill1"].append(False)
                    res["extraFill2"].append(False)
                    res["extradevicecolor1"].append('black')
                    res["extradevicecolor2"].append('black')
                    res["extramarkersizes1"].append(6.0)
                    res["extramarkersizes2"].append(6.0)
                    res["extramarkers1"].append(None)
                    res["extramarkers2"].append(None)
                    res["extralinewidths1"].append(1.0)
                    res["extralinewidths2"].append(1.0)
                    res["extralinestyles1"].append('-')
                    res["extralinestyles2"].append('-')
                    res["extradrawstyles1"].append('default')
                    res["extradrawstyles2"].append('default')
                    at = data["atData"]
                    timex = [
                        dateutil.parser.parse(d["Timestamp"]).timestamp() -
                        baseTime for d in at
                    ]
                    res["extratimex"].append(timex)
                    res["extratemp1"].append([d["StandardValue"] for d in at])
                    res["extratemp2"].append([-1] * len(timex))

                # BT RoR
                if "rorData" in data:
                    res["extradevices"].append(25)
                    res["extraname1"].append("RoR")
                    res["extraname2"].append("")
                    res["extramathexpression1"].append("")
                    res["extramathexpression2"].append("")
                    res["extraLCDvisibility1"].append(True)
                    res["extraLCDvisibility2"].append(False)
                    res["extraCurveVisibility1"].append(False)
                    res["extraCurveVisibility2"].append(False)
                    res["extraDelta1"].append(True)
                    res["extraDelta2"].append(False)
                    res["extraFill1"].append(False)
                    res["extraFill2"].append(False)
                    res["extradevicecolor1"].append('black')
                    res["extradevicecolor2"].append('black')
                    res["extramarkersizes1"].append(6.0)
                    res["extramarkersizes2"].append(6.0)
                    res["extramarkers1"].append(None)
                    res["extramarkers2"].append(None)
                    res["extralinewidths1"].append(1.0)
                    res["extralinewidths2"].append(1.0)
                    res["extralinestyles1"].append('-')
                    res["extralinestyles2"].append('-')
                    res["extradrawstyles1"].append('default')
                    res["extradrawstyles2"].append('default')
                    ror = data["rorData"]
                    timex = [
                        dateutil.parser.parse(d["Timestamp"]).timestamp() -
                        baseTime for d in ror
                    ]
                    res["extratimex"].append(timex)
                    res["extratemp1"].append([d["StandardValue"] for d in ror])
                    res["extratemp2"].append([-1] * len(timex))

    except Exception as e:
        #        import traceback
        #        import sys
        #        traceback.print_exc(file=sys.stdout)
        pass
    return res
コード例 #41
0
ファイル: gui.py プロジェクト: philippHorn/csv-plot
    def _set_end(self, py_datetime):

        qt_datetime = _datetime_to_Qdatetime(py_datetime)
        default = QDateTime.fromString("2000-01-01 00:00:00,0" , "yyyy-MM-dd HH:mm:ss,z")
        if self.end.dateTime() > qt_datetime or self.end.dateTime() == default:
             self.end.setDateTime(qt_datetime)
コード例 #42
0
def convert_astropy_to_pyqt(time_as_astropy):
    # the start time of the animation, as a string representation
    time_as_string = strftime_timestamp(time_as_astropy)
    # the start time of the animation, as a PyQt5 QDateTime() instance
    time_as_pyqt = QDateTime.fromString(time_as_string, 'yyyy-MM-dd hh:mm:ss')
    return time_as_pyqt
コード例 #43
0
    def _add_new_line(self):
        if self.buy_info_container.count() >= 11:
            QMessageBox.information(self.submit, "提示", '添加的行数过多,请提交后再做新增!')
            return

        self.line_number += 1
        line_number = str(self.line_number)
        buy_info_name = 'buy_info' + '_' + line_number
        setattr(self, buy_info_name, QtWidgets.QHBoxLayout())
        buy_info = getattr(self, buy_info_name)
        buy_info.setObjectName(buy_info_name)

        for index, title in enumerate(self.line_title):
            editor = static_func.create_instance('PyQt5.QtWidgets.' + self.edit_type[index])
            attr_name = title + '_' + line_number
            editor.setObjectName(attr_name)

            first_attr_name = title + '_' + '1'
            first_attr = getattr(self, first_attr_name)

            editor.setMinimumSize(getattr(first_attr, 'minimumSize')())
            editor.setMaximumSize(getattr(first_attr, 'maximumSize')())
            editor.setFont(getattr(first_attr, 'font')())

            if hasattr(first_attr, 'setClearButtonEnabled') and first_attr.isClearButtonEnabled():
                editor.setClearButtonEnabled(True)

            if title == 'buy_date':
                editor.setDisplayFormat("yyyy-MM-dd")
                editor.setDateTime(QDateTime.fromString(time_utils.get_now(), 'yyyy-MM-dd hh:mm:ss'))

            if title == 'remove':
                editor.setText('删除')
                editor.clicked.connect(self.do_remove)
                editor.setObjectName(attr_name)

            if title == 'seq':
                editor.setText(line_number)

            # 只读
            if title in ('total', 'unpaid'):
                editor.setReadOnly(first_attr.isReadOnly())
                editor.setEnabled(first_attr.isEnabled())
                editor.setText('0.0')

            if title in ('paid', 'price'):
                view_utils.set_validator(editor, 'float')
                editor.textEdited.connect(self._text_edit)
                editor.setText('0.0')

            if title == 'number':
                editor.valueChanged.connect(self._text_edit)

            if title in ('first_service', 'second_service'):
                self._add_all_service_item(editor)
                editor.activated.connect(self._add_all_service_item)
                if title == 'first_service':
                    editor.currentIndexChanged.connect(self._first_service_changed)

            if title == 'payment':
                view_utils.get_all_payment(editor)
                editor.addItem('点击新增')
                editor.activated['int'].connect(self._need_add_payment)

            view_utils.set_completer(editor, title)
            setattr(self, attr_name, editor)
            buy_info.addWidget(editor)
        self.buy_info_container.addLayout(buy_info)
コード例 #44
0
    def _load_tab(self, new_tab, data):  # noqa: C901
        """Load yaml data into a newly opened tab."""
        entries = []
        lazy_load = []  # type: typing.MutableSequence[_JsonType]
        # use len(data['history'])
        # -> dropwhile empty if not session.lazy_session
        lazy_index = len(data['history'])
        gen = itertools.chain(
            itertools.takewhile(lambda _: not lazy_load,
                                enumerate(data['history'])),
            enumerate(lazy_load),
            itertools.dropwhile(lambda i: i[0] < lazy_index,
                                enumerate(data['history'])))

        for i, histentry in gen:
            user_data = {}

            if 'zoom' in data:
                # The zoom was accidentally stored in 'data' instead of per-tab
                # earlier.
                # See https://github.com/qutebrowser/qutebrowser/issues/728
                user_data['zoom'] = data['zoom']
            elif 'zoom' in histentry:
                user_data['zoom'] = histentry['zoom']

            if 'scroll-pos' in data:
                # The scroll position was accidentally stored in 'data' instead
                # of per-tab earlier.
                # See https://github.com/qutebrowser/qutebrowser/issues/728
                pos = data['scroll-pos']
                user_data['scroll-pos'] = QPoint(pos['x'], pos['y'])
            elif 'scroll-pos' in histentry:
                pos = histentry['scroll-pos']
                user_data['scroll-pos'] = QPoint(pos['x'], pos['y'])

            if 'pinned' in histentry:
                new_tab.data.pinned = histentry['pinned']

            if (config.val.session.lazy_restore
                    and histentry.get('active', False)
                    and not histentry['url'].startswith('qute://back')):
                # remove "active" mark and insert back page marked as active
                lazy_index = i + 1
                lazy_load.append({
                    'title':
                    histentry['title'],
                    'url':
                    'qute://back#' + urllib.parse.quote(histentry['title']),
                    'active':
                    True
                })
                histentry['active'] = False

            active = histentry.get('active', False)
            url = QUrl.fromEncoded(histentry['url'].encode('ascii'))

            if 'original-url' in histentry:
                orig_url = QUrl.fromEncoded(
                    histentry['original-url'].encode('ascii'))
            else:
                orig_url = url

            if histentry.get("last_visited"):
                last_visited = QDateTime.fromString(
                    histentry.get("last_visited"),
                    Qt.ISODate,
                )  # type: typing.Optional[QDateTime]
            else:
                last_visited = None

            entry = TabHistoryItem(url=url,
                                   original_url=orig_url,
                                   title=histentry['title'],
                                   active=active,
                                   user_data=user_data,
                                   last_visited=last_visited)
            entries.append(entry)
            if active:
                new_tab.title_changed.emit(histentry['title'])

        try:
            new_tab.history.private_api.load_items(entries)
        except ValueError as e:
            raise SessionError(e)
コード例 #45
0
ファイル: gallery.py プロジェクト: ImoutoChan/happypanda
	def data(self, index, role=Qt.DisplayRole):
		if not index.isValid():
			return QVariant()
		if index.row() >= len(self._data) or \
			index.row() < 0:
			return QVariant()

		current_row = index.row() 
		current_gallery = self._data[current_row]
		current_column = index.column()

		def column_checker():
			if current_column == self._TITLE:
				title = current_gallery.title
				return title
			elif current_column == self._ARTIST:
				artist = current_gallery.artist
				return artist
			elif current_column == self._TAGS:
				tags = utils.tag_to_string(current_gallery.tags)
				return tags
			elif current_column == self._TYPE:
				type = current_gallery.type
				return type
			elif current_column == self._FAV:
				if current_gallery.fav == 1:
					return u'\u2605'
				else:
					return ''
			elif current_column == self._CHAPTERS:
				return len(current_gallery.chapters)
			elif current_column == self._LANGUAGE:
				return current_gallery.language
			elif current_column == self._LINK:
				return current_gallery.link
			elif current_column == self._DESCR:
				return current_gallery.info
			elif current_column == self._DATE_ADDED:
				g_dt = "{}".format(current_gallery.date_added)
				qdate_g_dt = QDateTime.fromString(g_dt, "yyyy-MM-dd HH:mm:ss")
				return qdate_g_dt
			elif current_column == self._PUB_DATE:
				g_pdt = "{}".format(current_gallery.pub_date)
				qdate_g_pdt = QDateTime.fromString(g_pdt, "yyyy-MM-dd HH:mm:ss")
				if qdate_g_pdt.isValid():
					return qdate_g_pdt
				else:
					return 'No date set'

		# TODO: name all these roles and put them in app_constants...

		if role == Qt.DisplayRole:
			return column_checker()
		# for artist searching
		if role == self.ARTIST_ROLE:
			artist = current_gallery.artist
			return artist

		if role == Qt.DecorationRole:
			pixmap = current_gallery.profile
			return pixmap
		
		if role == Qt.BackgroundRole:
			bg_color = QColor(242, 242, 242)
			bg_brush = QBrush(bg_color)
			return bg_color

		if app_constants.GRID_TOOLTIP and role == Qt.ToolTipRole:
			add_bold = []
			add_tips = []
			if app_constants.TOOLTIP_TITLE:
				add_bold.append('<b>Title:</b>')
				add_tips.append(current_gallery.title)
			if app_constants.TOOLTIP_AUTHOR:
				add_bold.append('<b>Author:</b>')
				add_tips.append(current_gallery.artist)
			if app_constants.TOOLTIP_CHAPTERS:
				add_bold.append('<b>Chapters:</b>')
				add_tips.append(len(current_gallery.chapters))
			if app_constants.TOOLTIP_STATUS:
				add_bold.append('<b>Status:</b>')
				add_tips.append(current_gallery.status)
			if app_constants.TOOLTIP_TYPE:
				add_bold.append('<b>Type:</b>')
				add_tips.append(current_gallery.type)
			if app_constants.TOOLTIP_LANG:
				add_bold.append('<b>Language:</b>')
				add_tips.append(current_gallery.language)
			if app_constants.TOOLTIP_DESCR:
				add_bold.append('<b>Description:</b><br />')
				add_tips.append(current_gallery.info)
			if app_constants.TOOLTIP_TAGS:
				add_bold.append('<b>Tags:</b>')
				add_tips.append(utils.tag_to_string(
					current_gallery.tags))
			if app_constants.TOOLTIP_LAST_READ:
				add_bold.append('<b>Last read:</b>')
				add_tips.append(
					'{} ago'.format(utils.get_date_age(current_gallery.last_read)) if current_gallery.last_read else "Never!")
			if app_constants.TOOLTIP_TIMES_READ:
				add_bold.append('<b>Times read:</b>')
				add_tips.append(current_gallery.times_read)
			if app_constants.TOOLTIP_PUB_DATE:
				add_bold.append('<b>Publication Date:</b>')
				add_tips.append('{}'.format(current_gallery.pub_date).split(' ')[0])
			if app_constants.TOOLTIP_DATE_ADDED:
				add_bold.append('<b>Date added:</b>')
				add_tips.append('{}'.format(current_gallery.date_added).split(' ')[0])

			tooltip = ""
			tips = list(zip(add_bold, add_tips))
			for tip in tips:
				tooltip += "{} {}<br />".format(tip[0], tip[1])
			return tooltip

		if role == self.GALLERY_ROLE:
			return current_gallery

		# favorite satus
		if role == self.FAV_ROLE:
			return current_gallery.fav

		if role == self.DATE_ADDED_ROLE:
			date_added = "{}".format(current_gallery.date_added)
			qdate_added = QDateTime.fromString(date_added, "yyyy-MM-dd HH:mm:ss")
			return qdate_added
		
		if role == self.PUB_DATE_ROLE:
			if current_gallery.pub_date:
				pub_date = "{}".format(current_gallery.pub_date)
				qpub_date = QDateTime.fromString(pub_date, "yyyy-MM-dd HH:mm:ss")
				return qpub_date

		if role == self.TIMES_READ_ROLE:
			return current_gallery.times_read

		if role == self.LAST_READ_ROLE:
			if current_gallery.last_read:
				last_read = "{}".format(current_gallery.last_read)
				qlast_read = QDateTime.fromString(last_read, "yyyy-MM-dd HH:mm:ss")
				return qlast_read

		return None