Exemplo n.º 1
0
    def save_recent_projects(self, folder):
        recent_project_list = QSettings(
            resources.SETTINGS_PATH,
            QSettings.IniFormat).value('recentProjects', {})
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

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

        if description == '':
            description = _translate("_s_ExplorerContainer", 'no description available')

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

        schema_uri = encode_uri(self.ds_uri, 'qgis_test')
        project_uri = encode_uri(self.ds_uri, 'qgis_test', 'abc')

        self.dropProjectsTable()  # make sure we have a clean start

        prj = QgsProject()
        uri = self.vl.source()
        vl1 = QgsVectorLayer(uri, 'test', 'postgres')
        self.assertEqual(vl1.isValid(), True)
        prj.addMapLayer(vl1)

        prj_storage = QgsApplication.projectStorageRegistry().projectStorageFromType("postgresql")
        self.assertTrue(prj_storage)

        lst0 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst0, [])

        # try to save project in the database

        prj.setFileName(project_uri)
        res = prj.write()
        self.assertTrue(res)

        lst1 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst1, ["abc"])

        # now try to load the project back

        prj2 = QgsProject()
        prj2.setFileName(project_uri)
        res = prj2.read()
        self.assertTrue(res)

        self.assertEqual(len(prj2.mapLayers()), 1)

        self.assertEqual(prj2.baseName(), "abc")
        self.assertEqual(prj2.absoluteFilePath(), "")  # path not supported for project storages
        self.assertTrue(abs(prj2.lastModified().secsTo(QDateTime.currentDateTime())) < 10)

        # try to see project's metadata

        res, metadata = prj_storage.readProjectStorageMetadata(project_uri)
        self.assertTrue(res)
        self.assertEqual(metadata.name, "abc")
        time_project = metadata.lastModified
        time_now = QDateTime.currentDateTime()
        time_diff = time_now.secsTo(time_project)
        self.assertTrue(abs(time_diff) < 10)

        # try to remove the project

        res = prj_storage.removeProject(project_uri)
        self.assertTrue(res)

        lst2 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst2, [])

        self.dropProjectsTable()  # make sure we have a clean finish... "leave no trace"
Exemplo n.º 3
0
    def __checkForExpired(self):
        """
        Private slot to check entries for expiration.
        """
        if self.__daysToExpire < 0 or len(self.__history) == 0:
            return

        now = QDateTime.currentDateTime()
        nextTimeout = 0

        while self.__history:
            checkForExpired = QDateTime(self.__history[-1].dateTime)
            checkForExpired.setDate(checkForExpired.date().addDays(self.__daysToExpire))
            if now.daysTo(checkForExpired) > 7:
                nextTimeout = 7 * 86400
            else:
                nextTimeout = now.secsTo(checkForExpired)
            if nextTimeout > 0:
                break

            itm = self.__history.pop(-1)
            self.__lastSavedUrl = ""
            self.entryRemoved.emit(itm)
        self.__saveTimer.saveIfNeccessary()

        if nextTimeout > 0:
            self.__expiredTimer.start(nextTimeout * 1000)
Exemplo n.º 4
0
    def refresh(self):
        minimum_datetime = QDateTime()
        minimum_datetime.setTime_t(self.community.get_block(1).mediantime)
        minimum_datetime.setTime(QTime(0, 0))

        self.date_from.setMinimumDateTime(minimum_datetime)
        self.date_from.setDateTime(minimum_datetime)
        self.date_from.setMaximumDateTime(QDateTime().currentDateTime())

        self.date_to.setMinimumDateTime(minimum_datetime)
        tomorrow_datetime = QDateTime().currentDateTime().addDays(1)
        self.date_to.setDateTime(tomorrow_datetime)
        self.date_to.setMaximumDateTime(tomorrow_datetime)

        ts_from = self.date_from.dateTime().toTime_t()
        ts_to = self.date_to.dateTime().toTime_t()

        model = HistoryTableModel(self.app.current_account, self.community)
        proxy = TxFilterProxyModel(ts_from, ts_to)
        proxy.setSourceModel(model)
        proxy.setDynamicSortFilter(True)
        proxy.setSortRole(Qt.DisplayRole)

        self.table_history.setModel(proxy)
        self.table_history.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_history.setSortingEnabled(True)
        self.table_history.horizontalHeader().setSectionResizeMode(QHeaderView.Interactive)
        self.table_history.resizeColumnsToContents()

        self.refresh_balance()
Exemplo n.º 5
0
    def __init__(self):
        self.events = Queue()
        self.app = QApplication(sys.argv)

        self.w = uic.loadUi("main.ui")
        self.w.setAttribute(Qt.WA_DeleteOnClose, True)
        self.w.show()

        self.sattable = self.w.satTable
        self.satview = self.w.mapCanvas

        self.scene = QtScene(self.satview)
        self.pal = QtPalette()

        self.rendersats = set()
        self.satcolors = dict()

        hdr = self.sattable.horizontalHeader()
        hdr.setSectionResizeMode(0, QHeaderView.ResizeToContents)
        hdr.setSectionResizeMode(1, QHeaderView.Fixed)
        hdr.setSectionResizeMode(2, QHeaderView.Fixed)

        self.w.dtFrom.setDateTime(QDateTime.currentDateTimeUtc())
        self.w.dtTo.setDateTime(
            QDateTime.currentDateTimeUtc().addSecs(3600 * 2)
        )

        self.filters = ["*", "*", "*", "*"]

        self.selectall = False
        self.nosats = True
        self.colchange = False

        self.connect_sigs()
Exemplo n.º 6
0
 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
Exemplo n.º 7
0
    def initControls(self, filter_):
        selected = filter_.get('operation', '')
        try:
            index = LogFilterDialog.OPERATION_OPTIONS.index(selected)
        except ValueError:
            index = 0
        self.operationCombo.setCurrentIndex(index)

        selected = filter_.get('tablename', '')
        try:
            index = LogFilterDialog.TABLENAME_OPTIONS.index(selected)
        except ValueError:
            index = 0
        self.tablenameCombo.setCurrentIndex(index)

        start = filter_.get('start_datetime', None)
        if start is None:
            start = datetime.utcnow()
            start = calendar.timegm(start.timetuple()) - 3600*24
        else:
            start = calendar.timegm(start.timetuple())
        
        end = filter_.get('end_datetime', datetime.utcnow())
        end = calendar.timegm(end.timetuple())
        self.fromEdit.setDateTime(QDateTime.fromTime_t(start, TZ))
        self.toEdit.setDateTime(QDateTime.fromTime_t(end, TZ))
Exemplo n.º 8
0
    def save_recent_projects(self, folder):
        settings = IDE.data_settings()
        recent_project_list = settings.value('recentProjects', {})
        # if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

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

        if not description:
            description = translations.TR_NO_DESCRIPTION

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            # if the length of the project list it's high that 10 then delete
            # the most old
            # TODO: add the length of available projects to setting
            if len(recent_project_list) > MAX_RECENT_PROJECTS:
                del recent_project_list[self.find_most_old_open(
                    recent_project_list)]
        settings.setValue('recentProjects', recent_project_list)
Exemplo n.º 9
0
    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")
Exemplo n.º 10
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                )
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                if source_data is not "":
                    amount_ref = self.account.units_to_diff_ref(source_data,
                                                                self.community)
                    # if referential type is quantitative...
                    if self.account.ref_type() == 'q':
                        # display int values
                        return QLocale().toString(float(amount_ref), 'f', 0)
                    else:
                        # display float values
                        return QLocale().toString(amount_ref, 'f', 6)

        if role == Qt.FontRole:
            font = QFont()
            if state_data == Transfer.AWAITING:
                font.setItalic(True)
            elif state_data == Transfer.REFUSED:
                font.setItalic(True)
            elif state_data == Transfer.TO_SEND:
                font.setBold(True)
            else:
                font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            if state_data == Transfer.REFUSED:
                return QColor(Qt.red)
            elif state_data == Transfer.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'deposit') or source_index.column() == self.sourceModel().columns_types.index('payment'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate)

        return source_data
Exemplo n.º 11
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 = 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()
Exemplo n.º 12
0
 def update_time(self):
     dateTime = QDateTime.currentDateTime()
     self.label_time.setText("{0}".format(QLocale.toString(
                     QLocale(),
                     QDateTime.currentDateTime(),
                     QLocale.dateTimeFormat(QLocale(), QLocale.NarrowFormat)
                 )))
     timer = QTimer()
     timer.timeout.connect(self.update_time)
     timer.start(1000)
Exemplo n.º 13
0
 def minimum_maximum_datetime(self):
     """
     Get minimum and maximum datetime
     :rtype: Tuple[PyQt5.QtCore.QDateTime, PyQt5.QtCore.QDateTime]
     :return: minimum and maximum datetime
     """
     minimum_datetime = QDateTime()
     minimum_datetime.setTime_t(1488322800) # First of may 2017
     tomorrow_datetime = QDateTime().currentDateTime().addDays(1)
     return minimum_datetime, tomorrow_datetime
Exemplo n.º 14
0
    def init_ui(self):
        # loadUi('ui/notes_edit_dialog.ui', self)
        self.setupUi(self)

        self.plannedDateTimeEdit.setMinimumDate(
            QDateTime.currentDateTime().date()
        )
        self.plannedDateTimeEdit.setDateTime(
            QDateTime.currentDateTime()
        )
Exemplo n.º 15
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            publication_col = CertifiersTableModel.columns_ids.index('publication')
            publication_index = self.sourceModel().index(source_index.row(), publication_col)
            expiration_col = CertifiersTableModel.columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)
            written_col = CertifiersTableModel.columns_ids.index('written')
            written_index = self.sourceModel().index(source_index.row(), written_col)

            publication_data = self.sourceModel().data(publication_index, Qt.DisplayRole)
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            written_data = self.sourceModel().data(written_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            warning_expiration_time = int((expiration_data - publication_data) / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if role == Qt.DisplayRole:
                if source_index.column() == CertifiersTableModel.columns_ids.index('expiration'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == CertifiersTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == CertifiersTableModel.columns_ids.index('pubkey'):
                    return source_data

            if role == Qt.FontRole:
                font = QFont()
                if not written_data:
                    font.setItalic(True)
                return font

            if role == Qt.ForegroundRole:
                if current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    return QColor("darkorange").darker(120)

            return source_data
Exemplo n.º 16
0
 def adjust_date_time(self):
     self.searchButton.setEnabled(True)
     self.cur_period = self.tp_combo.currentText()
     if self.cur_period == REPORT_CUSTOM_TP: return
     from PyQt5.QtCore import QDateTime
     start_t, end_t = period_to_timestamp(self.cur_period)
     self.startDateTime.dateTimeChanged.disconnect(self.clear_tp_combo)
     self.stopDateTime.dateTimeChanged.disconnect(self.clear_tp_combo)
     self.startDateTime.setDateTime(QDateTime.fromTime_t(start_t))
     self.stopDateTime.setDateTime(QDateTime.fromTime_t(end_t))
     self.startDateTime.dateTimeChanged.connect(self.clear_tp_combo)
     self.stopDateTime.dateTimeChanged.connect(self.clear_tp_combo)
Exemplo n.º 17
0
    def initControls(self, filter_):
        self.group.setChecked(False)

        for key in ['start_datetime', 'end_datetime']:
            if key in filter_:
                self.group.setChecked(True)
                break

        start = filter_.get('start_datetime', datetime.utcnow())
        start = calendar.timegm(start.timetuple())
        end = filter_.get('end_datetime', datetime.utcnow())
        end = calendar.timegm(end.timetuple())
        self.fromEdit.setDateTime(QDateTime.fromTime_t(start, TZ))
        self.toEdit.setDateTime(QDateTime.fromTime_t(end, TZ))
Exemplo n.º 18
0
 def checkForUpdate(self):
     """
     Public method to check for an update.
     """
     if self.__updatePeriod:
         updatePeriod = self.__updatePeriod
     else:
         updatePeriod = Preferences.getHelp("AdBlockUpdatePeriod") * 24
     if not self.__lastUpdate.isValid() or \
        (self.__remoteModified.isValid() and
         self.__remoteModified.addSecs(updatePeriod * 3600) <
             QDateTime.currentDateTime()) or \
        self.__lastUpdate.addSecs(updatePeriod * 3600) < \
             QDateTime.currentDateTime():
         self.updateNow()
Exemplo n.º 19
0
 def __startFrequencyTimer(self):
     """
     Private method to start the timer to recalculate the frequencies.
     """
     tomorrow = QDateTime(QDate.currentDate().addDays(1), QTime(3, 0))
     self.__frequencyTimer.start(
         QDateTime.currentDateTime().secsTo(tomorrow) * 1000)
Exemplo n.º 20
0
 def __newParticipant(self, nick):
     """
     Private slot handling a new participant joining.
     
     @param nick nick name of the new participant (string)
     """
     if nick == "":
         return
     
     color = self.chatEdit.textColor()
     self.chatEdit.setTextColor(Qt.gray)
     self.chatEdit.append(
         QDateTime.currentDateTime().toString(Qt.SystemLocaleLongDate) +
         ":")
     self.chatEdit.append(self.tr("* {0} has joined.\n").format(nick))
     self.chatEdit.setTextColor(color)
     
     QListWidgetItem(
         UI.PixmapCache.getIcon(
             "chatUser{0}.png".format(1 + self.usersList.count() % 6)),
         nick, self.usersList)
     
     if not self.__connected:
         self.__setConnected(True)
     
     if not self.isVisible():
         self.__ui.showNotification(
             UI.PixmapCache.getPixmap("cooperation48.png"),
             self.tr("New User"), self.tr("{0} has joined.")
                 .format(nick))
Exemplo n.º 21
0
 def __participantLeft(self, nick):
     """
     Private slot handling a participant leaving the session.
     
     @param nick nick name of the participant (string)
     """
     if nick == "":
         return
     
     items = self.usersList.findItems(nick, Qt.MatchExactly)
     for item in items:
         self.usersList.takeItem(self.usersList.row(item))
         del item
         
         color = self.chatEdit.textColor()
         self.chatEdit.setTextColor(Qt.gray)
         self.chatEdit.append(
             QDateTime.currentDateTime().toString(Qt.SystemLocaleLongDate) +
             ":")
         self.chatEdit.append(self.tr("* {0} has left.\n").format(nick))
         self.chatEdit.setTextColor(color)
     
     if not self.__client.hasConnections():
         self.__setConnected(False)
     
     if not self.isVisible():
         self.__ui.showNotification(
             UI.PixmapCache.getPixmap("cooperation48.png"),
             self.tr("User Left"), self.tr("{0} has left.")
                 .format(nick))
Exemplo n.º 22
0
 def __init__(self, mode, message="", parent=None):
     """
     Constructor
     
     @param mode mode of the dialog (HgQueuesNewPatchDialog.NEW_MODE,
         HgQueuesNewPatchDialog.REFRESH_MODE)
     @param message text to set as the commit message (string)
     @param parent reference to the parent widget (QWidget)
     @exception ValueError raised to indicate an invalid dialog mode
     """
     super(HgQueuesNewPatchDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.__mode = mode
     if self.__mode == HgQueuesNewPatchDialog.REFRESH_MODE:
         self.nameLabel.hide()
         self.nameEdit.hide()
     elif self.__mode == HgQueuesNewPatchDialog.NEW_MODE:
         # nothing special here
         pass
     else:
         raise ValueError("invalid value for mode")
     
     if message:
         self.messageEdit.setPlainText(message)
     
     self.dateTimeEdit.setDateTime(QDateTime.currentDateTime())
     
     self.__updateUI()
Exemplo n.º 23
0
 def __init__(self, tagsList, branchesList, bookmarksList=None,
              parent=None):
     """
     Constructor
     
     @param tagsList list of tags (list of strings)
     @param branchesList list of branches (list of strings)
     @param bookmarksList list of bookmarks (list of strings)
     @param parent parent widget (QWidget)
     """
     super(HgBackoutDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
     
     self.tagCombo.addItems(sorted(tagsList))
     self.branchCombo.addItems(["default"] + sorted(branchesList))
     if bookmarksList is not None:
         self.bookmarkCombo.addItems(sorted(bookmarksList))
     else:
         self.bookmarkButton.setHidden(True)
         self.bookmarkCombo.setHidden(True)
     
     self.__initDateTime = QDateTime.currentDateTime()
     self.dateEdit.setDateTime(self.__initDateTime)
Exemplo n.º 24
0
    def createBottomRightGroupBox(self):
        self.bottomRightGroupBox = QGroupBox("Group 3")
        self.bottomRightGroupBox.setCheckable(True)
        self.bottomRightGroupBox.setChecked(True)

        lineEdit = QLineEdit('s3cRe7')
        lineEdit.setEchoMode(QLineEdit.Password)

        spinBox = QSpinBox(self.bottomRightGroupBox)
        spinBox.setValue(50)

        dateTimeEdit = QDateTimeEdit(self.bottomRightGroupBox)
        dateTimeEdit.setDateTime(QDateTime.currentDateTime())

        slider = QSlider(Qt.Horizontal, self.bottomRightGroupBox)
        slider.setValue(40)

        scrollBar = QScrollBar(Qt.Horizontal, self.bottomRightGroupBox)
        scrollBar.setValue(60)

        dial = QDial(self.bottomRightGroupBox)
        dial.setValue(30)
        dial.setNotchesVisible(True)

        layout = QGridLayout()
        layout.addWidget(lineEdit, 0, 0, 1, 2)
        layout.addWidget(spinBox, 1, 0, 1, 2)
        layout.addWidget(dateTimeEdit, 2, 0, 1, 2)
        layout.addWidget(slider, 3, 0)
        layout.addWidget(scrollBar, 4, 0)
        layout.addWidget(dial, 3, 1, 2, 1)
        layout.setRowStretch(5, 1)
        self.bottomRightGroupBox.setLayout(layout)
Exemplo n.º 25
0
 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)
Exemplo n.º 26
0
    def replaceTemplate(self):
        if len(self.recipientInfo) == 0 or len(self.devicesInfo) == 0:
            return ""

        text = (self.act + '.')[:-1]
        text = self.updateElement(text, "time",
                                  self.startDatetime.time().toString("hh:mm"))
        text = self.updateElement(text, "date",
                                  self.startDatetime.date().toString("ddMMMyyyy"))
        for var in self.recipientInfo:
            text = self.updateElement(text, var, self.recipientInfo[var])
        
        amount = len(self.devicesInfo)
        text = self.updateElement(text, "amount", str(amount))
        text = self.updateElement(text, "amount_text", self.getAmountText(amount))
        deviceText = ""
        for i in range(amount):
            newDevice = (self.details + '.')[:-1]
            for var in self.devicesInfo[i]:
                newDevice = self.updateElement(newDevice, "index", str(i + 1))
                newDevice = self.updateElement(newDevice, var,
                                               self.devicesInfo[i][var])

            deviceText += newDevice
        text = self.updateElement(text, "details", deviceText)
        endDatetime = QDateTime.currentDateTime()
        text = self.updateElement(text, "endtime",
                                  endDatetime.time().toString("hh:mm"))
        return text
Exemplo n.º 27
0
 def __load(self):
     """
     Private method to load the model data.
     """
     if self.__loaded:
         return
     
     self.__filteredRows = []
     self.__historyDict = {}
     self.__scaleTime = QDateTime.currentDateTime()
     
     for sourceRow in range(self.sourceModel().rowCount()):
         idx = self.sourceModel().index(sourceRow, 0)
         url = idx.data(HistoryModel.UrlStringRole)
         if url not in self.__historyDict:
             sourceOffset = self.sourceModel().rowCount() - sourceRow
             self.__filteredRows.append(
                 HistoryData(sourceOffset, self.__frequencyScore(idx)))
             self.__historyDict[url] = sourceOffset
         else:
             # the url is known already, so just update the frequency score
             row = self.__filteredRows.index(
                 HistoryData(self.__historyDict[url], -1))
             self.__filteredRows[row].frequency += \
                 self.__frequencyScore(idx)
     
     self.__loaded = True
Exemplo n.º 28
0
    def set_settings(self):
        if self.traffic_id:
            query = """SELECT Position, Data, Table_Data, Note FROM staff_worker_traffic WHERE Id = %s"""
            sql_traffic = my_sql.sql_select(query, (self.traffic_id, ))
            if "mysql.connector.errors" in str(type(sql_traffic)):
                QMessageBox.critical(self, "Ошибка sql получения записей", sql_traffic.msg, QMessageBox.Ok)
                return False
            self.le_position.setText(str(sql_traffic[0][0]))
            self.dt_date.setDateTime(sql_traffic[0][1])
            self.le_note.setText(sql_traffic[0][3])
            if sql_traffic[0][2]:
                self.dt_tabel_date.setDateTime(sql_traffic[0][2])
            else:
                min = sql_traffic[0][1].minute
                if 0 <= min <= 15:
                    tab_date = sql_traffic[0][1].replace(minute=0)
                elif 16 <= min <= 45:
                    tab_date = sql_traffic[0][1].replace(minute=30)
                else:
                    tab_date = sql_traffic[0][1].replace(minute=0)
                    hour_up = sql_traffic[0][1].hour + 1
                    if hour_up < 24:
                        tab_date = tab_date.replace(hour=hour_up)
                    else:
                        day = sql_traffic[0][1].day
                        tab_date = tab_date.replace(day=day + 1, hour=hour_up-24)

                self.dt_tabel_date.setDateTime(tab_date)

        else:
            date = self.select_date or QDateTime.currentDateTime()
            datetime = QDateTime(date, QTime.currentTime())
            self.dt_date.setDateTime(datetime)
            self.dt_tabel_date.setDateTime(datetime)
Exemplo n.º 29
0
def test_cache_full(config_stub, tmpdir):
    """Do a sanity test involving everything."""
    config_stub.data = {
        'storage': {'cache-size': 1024},
        'general': {'private-browsing': False}
    }
    disk_cache = QNetworkDiskCache()
    disk_cache.setCacheDirectory(str(tmpdir))

    url = 'http://qutebrowser.org'
    content = b'cutebowser'
    preload_cache(disk_cache, url, content)
    url2 = 'https://qutebrowser.org'
    content2 = b'ohmycert'
    preload_cache(disk_cache, url2, content2)

    metadata = QNetworkCacheMetaData()
    metadata.setUrl(QUrl(url))
    soon = QDateTime.currentDateTime().addMonths(4)
    assert soon.isValid()
    metadata.setLastModified(soon)
    assert metadata.isValid()
    disk_cache.updateMetaData(metadata)
    disk_cache.remove(QUrl(url2))

    assert disk_cache.metaData(QUrl(url)).lastModified() == soon
    assert disk_cache.data(QUrl(url)).readAll() == content
Exemplo n.º 30
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        source_data = self.sourceModel().data(source_index, role)
        expiration_col = self.sourceModel().columns_ids.index('expiration')
        expiration_index = self.sourceModel().index(source_index.row(), expiration_col)
        expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
        current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
        sig_validity = self.community.parameters['sigValidity']
        warning_expiration_time = int(sig_validity / 3)
        #logging.debug("{0} > {1}".format(current_time, expiration_data))
        if expiration_data is not None:
            will_expire_soon = (current_time > expiration_data*1000 - warning_expiration_time*1000)
        if role == Qt.DisplayRole:
            if source_index.column() == self.sourceModel().columns_ids.index('renewed') \
                    or source_index.column() == self.sourceModel().columns_ids.index('expiration'):
                if source_data is not None:
                    return QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(source_data).date(),
                        QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                    )
                else:
                    return ""
            if source_index.column() == self.sourceModel().columns_ids.index('pubkey'):
                return "pub:{0}".format(source_data[:5])

        if role == Qt.ForegroundRole:
            if expiration_data:
                if will_expire_soon:
                    return QColor(Qt.red)
            else:
                return QColor(Qt.blue)
        return source_data
Exemplo n.º 31
0
def set_item_data(item, value, value_type):
    """
    Sets the item data
    :param item: item to set
    :param value: new item value
    :param value_type: new value type
    """

    if value_type in LIST_TYPES:
        if isinstance(value, str):
            value = ast.literal_eval(value)
        if value_type == FIELD_TYPE_LIST_DATE:
            new_list = []
            for subvalue in value:
                new_list.append(subvalue.strftime('%d/%m/%Y'))
            value = new_list
        elif value_type == FIELD_TYPE_LIST_DATETIME:
            new_list = []
            for subvalue in value:
                new_list.append(subvalue.strftime('%d/%m/%Y %H:%M:%S.%f'))
            value = new_list
        elif value_type == FIELD_TYPE_LIST_TIME:
            new_list = []
            for subvalue in value:
                new_list.append(subvalue.strftime('%H:%M:%S.%f'))
            value = new_list
        value_prepared = str(value)
        item.setData(Qt.EditRole, QVariant(value_prepared))
    elif value_type == FIELD_TYPE_DATETIME:
        if isinstance(value, datetime):
            value_prepared = QDateTime(value)
        elif isinstance(value, QDateTime):
            value_prepared = value
        elif isinstance(value, str):
            format = "%d/%m/%Y %H:%M:%S.%f"
            value_prepared = QDateTime(datetime.strptime(value, format))
        item.setData(Qt.EditRole, QVariant(value_prepared))
    elif value_type == FIELD_TYPE_DATE:
        if isinstance(value, date):
            value_prepared = QDate(value)
        elif isinstance(value, QDate):
            value_prepared = value
        elif isinstance(value, str):
            format = "%d/%m/%Y"
            value_prepared = QDate(datetime.strptime(value, format).date())
        item.setData(Qt.EditRole, QVariant(value_prepared))
    elif value_type == FIELD_TYPE_TIME:
        if isinstance(value, time):
            value_prepared = QTime(value)
        elif isinstance(value, QTime):
            value_prepared = value
        elif isinstance(value, str):
            format = "%H:%M:%S.%f"
            value_prepared = QTime(datetime.strptime(value, format).time())
        item.setData(Qt.EditRole, QVariant(value_prepared))
    elif value_type == FIELD_TYPE_FLOAT:
        value_prepared = float(value)
        item.setData(Qt.EditRole, QVariant(value_prepared))
    elif value_type == FIELD_TYPE_INTEGER:
        value_prepared = int(value)
        item.setData(Qt.EditRole, QVariant(value_prepared))
    elif value_type == FIELD_TYPE_BOOLEAN:
        value_prepared = value
        item.setData(Qt.EditRole, QVariant(value_prepared))
    elif value_type == FIELD_TYPE_STRING:
        value_prepared = str(value)
        item.setData(Qt.EditRole, QVariant(value_prepared))
Exemplo n.º 32
0
 def run(self):
     while True:
         data = QDateTime.currentDateTime()
         currentTime = data.toString("yyyy-MM-dd hh:mm:ss")
         self.update_date.emit(str(currentTime))
         time.sleep(1)
Exemplo n.º 33
0
 def showtime(self):
     self.LBbottom.setText(
         QDateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))
Exemplo n.º 34
0
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        self.episode_index = -1
        self.frame_index = 0
        self.frame_jump = 10
        self.max_time = 0
        self.download_path = ''
        self.sensor = 0
        self.episode_selected = False

        self.episodes = []
        self.episode_sensors = []

        self.update_from_button = False

        self.ui.refreshButton.clicked.connect(self.reload_db)
        self.ui.timeList.currentRowChanged.connect(self.episode_clicked)

        self.ui.forwardOneButton.clicked.connect(self.one_forward)
        self.ui.backwardOneButton.clicked.connect(self.one_backward)
        self.ui.forwardMoreButton.clicked.connect(self.more_forward)
        self.ui.backwardMoreButton.clicked.connect(self.more_backward)

        self.ui.connectTimeSpinbox.valueChanged.connect(
            self.update_connect_time)
        self.ui.sliceTimeSpinbox.valueChanged.connect(self.update_slice_time)

        self.ui.timeSlider.valueChanged.connect(self.move_timeslider)

        self.ui.saveCSVFRAMEButton.clicked.connect(
            self.write_csv_current_frame)
        self.ui.saveCSVEPISODEButton.clicked.connect(
            self.write_csv_current_episode)
        self.ui.loadCSVButton.clicked.connect(self.load_csv_button)

        now = QDateTime()
        now.setSecsSinceEpoch(time.time())

        yesterday = QDateTime()
        yesterday.setSecsSinceEpoch(time.time() - 24 * 60 * 60)

        self.ui.startTimeEdit.setDateTime(yesterday)
        self.ui.stopTimeEdit.setDateTime(now)

        self.connect_time = self.ui.connectTimeSpinbox.value()
        self.slice_time = self.ui.sliceTimeSpinbox.value()

        self.plotGraphicsView = ZoomQGraphicsView()

        self.ui.rightVLayout.insertWidget(0, self.plotGraphicsView)
        self.plot_scene = QGraphicsScene()
        self.plotGraphicsView.setScene(self.plot_scene)

        self.ui.frameAmountSpinbox.valueChanged.connect(
            self.update_episodes_ui_update)
        self.ui.sliceTimeSpinbox.valueChanged.connect(
            self.update_episodes_ui_update)
        self.ui.connectTimeSpinbox.valueChanged.connect(
            self.update_episodes_ui_update)
        self.ui.stopTimeEdit.dateTimeChanged.connect(
            self.update_episodes_ui_update)
        self.ui.startTimeEdit.dateTimeChanged.connect(
            self.update_episodes_ui_update)
        self.ui.ignoreStartCheckbox.stateChanged.connect(
            self.update_episodes_ui_update)
        self.ui.ignoreStopCheckbox.stateChanged.connect(
            self.update_episodes_ui_update)

        self.sensors = []

        self.or_index_counter = 0

        self.logger = logging.getLogger('database_scroll_logger')

        self.db_bridge = DB_Bridge()
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
created by Fangyang on Time:2019/11/10
'''
__author__ = 'Fangyang'

from PyQt5.QtCore import QDate, QTime, QDateTime, Qt

now = QDate.currentDate()
print(now.toString(Qt.ISODate))
print(now.toString(Qt.DefaultLocaleLongDate))

datetime = QDateTime.currentDateTime()
print(datetime.toString())

time = QTime.currentTime()
print(time.toString(Qt.DefaultLocaleLongDate))

if __name__ == '__main__':
    pass
Exemplo n.º 36
0
 def updateOutput(self, msg, showTime=False):
     if showTime:
         now = QDateTime.currentDateTime().toString('yyyy-MM-dd hh:mm:ss')
         self.output.append(f"<span style='color:blue'>{now}</span>")
     self.output.append(msg)
Exemplo n.º 37
0
 def getDateTime(self):
         return QDateTime.currentDateTime().toString(Qt.ISODate)
Exemplo n.º 38
0
 def show_current_date_time(self):
     self.dateLabel.setText(
         QDateTime.currentDateTime().toString("yyyy/MM/dd"))
     self.timeLabel.setText(
         QDateTime.currentDateTime().toString("hh:mm:ss"))
Exemplo n.º 39
0
 def _get_date_time_from_ui(self, dateEdit, onlyDate=True):
     if onlyDate:
         return QDateTime(dateEdit.date()).toPyDateTime()
     else:
         return QDateTime(dateEdit.dateTime()).toPyDateTime()
Exemplo n.º 40
0
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
                
Exemplo n.º 41
0
 def displayTime(self):
     self.timeStatus.setText(QDateTime.currentDateTime().toString())
Exemplo n.º 42
0
 def Qtimewidget(self):
     self.currentDateTime = QDateTime.currentDateTime()
     self.dateTimeEdit.setDateTime(self.currentDateTime)
     self.dateTimeEdit.repaint()
Exemplo n.º 43
0
	def setDisplayLabel(self):
		self.datetime4display = QDateTime.currentDateTime().toString()
    def testSaveLoadProject(self):

        schema_uri = encode_uri(self.ds_uri, 'qgis_test')
        project_uri = encode_uri(self.ds_uri, 'qgis_test', 'abc')

        self.dropProjectsTable()  # make sure we have a clean start

        prj = QgsProject()
        uri = self.vl.source()
        vl1 = QgsVectorLayer(uri, 'test', 'postgres')
        self.assertEqual(vl1.isValid(), True)
        prj.addMapLayer(vl1)

        prj_storage = QgsApplication.projectStorageRegistry(
        ).projectStorageFromType("postgresql")
        self.assertTrue(prj_storage)

        lst0 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst0, [])

        # try to save project in the database

        prj.setFileName(project_uri)
        res = prj.write()
        self.assertTrue(res)

        lst1 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst1, ["abc"])

        # now try to load the project back

        prj2 = QgsProject()
        prj2.setFileName(project_uri)
        res = prj2.read()
        self.assertTrue(res)

        self.assertEqual(len(prj2.mapLayers()), 1)

        self.assertEqual(prj2.baseName(), "abc")
        self.assertEqual(prj2.absoluteFilePath(),
                         "")  # path not supported for project storages
        self.assertTrue(
            abs(prj2.lastModified().secsTo(QDateTime.currentDateTime())) < 10)

        # try to see project's metadata

        res, metadata = prj_storage.readProjectStorageMetadata(project_uri)
        self.assertTrue(res)
        self.assertEqual(metadata.name, "abc")
        time_project = metadata.lastModified
        time_now = QDateTime.currentDateTime()
        time_diff = time_now.secsTo(time_project)
        self.assertTrue(abs(time_diff) < 10)

        # try to remove the project

        res = prj_storage.removeProject(project_uri)
        self.assertTrue(res)

        lst2 = prj_storage.listProjects(schema_uri)
        self.assertEqual(lst2, [])

        self.dropProjectsTable(
        )  # make sure we have a clean finish... "leave no trace"
Exemplo n.º 45
0
# -*- coding: utf-8 -*-
"""
Created on Thu Mar  4 12:40:03 2021

@author: ChrisLe
"""

from PyQt5.QtCore import QDateTime, Qt

now = QDateTime.currentDateTime()

print(f'Hoy:', now.toString(Qt.ISODate))
print(f'Añadiendo 12 dias: {now.addDays(12).toString(Qt.ISODate)}')
print(f'Quitando 22 dias: {now.addDays(-22).toString(Qt.ISODate)}')

print(f'Añadiendo 50 segundos: {now.addSecs(50).toString(Qt.ISODate)}')
print(f'Añadiendo 3 meses: {now.addMonths(3).toString(Qt.ISODate)}')
print(f'Añadiendo 12 años: {now.addYears(12).toString(Qt.ISODate)}')

Exemplo n.º 46
0
    def setupTab2(self, tab2):
        """Special widgets for preview panel"""
        scrollContainer = QVBoxLayout()
        scrollArea = QScrollArea()
        scrollArea.setWidgetResizable(True)
        mainWidget = QWidget()
        layout = QVBoxLayout()
        mainWidget.setLayout(layout)
        mainWidget.setMinimumSize(QSize(420, 800))
        scrollArea.setWidget(mainWidget)
        scrollContainer.addWidget(scrollArea)
        tab2.setLayout(scrollContainer)

        # Dialog
        group0 = QGroupBox("Dialog")
        group1Layout = QVBoxLayout()
        layoutRow1 = QHBoxLayout()
        layoutRow2 = QHBoxLayout()
        group1Layout.addLayout(layoutRow1)
        group1Layout.addLayout(layoutRow2)
        group0.setLayout(group1Layout)
        layout.addWidget(group0)

        b1 = QPushButton(self.tr("Info"))
        b1.clicked.connect(lambda: QMessageBox.information(
            self, "Info", self.tr("This is a message."), QMessageBox.Ok,
            QMessageBox.Ok))
        b2 = QPushButton(self.tr("Question"))
        b2.clicked.connect(lambda: QMessageBox.question(
            self, "question", self.tr("Are you sure?"), QMessageBox.No |
            QMessageBox.Yes, QMessageBox.Yes))
        b3 = QPushButton(self.tr("Warning"))
        b3.clicked.connect(lambda: QMessageBox.warning(
            self, "warning", self.tr("This is a warning."), QMessageBox.No |
            QMessageBox.Yes, QMessageBox.Yes))
        b4 = QPushButton(self.tr("Error"))
        b4.clicked.connect(lambda: QMessageBox.critical(
            self, "error", self.tr("It's a error."), QMessageBox.No |
            QMessageBox.Yes, QMessageBox.Yes))
        b5 = QPushButton(self.tr("About"))
        b5.clicked.connect(lambda: QMessageBox.about(
            self, "about", self.tr("About this software")))
        b6 = QPushButton(self.tr("Input"))  # ,"输入对话框"))
        b6.clicked.connect(lambda: QInputDialog.getInt(
            self, self.tr("input"), self.tr("please input int")))
        b6.clicked.connect(lambda: QInputDialog.getDouble(
            self, self.tr("input"), self.tr("please input float")))
        b6.clicked.connect(lambda: QInputDialog.getItem(
            self, self.tr("input"), self.tr("please select"), ["aaa", "bbb"]))
        b7 = QPushButton(self.tr("Color"))  # ,"颜色对话框"))
        b7.clicked.connect(lambda: QColorDialog.getColor())
        b8 = QPushButton(self.tr("Font"))  # ,"字体对话框"))
        b8.clicked.connect(lambda: QFontDialog.getFont())
        b9 = QPushButton(self.tr("OpenFile"))  # ,"打开对话框"))
        b9.clicked.connect(lambda: QFileDialog.getOpenFileName(
            self, "open", "", "Text(*.txt *.text)"))
        b10 = QPushButton(self.tr("SaveFile"))  # ,"保存对话框"))
        b10.clicked.connect(lambda: QFileDialog.getSaveFileName())
        layoutRow1.addWidget(b1)
        layoutRow1.addWidget(b2)
        layoutRow1.addWidget(b3)
        layoutRow1.addWidget(b4)
        layoutRow1.addWidget(b5)
        layoutRow2.addWidget(b6)
        layoutRow2.addWidget(b7)
        layoutRow2.addWidget(b8)
        layoutRow2.addWidget(b9)
        layoutRow2.addWidget(b10)

        # DateTime
        group1 = QGroupBox("DateTime")
        group1.setCheckable(True)
        group1Layout = QHBoxLayout()
        layoutRow1 = QVBoxLayout()
        layoutRow2 = QVBoxLayout()
        group1Layout.addLayout(layoutRow1)
        group1Layout.addLayout(layoutRow2)
        group1.setLayout(group1Layout)
        layout.addWidget(group1)

        group1.setMaximumHeight(240)
        dt1 = QDateEdit()
        dt1.setDate(QDate.currentDate())
        dt2 = QTimeEdit()
        dt2.setTime(QTime.currentTime())
        dt3 = QDateTimeEdit()
        dt3.setDateTime(QDateTime.currentDateTime())
        dt4 = QDateTimeEdit()
        dt4.setCalendarPopup(True)
        dt5 = QCalendarWidget()
        dt5.setMaximumSize(QSize(250, 240))
        layoutRow1.addWidget(dt1)
        layoutRow1.addWidget(dt2)
        layoutRow1.addWidget(dt3)
        layoutRow1.addWidget(dt4)
        layoutRow2.addWidget(dt5)

        # Slider
        group2 = QGroupBox("Sliders")
        group2.setCheckable(True)
        group2Layout = QVBoxLayout()
        layoutRow1 = QHBoxLayout()
        layoutRow2 = QHBoxLayout()
        group2Layout.addLayout(layoutRow1)
        group2Layout.addLayout(layoutRow2)
        group2.setLayout(group2Layout)
        layout.addWidget(group2)

        slider = QSlider()
        slider.setOrientation(Qt.Horizontal)
        slider.setMaximum(100)
        progress = QProgressBar()
        slider.valueChanged.connect(progress.setValue)
        slider.setValue(50)
        scroll1 = QScrollBar()
        scroll2 = QScrollBar()
        scroll3 = QScrollBar()
        scroll1.setMaximum(255)
        scroll2.setMaximum(255)
        scroll3.setMaximum(255)
        scroll1.setOrientation(Qt.Horizontal)
        scroll2.setOrientation(Qt.Horizontal)
        scroll3.setOrientation(Qt.Horizontal)
        c = QLabel(self.tr("Slide to change color"))  # , "拖动滑块改变颜色"))
        c.setAutoFillBackground(True)
        c.setAlignment(Qt.AlignCenter)
        # c.setStyleSheet("border:1px solid gray;")
        c.setStyleSheet("background:rgba(0,0,0,100);")

        def clr():
            # clr=QColor(scroll1.getValue(),scroll2.getValue(),scroll3.getValue(),100)
            # p=QPalette()
            # p.setColor(QPalette.Background,clr)
            # c.setPalette(p)
            c.setStyleSheet("background: rgba({},{},{},100);".format(
                scroll1.value(), scroll2.value(), scroll3.value()))

        scroll1.valueChanged.connect(clr)
        scroll2.valueChanged.connect(clr)
        scroll3.valueChanged.connect(clr)
        scroll1.setValue(128)
        layoutRow1.addWidget(slider)
        layoutRow1.addWidget(progress)
        layCol1 = QVBoxLayout()
        layCol1.addWidget(scroll1)
        layCol1.addWidget(scroll2)
        layCol1.addWidget(scroll3)
        layoutRow2.addLayout(layCol1)
        layoutRow2.addWidget(c)

        # Meter
        group3 = QGroupBox("Meters")
        group3.setCheckable(True)
        layRow = QHBoxLayout()
        group3.setLayout(layRow)
        layout.addWidget(group3)

        dial1 = QDial()
        dial2 = QDial()
        dial2.setNotchesVisible(True)
        dial1.valueChanged.connect(dial2.setValue)
        layRow.addWidget(dial1)
        layRow.addWidget(dial2)

        layout.addStretch(1)
Exemplo n.º 47
0
    def Tab1_running(self, args):

        self.tn1 = self.tn
        self.args = args
        self.t = threading.currentThread(
        )  # This helps to send a Flag to a running Thread to stop or else purpose.
        # while getattr(self.t, "do_run", True):
        # print ("working on %s" % self.arg)

        # self.tn1.set_debuglevel(0.5)
        # self.tn1_read = self.tn1.read_all()
        # print (repr(tn1_read))
        # self.tn1.read_until(b"#").decode('ascii')

        date_from = self.dateTimeEdit.text()
        date_to = self.dateTimeEdit_2.text()

        temp_for_command = [
        ]  # This used to receive a string of commands with ";" such as) run show interface terse;aaaa;run show chassis hardware;
        temp_for_command = self.lineEdit_4.text().split(
            ';')  #split used to save command list as LIST.

        if ((date_from or date_to) == '2000-01-01 00:00.00') or (
                date_from <=
                QDateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                and QDateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                <= date_to):
            for i in range(int(self.lineEdit_5.text())):

                if ((date_from or date_to) == '2000-01-01 00:00.00') or (
                        date_from <= QDateTime.currentDateTime().toString(
                            "yyyy-MM-dd hh:mm:ss")
                        and QDateTime.currentDateTime().toString(
                            "yyyy-MM-dd hh:mm:ss") <= date_to):
                    #  print(i)
                    #  print(QDateTime.currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))

                    for j in temp_for_command:
                        self.tn1.write(j.encode('ascii') + b'\n')
                        time.sleep(int(self.lineEdit_6.text()))
                        temporal = self.tn1.read_very_eager().decode('ascii')
                        self.textBrowser_2.append(temporal)

                        if getattr(
                                self.t, "do_run", True
                        ):  #This receives a Flag from "slot_4st" to stop it.

                            if self.fileName != 'Null':
                                print(self.fileName)
                                print(temporal)
                                self.ff.write(temporal)
                                self.ff.flush(
                                )  #This is to write system outputs in Buffer to a file.

                        else:
                            sys.exit(
                            )  #Thread stop, as running out of for loop.

                else:
                    self.textBrowser_2.append(
                        "Your test ended. or please check time expired 4).Running Schedule "
                    )
                    break

        else:
            # self.textBrowser_2.setFontPointSize(20)
            self.textBrowser_2.append(
                "please check the other input values added properly or time expired at 4).Running Schedule"
            )
Exemplo n.º 48
0
 def end(self):
     return QDateTime(self._fact.end)
Exemplo n.º 49
0
 def set_bound(self, dt, low, high):
     axisX = QDateTimeAxis()
     axisX.setFormat('h:mm')
     start_time = QDateTime()
     finish_time = QDateTime()
     start_time.setDate(QDate(dt.year, dt.month, dt.day))
     start_time.setTime(QTime(9, 0))
     finish_time.setDate(QDate(dt.year, dt.month, dt.day))
     finish_time.setTime(QTime(15, 30))
     axisX.setRange(start_time, finish_time)
     axisY = QValueAxis()
     axisY.setRange(low, high)
     self.chart_view.chart().setAxisX(axisX, self.price_series)
     self.chart_view.chart().setAxisY(axisY, self.price_series)
Exemplo n.º 50
0
    def build_gui(self):
        vbox = QVBoxLayout()
        self.setLayout(vbox)
        grid = QGridLayout()
        vbox.addLayout(grid)
        self.amount_label = QLabel('')

        grid.addWidget(QLabel(_("Target for confirmation")), 0, 0)
        self.qtarget = QDateTimeEdit(QDateTime.currentDateTime().addSecs(
            int(self.main_window.config.get('bitpost_target_interval')) * 60))
        grid.addWidget(self.qtarget, 0, 1)

        self.asap_check = QCheckBox("ASAP")
        self.asap_check.clicked.connect(self.toggle_target)
        grid.addWidget(self.asap_check, 0, 2)

        grid.addWidget(QLabel(_("Maximum Fee")), 2, 0)
        self.max_fees = QLineEdit(
            str(self.main_window.config.get('bitpost_max_fee')))
        self.max_fees.textChanged.connect(self.change_max_fees)
        grid.addWidget(self.max_fees, 2, 1)
        self.fee_combo = QComboBox()
        fee_combo_values = get_fee_units(
            self.main_window,
            self.main_window.config.get('bitpost_max_fee_unit'))
        self.fee_combo.addItems(fee_combo_values)
        grid.addWidget(self.fee_combo, 2, 2)

        self.schedule_check = QCheckBox(_("Schedule transaction"))
        self.schedule_check.clicked.connect(self.toggle_delay)
        grid.addWidget(self.schedule_check, 3, 0, 1, -1)
        self.qdelay = QDateTimeEdit(QDateTime.currentDateTime())
        grid.addWidget(self.qdelay, 4, 0)
        sp_retain = QSizePolicy(self.qdelay.sizePolicy())
        sp_retain.setRetainSizeWhenHidden(True)
        self.qdelay.setSizePolicy(sp_retain)
        self.qdelay.setVisible(False)

        self.message_label = QLabel(self.default_message())
        grid.addWidget(self.message_label, 9, 0, 1, -1)
        self.pw_label = QLabel(_('Password'))
        self.pw_label.setVisible(self.password_required)
        self.pw = PasswordLineEdit()
        self.pw.setVisible(self.password_required)
        grid.addWidget(self.pw_label, 11, 0)
        grid.addWidget(self.pw, 11, 1, 1, -1)

        self.send_button = QPushButton(_('Send'))
        self.send_button.clicked.connect(self.on_send)
        self.send_button.setDefault(True)

        self.preview_button = QPushButton(_('Preview'))
        self.preview_button.clicked.connect(self.on_preview)
        self.preview_button.setDefault(True)

        vbox.addLayout(
            Buttons(CancelButton(self), self.preview_button, self.send_button))

        # set default to ASAP checked
        self.asap_check.setChecked(True)
        self.toggle_target()

        self.update()
        self.is_send = False
Exemplo n.º 51
0
    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)
Exemplo n.º 52
0
 def start(self):
     return QDateTime(self._fact.start)
Exemplo n.º 53
0
#!/usr/bin/python3

#unix epoch

from PyQt5.QtCore import QDateTime, Qt

now = QDateTime.currentDateTime()

unix_time = now.toSecsSinceEpoch()
print(unix_time)

d = QDateTime.fromSecsSinceEpoch(unix_time)
print(d.toString(Qt.ISODate))
def do_training():

    D = []
    number_of_class = 0

    # uploading the dummy data to the model.
    #--------------------------------------------------------------------------
    with open('audio/dummy_class.csv', 'r') as f:
        reader = csv.reader(f)
        next(reader, None)

        for row in reader:

            try:
                # selecting name and id
                #--------------------------------------------------------------
                name = row[1]
                classID = row[0]
                print(classID, '\t', colored(name, 'red'))

                # generating the data for model.
                #--------------------------------------------------------------
                originalData(name, classID, D)
                #slowData(name, classID, D)
                #speedData(name, classID, D)
                #semitonesHigh(name, classID, D)
                #semitonesLow(name, classID, D)

                # global class for counting number of classes available.
                #--------------------------------------------------------------
                number_of_class += 1

            except:
                print('header detected so passing it.\n')
                pass

    with open('audio/classes.csv', 'r') as f:
        reader = csv.reader(f)

        # skip the headers or the first row of the csv if
        # we add it multiple times then it will remove multiple rows.
        #----------------------------------------------------------------------
        next(reader, None)

        for row in reader:

            try:
                # selecting name and id
                #--------------------------------------------------------------
                name = row[1]
                classID = row[0]
                print(classID, '\t', colored(name, 'cyan'))

                # generating the data for model.
                #--------------------------------------------------------------
                originalData(name, classID, D)
                #originalData_with_threshold(name, classID, D)
                #slowData(name, classID, D)
                #speedData(name, classID, D)
                #semitonesHigh(name, classID, D)
                #semitonesLow(name, classID, D)

                # global class for counting number of classes available.
                #--------------------------------------------------------------
                number_of_class += 1

            except:
                print('header detected so passing it.\n')
                pass

    k.clear_session()

    dataset = D
    random.shuffle(dataset)
    random.shuffle(dataset)
    random.shuffle(dataset)

    D_len = len(D)
    data_split = int((D_len * 70) / 100)

    train = dataset[:data_split]
    test = dataset[data_split:]

    X_train, y_train = zip(*train)
    X_test, y_test = zip(*test)

    # Reshape for CNN input.
    #--------------------------------------------------------------------------
    X_train = np.array([x.reshape((128, 128, 1)) for x in X_train])
    X_test = np.array([x.reshape((128, 128, 1)) for x in X_test])

    # One-Hot encoding for classes
    #--------------------------------------------------------------------------
    y_train = np.array(keras.utils.to_categorical(y_train, number_of_class))
    y_test = np.array(keras.utils.to_categorical(y_test, number_of_class))

    k.clear_session()

    model = Sequential()
    input_shape = (128, 128, 1)

    model.add(
        Conv2D(16, (3, 3),
               strides=(1, 1),
               input_shape=input_shape,
               padding='same'))
    model.add(Activation('relu'))

    model.add(Conv2D(32, (3, 3), strides=(1, 1), padding='same'))
    model.add(Activation('relu'))

    model.add(Conv2D(64, (3, 3), strides=(1, 1), padding='same'))
    model.add(Activation('relu'))

    model.add(Conv2D(128, (3, 3), strides=(1, 1), padding='same'))
    model.add(Activation('relu'))

    model.add(MaxPooling2D((2, 2)))

    model.add(Dropout(0.5))

    model.add(Flatten())

    model.add(Dense(128, activation='relu'))
    model.add(Dense(64, activation='relu'))

    model.add(Dense(number_of_class))
    model.add(Activation('softmax'))

    model.compile(optimizer="Adam",
                  loss="categorical_crossentropy",
                  metrics=['accuracy'])

    # defining the batch size and epochs.
    # num_b_size = len(test)*
    # num_epochs = int((len(D)-part)/num_b_size)

    set_epochs = 20
    set_batch = 32

    history = model.fit(X_train,
                        y_train,
                        epochs=set_epochs,
                        batch_size=set_batch,
                        validation_data=(X_test, y_test))

    score = model.evaluate(X_test, y_test)

    print('\n\nTest loss:', colored(score[0] * 100, 'red'))
    print('Test accuracy:', colored(score[1] * 100, 'green'))

    Totaldata = D_len
    NoClass = number_of_class
    BatchSize = set_batch
    Epoches = set_epochs
    TrainAcc = round(history.history['acc'][-1] * 100, 4)
    TestAcc = round(history.history['val_acc'][-1] * 100, 4)
    TrainLoss = round(history.history['loss'][-1] * 100, 4)
    TestLoss = round(history.history['val_loss'][-1] * 100, 4)
    DateTrain = QDateTime.currentDateTime().toString()

    # inserting the details into the CSV.
    #--------------------------------------------------------------------------
    update_training_CSV(Totaldata, NoClass, BatchSize, Epoches, TrainAcc,
                        TestAcc, TrainLoss, TestLoss, DateTrain)

    # saving thr trained model data.
    #--------------------------------------------------------------------------
    model.save('models/gunshot_prediction.h5')

    # this variable is going to be used to get back from the training progress bar window
    # to the training window.
    #------------------------------------------------------------------------------------
    global stop_training
    stop_training = 1

    #Confution Matrix
    #--------------------------------------------------------------------------
    y_pred = model.predict_classes(X_test)
    cm = confusion_matrix(np.argmax(y_test, axis=1), y_pred)
    print(cm)
Exemplo n.º 55
0
def _datetime_to_Qdatetime(date):   
    return QDateTime.fromTime_t(date.timestamp())
Exemplo n.º 56
0
    def __init__(self, parent=None):
        QBuyTicket.__init__(self, parent)
        self.ui = Ui_WindowBuyTicket()
        self.ui.setupUi(self)

        self.luggage_flag = False
        self.food_flag = False
        self.time_is_selected = False

        # buttons
        self.ui.button_back.clicked.connect(
            lambda: self.parent().replace_with(ProfileWindow()))
        self.ui.button_search.clicked.connect(lambda: self.show_answers())
        self.ui.listWidget_seats.itemClicked.connect(self.set_seat)

        # digital clock
        self.timer = QTimer()
        self.timer.timeout.connect(self._update)
        self.timer.start(1000)
        # date
        date = QDateTime.currentDateTime().toString()
        date = re.sub(r'..:.*', '', date)
        self.ui.date_label.setText(date)

        # init comboboxes
        try:
            ConnectionDB.cursor.execute(
                "SELECT DISTINCT departure from flights")
            result = ConnectionDB.cursor.fetchall()
            for departure in result:
                self.ui.comboBox_departure.addItem(str(departure[0]))
            self.ui.comboBox_departure.setCurrentIndex(0)
            Ticket_tb.departure = result[0][0]
            self.ui.comboBox_departure.activated[str].connect(
                Ticket_tb.set_departure)

            ConnectionDB.cursor.execute(
                "SELECT DISTINCT destination from flights")
            result = ConnectionDB.cursor.fetchall()
            for destination in result:
                self.ui.comboBox_destination.addItem(str(destination[0]))
            self.ui.comboBox_destination.setCurrentIndex(0)
            Ticket_tb.destination = result[0][0]
            self.ui.comboBox_destination.activated[str].connect(
                Ticket_tb.set_destination)
        except:
            ConnectionDB.connect.rollback()
            PrintException()

        # add options
        self.ui.checkBox_luggage.toggled.connect(self.set_tariff)
        self.ui.checkBox_food.toggled.connect(self.set_tariff)

        # list of seats id
        self.seats_id = []

        # calendar
        self.time_list = []
        self.ui.calendarWidget.clicked[QDate].connect(self.search_time)

        # list of time
        self.ui.listWidget_times.itemClicked.connect(self.set_flightId_by_time)
Exemplo n.º 57
0
import json

from exmo_api_lib import ExmoAPI
import requests
from PyQt5.QtCore import QDateTime


def api_query_server(method, params):
    requests.post(url='http://127.0.0.1:5000/' + method, json=json.dump(params)).json()


exmo = ExmoAPI()
api_query_server("history_data", {"pair": "BTC_USD", "start_date": QDateTime(2021, 1, 1, 0, 0, 0),
                                       "finish_date": QDateTime().currentDateTime()})
Exemplo n.º 58
0
    def __init__(self):
        super(MyUi, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        # 重定向标准输出stdout
        sys.stdout = emittingStream(textWritten=self.outputWritten)
        # 改变窗体大小并居中
        rect = QApplication.desktop().screenGeometry()
        self.resize(rect.width() - 100, rect.height() - 200)
        size = self.geometry()
        self.move((rect.width() - size.width()) / 2,
                  (rect.height() - size.height()) / 2)
        # 初始化控件
        self.ui.marketComboBox.addItems(mk['name'] for mk in iwencai.MARKET)
        self.ui.marketMethodComboBox.addItems(mt['name']
                                              for mt in iwencai.METHOD)
        self.ui.classifiedMethodComboBox.addItems(mt['name']
                                                  for mt in iwencai.METHOD)

        self.ui.marketSeriesComboBox.addItems(
            st for st in iwencai.STATISTIC_COLUMN)
        self.ui.classifiedSeriesComboBox.addItems(
            st for st in iwencai.STATISTIC_COLUMN)
        self.ui.stockSeriesComboBox.addItems(
            st for st in iwencai.STATISTIC_COLUMN)
        self.ui.classifiedComboBox.addItems(cl
                                            for cl in iwencai.CLASSICFICATION)

        self.ui.basicDataLineEdit.setText(iwencai.BASIC_DATA_DIR)
        self.ui.stockDataLineEdit.setText(iwencai.STOCK_DATA_DIR)
        self.ui.allStockLineEdit.setText(iwencai.ALL_STOCK_FILE)
        self.ui.statisticLineEdit.setText(iwencai.STATISTIC_FILE)
        self.ui.classifiedLineEdit.setText(iwencai.CLASSIFIED_FILE)

        self.ui.startDateEdit.setDateTime(
            QDateTime(QDate(2001, 1, 1), QTime(0, 0, 0)))
        self.ui.endDateEdit.setDateTime(
            QDateTime(QDate(datetime.datetime.now().year, 12, 31),
                      QTime(0, 0, 0)))

        # 设置signal/slot
        self.ui.addMarketSeriesButton.clicked.connect(
            lambda: self.addSeries('M', self.ui.marketComboBox.currentText(),
                                   self.ui.marketMethodComboBox.currentText(),
                                   self.ui.marketSeriesComboBox.currentText()))
        self.ui.addClassifiedSeriesButton.clicked.connect(
            lambda: self.addSeries(
                'C', self.ui.classifiedComboBox.currentText(),
                self.ui.classifiedMethodComboBox.currentText(),
                self.ui.classifiedSeriesComboBox.currentText()))
        self.ui.addStockSeriesButton.clicked.connect(
            lambda: self.addSeries('S', self.ui.stockLineEdit.text(), '值',
                                   self.ui.stockSeriesComboBox.currentText()))

        self.ui.saveButton.clicked.connect(lambda: self.saveSeries())
        self.ui.loadButton.clicked.connect(lambda: self.loadSeries())
        self.ui.deleteButton.clicked.connect(lambda: self.deleteSeries())
        self.ui.generateButton.clicked.connect(lambda: self.generateGraph())

        self.ui.checkButton_1.clicked.connect(
            lambda: self.checkBasicData(self.ui.basicDataLineEdit.text()))
        self.ui.checkButton_2.clicked.connect(
            lambda: self.checkAllStock(self.ui.allStockLineEdit.text()))
        self.ui.checkButton_3.clicked.connect(
            lambda: self.checkStockData(self.ui.stockDataLineEdit.text()))
        self.ui.checkButton_4.clicked.connect(
            lambda: self.checkStatistic(self.ui.statisticLineEdit.text()))
        self.ui.checkButton_5.clicked.connect(
            lambda: self.checkClassified(self.ui.classifiedLineEdit.text()))
        self.ui.bulidButton_1.clicked.connect(lambda: self.buildBasicData())
        self.ui.bulidButton_2.clicked.connect(lambda: self.bulidAllStock())
        self.ui.bulidButton_3.clicked.connect(lambda: self.bulidStockData())
        self.ui.bulidButton_4.clicked.connect(lambda: self.bulidStatistic())
        self.ui.bulidButton_5.clicked.connect(lambda: self.bulidClassified())

        # 加载生成的统计图表
        local_url = QUrl.fromLocalFile(RENDER_FILE)
        self.ui.graphWidget.load(local_url)
Exemplo n.º 59
0
def extractProfileRoastLog(url, _):
    res = {}  # the interpreted data set
    try:
        s = requests.Session()
        s.mount('file://', FileAdapter())
        page = s.get(url.toString(),
                     timeout=(4, 15),
                     headers={"Accept-Encoding": "gzip"})
        tree = html.fromstring(page.content)

        title = ""
        title_elements = tree.xpath('//h2[contains(@id,"page-title")]/text()')
        if len(title_elements) > 0:
            title = title_elements[0].strip()

        tag_values = {}
        for tag in [
                "Roastable:", "Starting mass:", "Ending mass:", "Roasted on:",
                "Roasted by:", "Roaster:", "Roast level:", "Roast Notes:"
        ]:
            tag_elements = tree.xpath(
                '//td[contains(@class,"text-rt") and normalize-space(text())="{}"]/following::td[1]/text()'
                .format(tag))
            if len(tag_elements) > 0:
                tag_values[tag] = "\n".join([e.strip() for e in tag_elements])
        # {'Roastable:': '2003000 Diablo FTO BULK', 'Starting mass:': '140.00 lb', 'Ending mass:': '116.80 lb', 'Roasted on:': 'Thu, Jun 6th, 2019 11:11 PM', 'Roasted by:': '*****@*****.**', 'Roaster:': 'Diedrich CR-70'}

        if "Roasted on:" in tag_values:
            try:
                dt = dateutil.parser.parse(tag_values["Roasted on:"])
                dateQt = QDateTime.fromTime_t(int(round(dt.timestamp())))
                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
            except:
                pass

        w_in = 0
        w_out = 0
        u = "lb"
        if "Starting mass:" in tag_values:
            w_in, u = tag_values["Starting mass:"].strip().split(" ")
        if "Ending mass:" in tag_values:
            w_out, u = tag_values["Ending mass:"].strip().split(" ")
        res["weight"] = [
            float(w_in),
            float(w_out), ("Kg" if u.strip() == "kg" else "lb")
        ]

        if "Roasted by:" in tag_values:
            res["operator"] = tag_values["Roasted by:"]
        if "Roaster:" in tag_values:
            res["roastertype"] = tag_values["Roaster:"]
        if "Roast level:" in tag_values:
            try:
                c = int(round(float(tag_values["Roast level:"])))
                res["ground_color"] = c
            except:
                pass
        if "Roast Notes:" in tag_values:
            res["roastingnotes"] = tag_values["Roast Notes:"]

        if title == "" and "Roastable:" in tag_values:
            title = tag_values["Roastable:"]
        if title != "":
            res["title"] = title

        # if DROP temp > 300 => F else C

        source_elements = tree.xpath('//script[contains(@id,"source")]/text()')
        if len(source_elements) > 0:
            source_element = source_elements[0].strip()

            pattern = re.compile(r"\"rid=(\d+)\"")
            d = pattern.findall(source_element)
            if len(d) > 0:
                rid = d[0]

                url = "https://roastlog.com/roasts/profiles/?rid={}".format(
                    rid)
                headers = {
                    "X-Requested-With": "XMLHttpRequest",
                    "Accept": "application/json",
                    "Accept-Encoding": "gzip"
                }
                response = requests.get(url, timeout=(4, 15), headers=headers)
                data_json = response.json()

                timeindex = [-1, 0, 0, 0, 0, 0, 0, 0]
                specialevents = []
                specialeventstype = []
                specialeventsvalue = []
                specialeventsStrings = []

                if "line_plots" in data_json:
                    mode = "F"
                    timex = []
                    temp1, temp2, temp3, temp4 = [], [], [], []
                    temp3_label = "TC3"
                    temp4_label = "TC4"
                    #                    temp1ror = []
                    for lp in data_json["line_plots"]:
                        if "channel" in lp and "data" in lp:
                            if lp["channel"] == 0:  # BT
                                data = lp["data"]
                                timex = [d[0] / 1000 for d in data]
                                temp1 = [d[1] for d in data]
                            elif lp["channel"] == 1:  # ET
                                temp2 = [d[1] for d in lp["data"]]
                            elif lp["channel"] == 2:  # XT1
                                temp3 = [d[1] for d in lp["data"]]
                                if "label" in lp:
                                    temp3_label = lp["label"]
                            elif lp["channel"] == 3:  # XT2
                                temp4 = [d[1] for d in lp["data"]]
                                if "label" in lp:
                                    temp4_label = lp["label"]
#                            elif lp["channel"] == 4: # BT RoR
#                                temp1ror = [d[1] for d in lp["data"]]
                    res["timex"] = timex
                    if len(timex) == len(temp1):
                        res["temp2"] = temp1
                    else:
                        res["temp2"] = [-1] * len(timex)
                    if len(timex) == len(temp2):
                        res["temp1"] = temp2
                    else:
                        res["temp1"] = [-1] * len(timex)
                    if len(temp3) == len(timex) or len(temp4) == len(timex):
                        temp3_visibility = True
                        temp4_visibility = True
                        # add one (virtual) extra device
                        res["extradevices"] = [25]
                        res["extratimex"] = [timex]
                        if len(temp3) == len(timex):
                            res["extratemp1"] = [temp3]
                        else:
                            res["extratemp1"] = [[-1] * len(timex)]
                            temp3_visibility = False
                        if len(temp4) == len(timex):
                            res["extratemp2"] = [temp4]
                        else:
                            res["extratemp2"] = [[-1] * len(timex)]
                            temp4_visibility = False
                        res["extraname1"] = [temp3_label]
                        res["extraname2"] = [temp4_label]
                        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"] = [False]
                        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']

                timex_events = {
                    "Intro temperature": 0,
                    "yellowing": 1,
                    "Yellow": 1,
                    "DRY": 1,
                    "Dry": 1,
                    "dry": 1,
                    "Dry End": 1,
                    "Start 1st crack": 2,
                    "START 1st": 2,
                    "End 1st crack": 3,
                    "Start 2nd crack": 4,
                    "End 2nd crack": 5,
                    "Drop temperature": 6
                }
                if "table_events" in data_json:
                    for te in data_json["table_events"]:
                        if "label" in te and "time" in te:
                            if te["label"] in timex_events:
                                try:
                                    timex_idx = res["timex"].index(
                                        stringtoseconds(te["time"]))
                                    timeindex[timex_events[te["label"]]] = max(
                                        0, timex_idx)
                                except:
                                    pass
                            else:
                                try:
                                    timex_idx = res["timex"].index(
                                        stringtoseconds(te["time"]))
                                    specialeventsStrings.append(te["label"])
                                    specialevents.append(timex_idx)
                                    specialeventstype.append(4)
                                    specialeventsvalue.append(0)
                                except:
                                    pass
                res["timeindex"] = timeindex

                mode = "F"
                if timeindex[6] != 0 and len(temp1) > timeindex[6] and temp1[
                        timeindex[6]] < 250:
                    mode = "C"
                if timeindex[0] > -1 and len(temp1) > timeindex[0] and temp1[
                        timeindex[0]] < 250:
                    mode = "C"
                res["mode"] = mode

                if len(specialevents) > 0:
                    res["specialevents"] = specialevents
                    res["specialeventstype"] = specialeventstype
                    res["specialeventsvalue"] = specialeventsvalue
                    res["specialeventsStrings"] = specialeventsStrings
    except Exception as e:
        #        import traceback
        #        import sys
        #        traceback.print_exc(file=sys.stdout)
        pass
    return res
Exemplo n.º 60
0
    topItem.addSubProperty(item)

    item = variantManager.addProperty(QVariant.Date, str(i) + " Date Property")
    i += 1
    item.setValue(QDate.currentDate().addDays(2))
    topItem.addSubProperty(item)

    item = variantManager.addProperty(QVariant.Time, str(i) + " Time Property")
    i += 1
    item.setValue(QTime.currentTime())
    topItem.addSubProperty(item)

    item = variantManager.addProperty(QVariant.DateTime,
                                      str(i) + " DateTime Property")
    i += 1
    item.setValue(QDateTime.currentDateTime())
    topItem.addSubProperty(item)

    item = variantManager.addProperty(QVariant.KeySequence,
                                      str(i) + " KeySequence Property")
    i += 1
    item.setValue(QKeySequence(Qt.ControlModifier | Qt.Key_Q))
    topItem.addSubProperty(item)

    item = variantManager.addProperty(QVariant.Char, str(i) + " Char Property")
    i += 1
    item.setValue(chr(386))
    topItem.addSubProperty(item)

    item = variantManager.addProperty(QVariant.Locale,
                                      str(i) + " Locale Property")