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 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)
    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"
    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()
        )
Beispiel #5
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)
Beispiel #6
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()
Beispiel #7
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))
Beispiel #8
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))
Beispiel #9
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)
Beispiel #10
0
    def addItem(self, data):
        hash = createHash(data)
        if self.lastAddedHash == hash:
            return

        self.lastAddedHash = hash

        query = QSqlQuery()
        prepareQuery(query,
            """
            delete from clipboardItems where itemHash = :hash;
            """)
        query.bindValue(':hash', hash)
        executeQuery(query)

        text = data.get(mimeText, '')

        record = self.record()
        record.setValue('itemHash', hash)
        record.setValue('itemText', text)
        record.setValue('itemData', QByteArray(serializeData(data)))
        record.setValue('copyTime', QDateTime.currentDateTime())

        if not self.insertRecord(0, record):
            raise ValueError('Failed to insert item: ' + self.lastError().text())

        self.submitChanges()
 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()
Beispiel #12
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)
Beispiel #13
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
Beispiel #14
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
Beispiel #15
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)
Beispiel #16
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
Beispiel #17
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)
Beispiel #18
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)
Beispiel #19
0
    def __init__(self, target):
        super(LightningStrikesTransition, self).__init__()

        self.setEventSource(self)
        self.setEventType(QEvent.Timer)
        self.setTargetState(target)
        qsrand(QDateTime.currentDateTime().toTime_t())
        self.startTimer(1000)
Beispiel #20
0
 def __init__(self, name, number, maxAmount):
     super(QDialog, self).__init__()
     self.ui = Ui_sellDialog()
     self.ui.setupUi(self)
     self.ui.txtName.setText(str(name))
     self.ui.txtNumber.setText(str(number))
     self.ui.spnAmount.setMaximum(int(maxAmount))
     self.ui.dtimeDate.setDateTime(QDateTime.currentDateTime())
Beispiel #21
0
 def purge_old_cookies(self):
     """Purge expired cookies from the cookie jar."""
     # Based on:
     # http://doc.qt.io/qt-5/qtwebkitexamples-webkitwidgets-browser-cookiejar-cpp.html
     now = QDateTime.currentDateTime()
     cookies = [c for c in self.allCookies()
                if c.isSessionCookie() or c.expirationDate() >= now]
     self.setAllCookies(cookies)
    def save(self):
        defaultFileName = "%s_%s" % (self.chartSelector.currentText(),
                                     QDateTime.currentDateTime().toString('yyyyMMdd'))

        fileName, selectedFilter = getSaveFileName(
            self, 'export_statistics', defaultFileName,
            OpenNumismat.HOME_PATH, self.chart.filters)
        if fileName:
            self.chart.save(fileName, selectedFilter)
Beispiel #23
0
	def __init__(self, id_factura_detalle =int(),id_factura='',id_mantenimiento=int(),
						id_reparacion=int(),registro=''):
		super(invoiceItem, self).__init__()
		self.id_factura_detalle = id_factura_detalle
		self.id_factura = id_factura
		self.id_mantenimiento = id_mantenimiento
		self.id_reparacion = id_reparacion
		self.registro = QDateTime.currentDateTime()
		qDebug('[Debug] se instacia la clase invoiceItem')
 def __hasExpired(self, effectiveDate, expiryDate):
     """
     Private method to check for a certificate expiration.
     
     @param effectiveDate date the certificate becomes effective (QDateTime)
     @param expiryDate date the certificate expires (QDateTime)
     @return flag indicating the expiration status (boolean)
     """
     now = QDateTime.currentDateTime()
     
     return now < effectiveDate or now >= expiryDate
Beispiel #25
0
 def __showErrorMessage(self, message):
     """
     Private slot to show an error message.
     
     @param message error message to show (string)
     """
     color = self.chatEdit.textColor()
     self.chatEdit.setTextColor(Qt.red)
     self.chatEdit.append(QDateTime.currentDateTime().toString(Qt.SystemLocaleLongDate) + ":")
     self.chatEdit.append(message + "\n")
     self.chatEdit.setTextColor(color)
Beispiel #26
0
    def __banKickUser(self):
        """
        Private slot to ban and kick a user.
        """
        itm = self.usersList.currentItem()
        self.__client.banKickUser(itm.text())

        color = self.chatEdit.textColor()
        self.chatEdit.setTextColor(Qt.darkYellow)
        self.chatEdit.append(QDateTime.currentDateTime().toString(Qt.SystemLocaleLongDate) + ":")
        self.chatEdit.append(self.tr("* {0} has been banned and kicked.\n").format(itm.text().split("@")[0]))
        self.chatEdit.setTextColor(color)
Beispiel #27
0
 def add_file(self, _type, on_added, object_properties = None, name = None, bare_name = None):
     file_path = self.file_path(_type, name=name, bare_name = bare_name, object_properties = object_properties)
     files = [f for f in self.__get_files(_type, full_path = False) if f[1] != file_path]
     files.append((QDateTime.currentDateTime(), os.path.basename(file_path)))
     
     self.data[_type] = sorted(files, key=lambda o: o[0], reverse=True)
     self.save()
     on_added(file_path)
     name = fits.getheader(file_path).get('OBJECT', os.path.basename(file_path))
     Notification('File {} saved in {}/{}'.format(name, self.get_name(), _type), title='File Saved', type='success', timeout=5)
     self.filesChanged.emit()
     return file_path
Beispiel #28
0
 def __init__(self, cookieJar, parent=None):
     """
     Constructor
     
     @param cookieJar reference to the cookie jar (CookieJar)
     @param parent reference to the parent widget (QWidget)
     """
     super(CookiesDialog, self).__init__(parent)
     self.setupUi(self)
     
     self.addButton.setEnabled(False)
     
     self.__cookieJar = cookieJar
     
     self.removeButton.clicked.connect(self.cookiesTable.removeSelected)
     self.removeAllButton.clicked.connect(self.cookiesTable.removeAll)
     
     self.cookiesTable.verticalHeader().hide()
     model = CookieModel(cookieJar, self)
     self.__proxyModel = QSortFilterProxyModel(self)
     self.__proxyModel.setSourceModel(model)
     self.searchEdit.textChanged.connect(
         self.__proxyModel.setFilterFixedString)
     self.cookiesTable.setModel(self.__proxyModel)
     self.cookiesTable.doubleClicked.connect(self.__showCookieDetails)
     self.cookiesTable.selectionModel().selectionChanged.connect(
         self.__tableSelectionChanged)
     self.cookiesTable.model().modelReset.connect(self.__tableModelReset)
     
     fm = QFontMetrics(QFont())
     height = fm.height() + fm.height() // 3
     self.cookiesTable.verticalHeader().setDefaultSectionSize(height)
     self.cookiesTable.verticalHeader().setMinimumSectionSize(-1)
     for section in range(model.columnCount()):
         header = self.cookiesTable.horizontalHeader()\
             .sectionSizeHint(section)
         if section == 0:
             header = fm.width("averagebiglonghost.averagedomain.info")
         elif section == 1:
             header = fm.width("_session_id")
         elif section == 4:
             header = fm.width(
                 QDateTime.currentDateTime().toString(Qt.LocalDate))
         buffer = fm.width("mm")
         header += buffer
         self.cookiesTable.horizontalHeader().resizeSection(section, header)
     self.cookiesTable.horizontalHeader().setStretchLastSection(True)
     self.cookiesTable.model().sort(
         self.cookiesTable.horizontalHeader().sortIndicatorSection(),
         Qt.AscendingOrder)
     
     self.__detailsDialog = None
Beispiel #29
0
 def __rulesDownloaded(self):
     """
     Private slot to deal with the downloaded rules.
     """
     reply = self.sender()
     
     response = reply.readAll()
     reply.close()
     self.__downloading = None
     
     if reply.error() != QNetworkReply.NoError:
         if not self.__defaultSubscription:
             # don't show error if we try to load the default
             E5MessageBox.warning(
                 None,
                 self.tr("Downloading subscription rules"),
                 self.tr(
                     """<p>Subscription rules could not be"""
                     """ downloaded.</p><p>Error: {0}</p>""")
                 .format(reply.errorString()))
         else:
             # reset after first download attempt
             self.__defaultSubscription = False
         return
     
     if response.isEmpty():
         E5MessageBox.warning(
             None,
             self.tr("Downloading subscription rules"),
             self.tr("""Got empty subscription rules."""))
         return
     
     fileName = self.rulesFileName()
     QFile.remove(fileName)
     f = QFile(fileName)
     if not f.open(QIODevice.ReadWrite):
         E5MessageBox.warning(
             None,
             self.tr("Downloading subscription rules"),
             self.tr(
                 """Unable to open adblock file '{0}' for writing.""")
             .file(fileName))
         return
     f.write(response)
     f.close()
     self.__lastUpdate = QDateTime.currentDateTime()
     if self.__validateCheckSum(fileName):
         self.__loadRules()
     else:
         QFile.remove(fileName)
     self.__downloading = None
     reply.deleteLater()
Beispiel #30
0
	def __init__(self,id_inspeccion=int(),id_vehiculo='',id_tecnico='',
				id_contacto=int(),id_ciudad=int(),periodo=int(),fecha='',notas='',registro=''):
		super(Inspection, self).__init__()
		self.id_inspeccion = id_inspeccion
		self.id_vehiculo = id_vehiculo
		self.id_tecnico = id_tecnico
		self.id_contacto = id_contacto
		self.id_ciudad = id_ciudad
		self.periodo = periodo
		self.fecha = QDate().currentDate()
		self.notas = notas
		self.registro = QDateTime.currentDateTime()
		qDebug('[Debug] se inicia la clase inspection')
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import QDate, QTime, QDateTime, Qt
from PyQt5.QtWidgets import QMessageBox
from datetime import date
import requests, json


def getBitcoinPrice():
    URL = 'https://www.bitstamp.net/api/ticker/'
    r = requests.get(URL)
    priceFloat = float(json.loads(r.text)['last'])
    return priceFloat


cbcp = getBitcoinPrice()
datnow = QDateTime.currentDateTime().addDays(7)


class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(541, 460)
        self.label_a = QtWidgets.QLabel(Dialog)
        self.label_a.setObjectName("label_a")
        self.label_a.setGeometry(QtCore.QRect(6, 165, 10, 10))
        self.label_b = QtWidgets.QLabel(Dialog)
        self.label_b.setObjectName("label_b")
        self.label_b.setGeometry(QtCore.QRect(6, 235, 10, 10))
        self.label_c = QtWidgets.QLabel(Dialog)
        self.label_c.setObjectName("label_c")
        self.label_c.setGeometry(QtCore.QRect(6, 304, 10, 10))
Beispiel #32
0
	def setDisplayLabel(self):
		self.datetime4display = QDateTime.currentDateTime().toString()
Beispiel #33
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"))
Beispiel #34
0
 def Qtimewidget(self):
     self.currentDateTime = QDateTime.currentDateTime()
     self.dateTimeEdit.setDateTime(self.currentDateTime)
     self.dateTimeEdit.repaint()
Beispiel #35
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"
            )
Beispiel #36
0
def systime():
    now = QDateTime.currentDateTime()
    systime = now.toString("yyyyMMddhhmmss.zz")
    return systime
Beispiel #37
0
def time():
    datetime = QDateTime.currentDateTime()
    win.statusbar.showMessage(datetime.toString('dd.MM.yyyy, hh:mm:ss.zzz'))
    timer.start()
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtCore import QDate, QTime, QDateTime, Qt
from PyQt5.QtWidgets import QApplication, QWidget


if __name__ == '__main__':
    
    app = QApplication(sys.argv)
    
    w = QWidget()
    w.resize(250,150)
    w.move(100,100)
    w.setWindowTitle('simple test')
    w.show()
    
    now = QDateTime.currentDateTime()

    print(now.toString(Qt.ISODate))
    print(now.toString(Qt.DefaultLocaleLongDate))
    
    sys.exit(app.exec_())




Beispiel #39
0
 def showCurrTime(self):
     datetime = QDateTime.currentDateTime()
     self.timeLabel.setText("     " + datetime.toString())
Beispiel #40
0
 def add_log(self):
     with open(self.app.LOG_ADMIN_FILENAME, 'a') as f:
         f.write(QDateTime.currentDateTime().toString(date_time_format()))
         f.write('\n')
     self.fill_log()
Beispiel #41
0
 def run(self):
     while True:
         data = QDateTime.currentDateTime()
         self.update_date.emit(str(data))
         time.sleep(1)
Beispiel #42
0
 def run(self):
     while True:
         data = QDateTime.currentDateTime()
         currTime = data.toString("yyyy-MM-dd hh:mm:ss")
         self.update_date.emit(str(currTime))
         time.sleep(1)
Beispiel #43
0
 def flush(self):
     # 获取系统当前时间
     dateTime = QDateTime.currentDateTime()
     # 显示的内容
     self.lcd.display(dateTime.toString("yyyy-MM-dd HH:mm:ss.zzz"))
 def startTimer(self):
     self.start_time = QDateTime.currentDateTime()
     self.running = True
     self.last_duration = 0
     self.timer.start(53)
Beispiel #45
0
def sysdate():
    now = QDateTime.currentDateTime()
    sysdate = now.toString("yyyyMMdd")
    return sysdate
def mux_process():
    cur_date_time = QDateTime.currentDateTime()
    epoch_time = cur_date_time.toMSecsSinceEpoch()

    # DEBUG info
    #dprint("thread: %s" % QtCore.QThread.currentThread().objectName())

    if mux_pyqt.is_MUX_scanning:
        readings = mux.state.readings

        for i in range(N_channels):
            if readings[i] > 9.8e37:
                readings[i] = np.nan
    else:
        # Multiplexer is not scanning. No readings available
        readings = [np.nan] * N_channels
        mux.state.readings = readings

    # Add readings to charts
    for i in range(N_channels):
        window.CHs_mux[i].add_new_reading(epoch_time, readings[i])

    # UGLY HACK: put in Polyscience temperature bath and PT104 update here
    bath.query_P1_temp()
    #bath.query_P2_temp()  # External probe
    window.CH_P1_temp.add_new_reading(epoch_time, bath.state.P1_temp)
    window.CH_P2_temp.add_new_reading(epoch_time, bath.state.P2_temp)
    window.CH_PT104_ch1_T.add_new_reading(epoch_time, pt104.state.ch1_T)

    # ----------------------------------------------------------------------
    #   Logging to file
    # ----------------------------------------------------------------------

    if file_logger.starting:
        fn_log = ("d:/data/calib_thermistors_" +
                  cur_date_time.toString("yyMMdd_HHmmss") + ".txt")
        if file_logger.create_log(epoch_time, fn_log, mode='w'):
            file_logger.signal_set_recording_text.emit("Recording to file: " +
                                                       fn_log)

            # Header
            file_logger.write("time[s]\t")
            file_logger.write("P1_temp[degC]\t")
            file_logger.write("P2_temp[degC]\t")
            file_logger.write("PT104_Ch1[degC]\t")
            for i in range(N_channels - 1):
                file_logger.write("CH%s\t" %
                                  mux.state.all_scan_list_channels[i])
            file_logger.write("CH%s\n" % mux.state.all_scan_list_channels[-1])

    if file_logger.stopping:
        file_logger.signal_set_recording_text.emit(
            "Click to start recording to file")
        file_logger.close_log()

    if file_logger.is_recording:
        log_elapsed_time = (epoch_time - file_logger.start_time) / 1e3  # [sec]

        # Add new data to the log
        file_logger.write("%.3f\t" % log_elapsed_time)
        file_logger.write("%.2f\t" % bath.state.P1_temp)
        file_logger.write("%.2f\t" % bath.state.P2_temp)
        file_logger.write("%.3f" % pt104.state.ch1_T)
        for i in range(N_channels):
            if len(mux.state.readings) <= i:
                file_logger.write("\t%.5e" % np.nan)
            else:
                file_logger.write("\t%.5e" % mux.state.readings[i])
        file_logger.write("\n")
Beispiel #47
0
def systimeonly():
    now = QDateTime.currentDateTime()
    systo = now.toString("hhmmss.zz")
    return systo
Beispiel #48
0
 def setToday(self):
     today = QDateTime.currentDateTime()
     today.setTime(self.te_datetime.time())
     self.te_datetime.setDateTime(today)
Beispiel #49
0
 def appendData(self, currPirce):
     if len(self.priceData) == self.viewLimit:
         self.priceData.remove(0)
     dt = QDateTime.currentDateTime()
     self.priceData.append(dt.toMSecsSinceEpoch(), currPirce)
     self.__updateAxis()
    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"
Beispiel #51
0
Datei: gui.py Projekt: RMDE/DBMS
 def show_time(self):
     time = QDateTime.currentDateTime()
     timeDisplay = time.toString("yyyy-MM-dd dddd hh:mm:ss ")
     self.lbl.setText("当前时间" + timeDisplay)
Beispiel #52
0
#!/usr/bin/python

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))
Beispiel #53
0
    def initUi(self):
        #self.setWindowFlags(Qt.WindowCloseButtonHint && Qt.WindowMinimizeButtonHint)
        #self.setWindowFlags(Qt.WindowMinimizeButtonHint)
        self.setWindowTitle('火车票查询系统')
        #self.setGeometry(40,80,1500,720)
        #第一部分,输入出发地、目的地和日期
        controlsLayout = QGridLayout()  #栅格布局
        self.label1 = QLabel("出发地:")
        self.Editlabel1 = QLineEdit()
        self.label2 = QLabel("目的地:")
        self.Editlabel2 = QLineEdit()
        self.label3 = QLabel("乘车日期:")

        self.Editlabel3 = QDateTimeEdit()
        now = QDateTime.currentDateTime()
        #print(now)
        self.Editlabel3.setDateTime(now)
        self.Editlabel3.setDisplayFormat("yyyy-MM-dd")  #小写m为分钟
        self.Editlabel3.setCalendarPopup(True)

        self.buttonOK = QPushButton("确定")

        controlsLayout.addWidget(QLabel(""), 0, 0, 1, 6)
        self.message = QLabel("暂未查询车次信息!")
        controlsLayout.addWidget(self.message, 0, 7, 1, 4)

        controlsLayout.addWidget(self.label1, 0, 11, 1, 1)
        controlsLayout.addWidget(self.Editlabel1, 0, 12, 1, 2)
        controlsLayout.addWidget(QLabel(" "), 0, 14, 1, 1)

        controlsLayout.addWidget(self.label2, 0, 15, 1, 1)
        controlsLayout.addWidget(self.Editlabel2, 0, 16, 1, 2)
        controlsLayout.addWidget(QLabel(" "), 0, 18, 1, 1)

        controlsLayout.addWidget(self.label3, 0, 19, 1, 1)
        controlsLayout.addWidget(self.Editlabel3, 0, 20, 1, 2)
        controlsLayout.addWidget(QLabel(" "), 0, 22, 1, 1)

        controlsLayout.addWidget(self.buttonOK, 0, 23, 1, 1)
        controlsLayout.addWidget(QLabel(" "), 0, 25, 1, 8)

        #第二部分,显示查询到的车次信息
        horizontalHeader = [
            "车次", "车站", "时间", "历时", "商务座", "一等座", "二等座", "高级软卧", "软卧", "动卧",
            "硬卧", "软座", "硬座", "无座", "其他"
        ]
        self.table = QTableWidget()
        self.table.setColumnCount(15)
        self.table.setRowCount(0)  #初始化为0行
        self.table.setHorizontalHeaderLabels(horizontalHeader)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)  #不能编辑
        self.table.setSelectionBehavior(QTableWidget.SelectRows)  #选中整行
        self.table.setSelectionMode(QTableWidget.SingleSelection)
        for index in range(self.table.columnCount()):
            headItem = self.table.horizontalHeaderItem(index)
            headItem.setFont(QFont("song", 12, QFont.Bold))
            headItem.setForeground(QBrush(Qt.gray))
            headItem.setTextAlignment(Qt.AlignCenter | Qt.AlignVCenter)
        #self.table.setFrameShape(QFrame.HLine)#设定样式
        #self.table.setShowGrid(False) #取消网格线
        #self.table.verticalHeader().setVisible(False) #隐藏垂直表头
        #row_count = self.table.rowCount()
        #self.table.setColumnWidth(0,200)
        mainLayout = QHBoxLayout()
        mainLayout.addWidget(self.table)
        layout = QVBoxLayout()
        layout.addLayout(controlsLayout)
        layout.addLayout(mainLayout)
        self.setLayout(layout)
        self.buttonOK.clicked.connect(self.showMessage)
        self.showMaximized()
Beispiel #54
0
 def __init__(self, parent=None):
     QDateTimeEdit.__init__(self, parent)
     self.setMinimumDateTime(datetime.fromtimestamp(self.min_allowed_value))
     self.setMaximumDateTime(datetime.fromtimestamp(self.max_allowed_value))
     self.setDateTime(QDateTime.currentDateTime())
Beispiel #55
0
 def getDateTime(self):
         return QDateTime.currentDateTime().toString(Qt.ISODate)
Beispiel #56
0
 def updtTime(self):
     currentTime = QDateTime.currentDateTime().toString('hh:mm:ss')
     self.testTimeDisplay.display(currentTime)
Beispiel #57
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)
Beispiel #58
0
def systimef():
    now = QDateTime.currentDateTime()
    systime = now.toString("yyyy/MM/dd hh:mm:ss.zz")
    return systime
Beispiel #59
0
 def displayTime(self):
     self.timeStatus.setText(QDateTime.currentDateTime().toString())
 def calcDuration(self) -> (QDateTime, int):
     self.stop_time = QDateTime.currentDateTime()
     duration = self.start_time.msecsTo(self.stop_time)
     return self.curr_time.addMSecs(duration), duration