コード例 #1
0
ファイル: editor_search.py プロジェクト: hydrargyrum/eye
    def _searchBatch(self, needOne=False):
        with self.safeBatch():
            start_time = QElapsedTimer()
            start_time.start()

            for self.start_line in range(self.start_line, self.editor.lines()):
                if not needOne and start_time.hasExpired(10):
                    return

                matched = self.searchInLine(self.start_line)
                if matched:
                    needOne = False

            self.timer.stop()
            self.finished.emit(0)
コード例 #2
0
ファイル: etags.py プロジェクト: hydrargyrum/eye
    def _batchLoad(self):
        with self.safeBatch():
            duration = QElapsedTimer()
            duration.start()

            for taginfo in self.parsing:
                self.db.add_tag(taginfo)

                if duration.hasExpired(10):
                    return

            CACHE.addConf(self.parser.path, self.db)
            self.timer.stop()

            LOGGER.debug('db %r has finished loading', self.parser.path)
            self.searchInDb(self.request)
コード例 #3
0
    def __init__(self, font_size=100, debug=False):

        super().__init__(font_size=font_size)

        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.setAlignment(Qt.AlignCenter)

        self.speed = False
        self.seconds = 0.0
        self._elapsed_time = QElapsedTimer()
        self._timer = QTimer(self, interval=100, timeout=self._update)
        self._timer.timeout.connect(self._update)
        self._timer.start()

        if debug:
            self.setFrameStyle(QFrame.Box | QFrame.Raised)
コード例 #4
0
	def crawlBatch(self):
		start_time = QElapsedTimer()
		start_time.start()
		prefix_len = len(self.root) + 1 # 1 for the /

		for path in self.crawler:
			subpath = path[prefix_len:]

			qitem = QStandardItem(subpath)
			qitem.setData(path, AbsolutePathRole)
			qitem.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
			self.mdl.appendRow(qitem)

			if start_time.hasExpired(self.maxSecsPerCrawlBatch * 1000):
				self.crawlTimer.start(0)
				break
コード例 #5
0
ファイル: main.py プロジェクト: lauracavaliere/appsAway
    def startProgressBar(self):
        global PAUSED
        self.pushStartButton.setEnabled(False)
        self.pushStopButton.setEnabled(False)

        for buttonOption in self.button_list:
            if buttonOption.button != None:
                buttonOption.button.setEnabled(False)
            if buttonOption.inputBox != None:
                buttonOption.inputBox.setEnabled(False)

        PAUSED = False

        elapsedTime = QElapsedTimer()
        elapsedTime.start()

        self.startApplication()
コード例 #6
0
def _wait_for_clipboard(qtbot, clipboard, mode, expected):
    timeout = 1000
    timer = QElapsedTimer()
    timer.start()

    while True:
        if clipboard.text(mode=mode) == expected:
            return
        with qtbot.waitSignal(clipboard.changed, timeout=timeout) as blocker:
            pass
        if not blocker.signal_triggered or timer.hasExpired(timeout):
            mode_names = {
                QClipboard.Clipboard: 'clipboard',
                QClipboard.Selection: 'primary selection',
            }
            raise WaitForTimeout(
                "Timed out after {}ms waiting for {} in {}.".format(
                    timeout, expected, mode_names[mode]))
コード例 #7
0
    def __init__(self, parent=None):
        super(TimerThree, self).__init__(parent)

        self.setObjectName("TimerThree")
        self.setWindowTitle("TimerThree")
        self.resize(651, 413)

        self.timer_lcd = QtWidgets.QLCDNumber(self)
        # timer_lcd.setGeometry(QtCore.QRect(30, 30, 591, 211))
        self.timer_lcd.setObjectName("timer_lcd")
        self.timer_lcd.setSegmentStyle(QLCDNumber.Filled)

        self.isStarted = False
        self.isPaused = False

        start_stop_button = QPushButton("&Start/Stop")
        # start_stop_button.setGeometry(QtCore.QRect(30, 280, 281, 91))
        font = QtGui.QFont()
        font.setPointSize(18)
        start_stop_button.setFont(font)
        start_stop_button.setObjectName("start_stop_button")
        start_stop_button.setFocusPolicy(Qt.NoFocus)

        pause_button = QPushButton("Pause")
        # pause_button.setGeometry(QtCore.QRect(340, 280, 281, 91))
        font = QtGui.QFont()
        font.setPointSize(18)
        pause_button.setFont(font)
        pause_button.setObjectName("pause_button")
        pause_button.setFocusPolicy(Qt.NoFocus)

        main_layout = QGridLayout()
        # main_layout.setSizeConstraint(QLayout.SetFixedSize) # Cannot resize.
        main_layout.addWidget(start_stop_button, 2, 0)
        main_layout.addWidget(pause_button, 2, 1)
        main_layout.addWidget(self.timer_lcd, 1, 0, 1, 2)
        self.setLayout(main_layout)

        self.timer = QTimer()
        # start_stop_button.clicked.connect(self.basic_countdown())
        start_stop_button.clicked.connect(self.timer_start)
        self.el_timer = QElapsedTimer()
        pause_button.clicked.connect(self.timer_pause)
コード例 #8
0
    def __init__(self, parent=None, title=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        self.setWindowTitle(title)

        # Load Map texture
        img = Image.open(mapTexture).convert("RGBA")

        # Create the WebGPU draw function and initialize GPU
        self.drawFunction = get_draw_function(self, img)

        self.request_draw(self.mainloop)  # Updates on resize / redraw

        # Set timer to update every frame
        self.timer = QTimer()
        self.timer.timeout.connect(self.mainloop)
        self.timer.start(math.floor(1000 / FPS))

        self.timing = QElapsedTimer()
        self.timing.start()
        self.oldTime = 0
コード例 #9
0
    def startProgressBar(self):
        global PAUSED
        self.pushStartButton.setEnabled(False)
        self.pushStopButton.setEnabled(False)

        for buttonOption in self.button_list:
            if buttonOption.button != None:
                buttonOption.button.setEnabled(False)
            if buttonOption.inputBox != None:
                buttonOption.inputBox.setEnabled(False)

        PAUSED = False

        elapsedTime = QElapsedTimer()
        elapsedTime.start()

        self.startApplication()
        os.chdir(
            os.path.join(os.environ.get('HOME'), "teamcode", "appsAway",
                         "scripts"))
        rc = subprocess.call("./appsAway_setEnvironment.local.sh")
コード例 #10
0
    def __init__(self, idRoom):
        super(RoomRow, self).__init__()
        self.setStyleSheet(
            'QFrame {background: #757575; border-radius: 10px; margin: 0px}')
        self.setFixedHeight(50)

        self.callModel = service.CallModel()

        self.elapsedTimer = QElapsedTimer()
        self.elapsedTimer.start()
        self.timerSingle = QTimer()
        self.timerSingle.setSingleShot(True)
        self.timerSingle.timeout.connect(self.deactivateBlink)

        self.timer = QTimer()
        self.timer.timeout.connect(self.blink)
        self.stopwatch = QTimer()
        self.stopwatch.timeout.connect(self.updateStopwatch)

        self.types = {
            'azul': '#0d47a1',
            'normal': '#00e676',
            'bano': '#fdd835'
        }
        self.flagBlink = True
        self.isActive = False
        self.callType = None

        self.room = QLabel(idRoom)
        self.room.setStyleSheet('font: 25px; color: white')
        self.room.setAlignment(Qt.AlignCenter)
        self.timePassed = QLabel('—')
        self.timePassed.setStyleSheet('color: white')
        self.timePassed.setFont(QFont('DS-Digital', 25))
        self.timePassed.setAlignment(Qt.AlignCenter)

        hbox = QHBoxLayout(self)
        hbox.addWidget(self.room)
        hbox.addWidget(self.timePassed)
コード例 #11
0
    def slot_batch_resize(self):
        dialog = QDialog()
        dialog.setWindowTitle(i18n("Resize all Pages"))
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(dialog.accept)
        buttons.rejected.connect(dialog.reject)
        sizesBox = comics_export_dialog.comic_export_resize_widget("Scale", batch=True, fileType=False)
        exporterSizes = comics_exporter.sizesCalculator()
        dialog.setLayout(QVBoxLayout())
        dialog.layout().addWidget(sizesBox)
        dialog.layout().addWidget(buttons)

        if dialog.exec_() == QDialog.Accepted:
            progress = QProgressDialog(i18n("Resizing pages..."), str(), 0, len(self.setupDictionary["pages"]))
            progress.setWindowTitle(i18n("Resizing Pages"))
            progress.setCancelButton(None)
            timer = QElapsedTimer()
            timer.start()
            config = {}
            config = sizesBox.get_config(config)
            for p in range(len(self.setupDictionary["pages"])):
                absoluteUrl = os.path.join(self.projecturl, self.setupDictionary["pages"][p])
                progress.setValue(p)
                timePassed = timer.elapsed()
                if (p > 0):
                    timeEstimated = (len(self.setupDictionary["pages"]) - p) * (timePassed / p)
                    passedString = str(int(timePassed / 60000)) + ":" + format(int(timePassed / 1000), "02d") + ":" + format(timePassed % 1000, "03d")
                    estimatedString = str(int(timeEstimated / 60000)) + ":" + format(int(timeEstimated / 1000), "02d") + ":" + format(int(timeEstimated % 1000), "03d")
                    progress.setLabelText(str(i18n("{pages} of {pagesTotal} done. \nTime passed: {passedString}:\n Estimated:{estimated}")).format(pages=p, pagesTotal=len(self.setupDictionary["pages"]), passedString=passedString, estimated=estimatedString))
                    qApp.processEvents()
                if os.path.exists(absoluteUrl):
                    doc = Application.openDocument(absoluteUrl)
                    listScales = exporterSizes.get_scale_from_resize_config(config["Scale"], [doc.width(), doc.height(), doc.resolution(), doc.resolution()])
                    doc.scaleImage(listScales[0], listScales[1], listScales[2], listScales[3], "bicubic")
                    doc.waitForDone()
                    doc.save()
                    doc.waitForDone()
                    doc.close()
コード例 #12
0
    def __init__(self, parent):
        super().__init__(parent)
        self.setFocusPolicy(Qt.StrongFocus)

        # Init data
        self._font = QFont('Serif', 14, QFont.Light)
        self._fpsTimer = QElapsedTimer()
        self._frameCount = 0
        self._fps = 0
        self._fpsTimer.start()
        self._camera = Camera()
        self._displayFrameRate = False
        self._cosmeticProperties = None
        self._environment = None
        self._cartShape = CartPoleShape()
        self._axisPlot = AxesPlot(rect=QRectF(-1, 0, 2, 0),
                                  axisX=True,
                                  axisY=False,
                                  pen=QPen(Qt.blue, 0),
                                  font=self._font,
                                  ticks=11,
                                  tickHeight=20)
        self.setEnabled(False)
コード例 #13
0
ファイル: test_track.py プロジェクト: triad7th/pyprone
from time import sleep
from PyQt5.QtCore import QTimer, QElapsedTimer
from PyQt5.QtWidgets import QApplication

from pyprone.entities.midifile import PrMidiFile
from pyprone.entities.midifile.track import PrMidiTrack
from pyprone.core.helpers.formats import sec2HMSF, tick2MBT, MBT2tick, tempo2bpm
from mido import open_output

midifile = PrMidiFile('midifile')
midifile.load('./pyprone/resources/midifiles/a-whole-new-world.mid')
port = open_output('Microsoft GS Wavetable Synth 0')

etimer = QElapsedTimer()
etimerT = QElapsedTimer()

etimerT.start()
for track in midifile.tracks:
    etimer.start()
    for t in track:
        pass
    print(f'{track.no} : {etimer.elapsed()}')

print(f'total elapsed : {etimerT.elapsed()}')

midifile.tracks[0].rewind(MBT2tick(7, 1, 0, midifile.tpb))
print(midifile.tracks[0])
print(midifile.tracks[0].idx)
print(midifile.tracks[0].msg)
コード例 #14
0
class NotificationLayout(QObject):
    displayTimeMs = 2000
    maximumDisplayCount = 5
    elapsedTimer = QElapsedTimer()
    basicTimer = QBasicTimer()
    layoutType = Qt.AlignTop | Qt.AlignRight
    notifications = {}

    def __init__(self, *args, **kwargs):
        super(NotificationLayout, self).__init__(*args, **kwargs)

        self.basicTimer.start(600, self)

    def destroyed(self, object=...) -> None:
        self.Clear()

    def AddNotificationWidget(self, parent, params):
        if not parent:
            desktop = QApplication.desktop()
            desktop.setGeometry(desktop.availableGeometry())
            parent = desktop
        if self.notifications.__contains__(parent):
            parent.installEventFilter(self)
            parent.destroyed.connect(self.OnParentWidgetDestroyed)

        widget = NotificationWidget(parent, params=params)
        widget.CloseButtonClicked.connect(self.OnCloseClicked)
        widget.DetailsButtonClicked.connect(self.OnDetailsClicked)
        widget.destroyed.connect(self.OnWidgetDestroyed)

        widgetParams = params
        widgetParams.InitAnimation(widget)

        widgetParams.callback = params.callback
        widgetParams.remainTimeMs = self.displayTimeMs

        if not self.notifications.__contains__(parent):
            self.notifications[parent] = []
        self.notifications[parent].append((widget, widgetParams))

        self.LayoutWidgets(parent)

    def LayoutWidgets(self, parent):
        totalHeight = 0
        widgets = self.notifications[parent]

        size = min(len(widgets), self.maximumDisplayCount)
        widgetsToDisplay = widgets[:size]
        if self.layoutType & Qt.AlignTop:
            widgetsToDisplay.reverse()
        for pair in widgetsToDisplay:
            widget = pair[0]
            justCreated = False
            if widget.isVisible() == False:
                justCreated = True
                opacityAnimation = pair[1].opacityAnimation
                widget.show()
                opacityAnimation.setStartValue(0.0)
                opacityAnimation.setEndValue(1.0)
                opacityAnimation.start()

            x = 0 if self.layoutType & Qt.AlignLeft else (parent.width() -
                                                          widget.width())
            y = totalHeight if self.layoutType & Qt.AlignTop else parent.height(
            ) - widget.height() - totalHeight
            widgetPos = QPoint(x, y)

            # noticationWidget marked as window inside Qt, self case we need to use global coordinates
            # if not mark it as window - on OS X notification will be behind from RenderWidget

            widgetPos = parent.mapToGlobal(widgetPos)

            if justCreated:
                widget.move(widgetPos)
            else:
                positionAnimation = pair[1].positionAnimation
                positionAnimation.stop()
                positionAnimation.setStartValue(widget.pos())
                positionAnimation.setEndValue(widgetPos)
                positionAnimation.start()

            totalHeight += widget.size().height()

    def Clear(self):
        for widgets in self.notifications:
            for pair in widgets:
                widget = pair[0]
                widget.close()
                widget.setParent(None)

        self.notifications.clear()

    def eventFilter(self, sender, event):
        type = event.type()
        if type == QEvent.Resize or type == QEvent.Move:
            self.LayoutWidgets(sender)

        return QObject.eventFilter(self, sender, event)

    def timerEvent(self, event):
        elapsedMs = self.elapsedTimer.restart()
        for parent in self.notifications:
            widgets = self.notifications[parent]
            if parent.isActiveWindow() or isinstance(parent, QDesktopWidget):
                for pair in widgets:
                    widget = pair[0]
                    params = pair[1]
                    params.DecrementTime(elapsedMs)
                    if params.remainTimeMs == 0:
                        widget.setParent(None)
                        widget.close()
                        widgets.remove(pair)
                self.LayoutWidgets(parent)
                return

    def SetLayoutType(self, type):
        if self.layoutType == type:
            return

        self.layoutType = type

        # now remove all notifications
        self.Clear()

    def SetDisplayTimeMs(self, displayTimeMs_):
        self.displayTimeMs = displayTimeMs_

    def OnCloseClicked(self, notification):
        notification.setParent(None)
        for parent in self.notifications:
            widgets = self.notifications[parent]
            for pair in widgets:
                if pair[0] == notification:
                    widgets.remove(pair)
                    notification.close()
                    self.LayoutWidgets(parent)
                    return

    def OnDetailsClicked(self, notification):
        parent = notification.parentWidget()
        widgets = self.notifications[parent]

        for pair in widgets:
            if pair[0] == notification:
                pair[1].callback()
                break

        del notification

    def OnWidgetDestroyed(self):
        notification = self.sender()
        for parent in self.notifications:
            widgets = self.notifications[parent]
            _notification = None
            for pair in widgets:
                if pair[0] == notification:
                    _notification = pair[0]
                    break
            if _notification:
                self.LayoutWidgets(parent)
                return

    def OnParentWidgetDestroyed(self):
        senderWidget = self.sender()
        if self.notifications.__contains__(senderWidget):
            del self.notifications[senderWidget]
コード例 #15
0
    def save_out_pngs(self, sizesList):
        # A small fix to ensure crop to guides is set.
        if "cropToGuides" not in self.configDictionary.keys():
            self.configDictionary["cropToGuides"] = False

        # Check if we have pages at all...
        if "pages" in self.configDictionary.keys():

            # Check if there's export methods, and if so make sure the appropriate dictionaries are initialised.
            if len(sizesList.keys()) < 1:
                print(
                    "CPMT: Export failed because there's no export methods set."
                )
                return False
            else:
                for key in sizesList.keys():
                    self.pagesLocationList[key] = []

            # Get the appropriate paths.
            path = Path(self.projectURL)
            exportPath = path / self.configDictionary["exportLocation"]
            pagesList = self.configDictionary["pages"]
            fileName = str(exportPath)

            # Create a progress dialog.
            progress = QProgressDialog("Preparing export.", str(), 0,
                                       len(pagesList))
            progress.setWindowTitle("Exporting comic...")
            progress.setCancelButton(None)
            timer = QElapsedTimer()
            timer.start()
            progress.show()
            qApp.processEvents()

            for p in range(0, len(pagesList)):

                # Update the label in the progress dialog.
                progress.setValue(p)
                timePassed = timer.elapsed()
                if (p > 0):
                    timeEstimated = (len(pagesList) - p) * (timePassed / p)
                    passedString = str(int(timePassed / 60000)) + ":" + format(
                        int(timePassed / 1000), "02d") + ":" + format(
                            timePassed % 1000, "03d")
                    estimatedString = str(int(
                        timeEstimated / 60000)) + ":" + format(
                            int(timeEstimated / 1000), "02d") + ":" + format(
                                int(timeEstimated % 1000), "03d")
                    progress.setLabelText(
                        str(
                            i18n(
                                "{pages} of {pagesTotal} done. \nTime passed: {passedString}:\n Estimated:{estimated}"
                            )).format(pages=p,
                                      pagesTotal=len(pagesList),
                                      passedString=passedString,
                                      estimated=estimatedString))
                qApp.processEvents()
                # Get the appropriate url and open the page.
                url = str(Path(self.projectURL) / pagesList[p])
                page = Application.openDocument(url)
                page.waitForDone()

                # remove layers and flatten.
                labelList = self.configDictionary["labelsToRemove"]
                panelsAndText = []

                # These three lines are what is causing the page not to close.
                root = page.rootNode()
                self.getPanelsAndText(root, panelsAndText)
                self.removeLayers(labelList, root)
                page.refreshProjection()
                # We'll need the offset and scale for aligning the panels and text correctly. We're getting this from the CBZ

                pageData = {}
                pageData["vector"] = panelsAndText
                tree = ET.fromstring(page.documentInfo())
                pageData["title"] = page.name()
                calligra = "{http://www.calligra.org/DTD/document-info}"
                about = tree.find(calligra + "about")
                keywords = about.find(calligra + "keyword")
                keys = str(keywords.text).split(",")
                pKeys = []
                for key in keys:
                    if key in self.pageKeys:
                        pKeys.append(key)
                pageData["keys"] = pKeys
                page.flatten()
                page.waitForDone()
                batchsave = Application.batchmode()
                Application.setBatchmode(True)
                # Start making the format specific copy.
                for key in sizesList.keys():
                    w = sizesList[key]
                    # copy over data
                    projection = page.clone()
                    projection.setBatchmode(True)
                    # Crop. Cropping per guide only happens if said guides have been found.
                    if w["Crop"] is True:
                        listHGuides = []
                        listHGuides = page.horizontalGuides()
                        listHGuides.sort()
                        for i in range(len(listHGuides) - 1, 0, -1):
                            if listHGuides[i] < 0 or listHGuides[
                                    i] > page.height():
                                listHGuides.pop(i)
                        listVGuides = page.verticalGuides()
                        listVGuides.sort()
                        for i in range(len(listVGuides) - 1, 0, -1):
                            if listVGuides[i] < 0 or listVGuides[
                                    i] > page.width():
                                listVGuides.pop(i)
                        if self.configDictionary["cropToGuides"] and len(
                                listVGuides) > 1:
                            cropx = listVGuides[0]
                            cropw = listVGuides[-1] - cropx
                        else:
                            cropx = self.configDictionary["cropLeft"]
                            cropw = page.width(
                            ) - self.configDictionary["cropRight"] - cropx
                        if self.configDictionary["cropToGuides"] and len(
                                listHGuides) > 1:
                            cropy = listHGuides[0]
                            croph = listHGuides[-1] - cropy
                        else:
                            cropy = self.configDictionary["cropTop"]
                            croph = page.height(
                            ) - self.configDictionary["cropBottom"] - cropy
                        projection.crop(cropx, cropy, cropw, croph)
                        projection.waitForDone()
                        qApp.processEvents()
                        # resize appropriately
                    else:
                        cropx = 0
                        cropy = 0
                    res = page.resolution()
                    listScales = [
                        projection.width(),
                        projection.height(), res, res
                    ]
                    projectionOldSize = [
                        projection.width(),
                        projection.height()
                    ]
                    sizesCalc = sizesCalculator()
                    listScales = sizesCalc.get_scale_from_resize_config(
                        config=w, listSizes=listScales)
                    projection.unlock()
                    projection.scaleImage(listScales[0], listScales[1],
                                          listScales[2], listScales[3],
                                          "bicubic")
                    projection.waitForDone()
                    qApp.processEvents()
                    # png, gif and other webformats should probably be in 8bit srgb at maximum.
                    if key != "TIFF":
                        if (projection.colorModel() != "RGBA"
                                and projection.colorModel() != "GRAYA"
                            ) or projection.colorDepth() != "U8":
                            projection.setColorSpace("RGBA", "U8",
                                                     "sRGB built-in")
                    else:
                        # Tiff on the other hand can handle all the colormodels, but can only handle integer bit depths.
                        # Tiff is intended for print output, and 16 bit integer will be sufficient.
                        if projection.colorDepth(
                        ) != "U8" or projection.colorDepth() != "U16":
                            projection.setColorSpace(page.colorModel(), "U16",
                                                     page.colorProfile())
                    # save
                    # Make sure the folder name for this export exists. It'll allow us to keep the
                    # export folders nice and clean.
                    folderName = str(key + "-" + w["FileType"])
                    if Path(exportPath / folderName).exists() is False:
                        Path.mkdir(exportPath / folderName)
                    # Get a nice and descriptive fle name.
                    fn = str(
                        Path(exportPath / folderName) /
                        str("page_" + format(p, "03d") + "_" +
                            str(listScales[0]) + "x" + str(listScales[1]) +
                            "." + w["FileType"]))
                    # Finally save and add the page to a list of pages. This will make it easy for the packaging function to
                    # find the pages and store them.
                    projection.exportImage(fn, InfoObject())
                    projection.waitForDone()
                    qApp.processEvents()
                    if key == "CBZ":
                        transform = {}
                        transform["offsetX"] = cropx
                        transform["offsetY"] = cropy
                        transform["resDiff"] = page.resolution() / 72
                        transform["scaleWidth"] = projection.width(
                        ) / projectionOldSize[0]
                        transform["scaleHeight"] = projection.height(
                        ) / projectionOldSize[1]
                        pageData["transform"] = transform
                    self.pagesLocationList[key].append(fn)
                    projection.close()
                self.acbfPageData.append(pageData)
                page.close()
            progress.setValue(len(pagesList))
            Application.setBatchmode(batchsave)
            # TODO: Check what or whether memory leaks are still caused and otherwise remove the entry below.
            print(
                "CPMT: Export has finished. If there are memory leaks, they are caused by file layers."
            )
            return True
        print("CPMT: Export not happening because there aren't any pages.")
        return False
コード例 #16
0
    def export(self):
        export_success = False

        path = Path(self.projectURL)
        if path.exists():
            # Make a meta-data folder so we keep the export folder nice and clean.
            exportPath = path / self.configDictionary["exportLocation"]
            if Path(exportPath / "metadata").exists() is False:
                Path(exportPath / "metadata").mkdir()

            # Get to which formats to export, and set the sizeslist.
            lengthProcess = len(self.configDictionary["pages"])
            sizesList = {}
            if "CBZ" in self.configDictionary.keys():
                if self.configDictionary["CBZactive"]:
                    lengthProcess += 5
                    sizesList["CBZ"] = self.configDictionary["CBZ"]
            if "EPUB" in self.configDictionary.keys():
                if self.configDictionary["EPUBactive"]:
                    lengthProcess += 1
                    sizesList["EPUB"] = self.configDictionary["EPUB"]
            if "TIFF" in self.configDictionary.keys():
                if self.configDictionary["TIFFactive"]:
                    sizesList["TIFF"] = self.configDictionary["TIFF"]
            # Export the pngs according to the sizeslist.
            # Create a progress dialog.
            self.progress = QProgressDialog(i18n("Preparing export."), str(),
                                            0, lengthProcess)
            self.progress.setWindowTitle(i18n("Exporting Comic..."))
            self.progress.setCancelButton(None)
            self.timer = QElapsedTimer()
            self.timer.start()
            self.progress.show()
            qApp.processEvents()
            export_success = self.save_out_pngs(sizesList)

            # Export acbf metadata.
            if export_success:
                if "CBZ" in sizesList.keys():
                    title = self.configDictionary["projectName"]
                    if "title" in self.configDictionary.keys():
                        title = str(self.configDictionary["title"]).replace(
                            " ", "_")

                    self.acbfLocation = str(exportPath / "metadata" /
                                            str(title + ".acbf"))

                    locationStandAlone = str(exportPath / str(title + ".acbf"))
                    self.progress.setLabelText(
                        i18n("Saving out ACBF and\nACBF standalone"))
                    self.progress.setValue(self.progress.value() + 2)
                    export_success = exporters.ACBF.write_xml(
                        self.configDictionary, self.acbfPageData,
                        self.pagesLocationList["CBZ"], self.acbfLocation,
                        locationStandAlone, self.projectURL)
                    print("CPMT: Exported to ACBF", export_success)

            # Export and package CBZ and Epub.
            if export_success:
                if "CBZ" in sizesList.keys():
                    export_success = self.export_to_cbz(exportPath)
                    print("CPMT: Exported to CBZ", export_success)
                if "EPUB" in sizesList.keys():
                    self.progress.setLabelText(i18n("Saving out EPUB"))
                    self.progress.setValue(self.progress.value() + 1)
                    export_success = exporters.EPUB.export(
                        self.configDictionary, self.projectURL,
                        self.pagesLocationList["EPUB"], self.acbfPageData)
                    print("CPMT: Exported to EPUB", export_success)
        else:
            QMessageBox.warning(None, i18n("Export not Possible"),
                                i18n("Nothing to export, URL not set."),
                                QMessageBox.Ok)
            print("CPMT: Nothing to export, url not set.")

        return export_success
コード例 #17
0
#         f' | ABST: {track.time}']))

#     sleep(delta)
#     if not track.msg.is_meta:
#         port.send(track.msg.core)

# for msg in midifile.merge_run():
#     print(f'{msg} | tempo: {midifile.tempo}')
#     #sleep(msg.time)
#     if not msg.is_meta:
#         port.send(msg)

print('setup start..')
midi_iter = iter(midifile.run(MBT2tick(4, 1, 0, midifile.tpb)))
qtimer = QTimer()
etimer = QElapsedTimer()
app = QApplication([])
print('setup end..')

print('rewind start..')
etimer.start()
track = next(midi_iter)
if track:
    csr_secs = track.secs
    print(
        f'rewind end, elapsed: {etimer.elapsed() / 1000}, play starts from : {csr_secs}'
    )


def play():
    global midi_iter, track, qtimer, etimer
コード例 #18
0
ファイル: gameview.py プロジェクト: Litude/py-labyrinth
 def __init__(self):
     super().__init__()
     self.game = Game()
     self.game.new_game(Coordinate(20, 20, 2))
     self.elapsed_timer = QElapsedTimer()
     self.elapsed_timer.start()
コード例 #19
0
 def __init__(self):
     super().__init__()
     self.timer = QTimer()
     self.delta = QElapsedTimer()
     self.timer.setInterval(100)
     self.timer.timeout.connect(self.displayTime)
コード例 #20
0
 def ElapsedTime(self):
     self.elapsed_time = QElapsedTimer()
コード例 #21
0
    def wait_for(self, timeout=None, *, override_waited_for=False, **kwargs):
        """Wait until a given value is found in the data.

        Keyword arguments to this function get interpreted as attributes of the
        searched data. Every given argument is treated as a pattern which
        the attribute has to match against.

        Args:
            timeout: How long to wait for the message.
            override_waited_for: If set, gets triggered by previous messages
                                 again.

        Return:
            The matched line.
        """
        __tracebackhide__ = True
        if timeout is None:
            if 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        for line in self._data:
            matches = []

            for key, expected in kwargs.items():
                value = getattr(line, key)
                matches.append(self._match_data(value, expected))

            if all(matches) and (not line.waited_for or override_waited_for):
                # If we waited for this line, chances are we don't mean the
                # same thing the next time we use wait_for and it matches
                # this line again.
                line.waited_for = True
                return line

        # If there is none, wait for the message
        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                raise WaitForTimeout("Timed out after {}ms waiting for "
                                     "{!r}.".format(timeout, kwargs))

            for args in spy:
                assert len(args) == 1
                line = args[0]

                matches = []

                for key, expected in kwargs.items():
                    value = getattr(line, key)
                    matches.append(self._match_data(value, expected))

                if all(matches):
                    # If we waited for this line, chances are we don't mean the
                    # same thing the next time we use wait_for and it matches
                    # this line again.
                    line.waited_for = True
                    return line
コード例 #22
0
    def __init__(self, parent=None):
        """
        Constructor
        
        @param parent parent widget (QWidget)
        """
        super(Browser, self).__init__(parent)

        self.setWindowTitle(
            QCoreApplication.translate('Browser', 'File-Browser'))
        self.setWindowIcon(UI.PixmapCache.getIcon("eric.png"))

        self.__model = BrowserModel()
        self.__sortModel = BrowserSortFilterProxyModel()
        self.__sortModel.setSourceModel(self.__model)
        self.setModel(self.__sortModel)

        self.selectedItemsFilter = [BrowserFileItem]

        self._activating = False

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self._contextMenuRequested)
        self.activated.connect(self._openItem)
        self.expanded.connect(self._resizeColumns)
        self.collapsed.connect(self._resizeColumns)

        self.setWhatsThis(
            QCoreApplication.translate(
                'Browser', """<b>The Browser Window</b>"""
                """<p>This allows you to easily navigate the hierarchy of"""
                """ directories and files on your system, identify the Python"""
                """ programs and open them up in a Source Viewer window. The"""
                """ window displays several separate hierarchies.</p>"""
                """<p>The first hierarchy is only shown if you have opened a"""
                """ program for debugging and its root is the directory"""
                """ containing that program. Usually all of the separate files"""
                """ that make up a Python application are held in the same"""
                """ directory, so this hierarchy gives you easy access to most"""
                """ of what you will need.</p>"""
                """<p>The next hierarchy is used to easily navigate the"""
                """ directories that are specified in the Python"""
                """ <tt>sys.path</tt> variable.</p>"""
                """<p>The remaining hierarchies allow you navigate your system"""
                """ as a whole. On a UNIX system there will be a hierarchy with"""
                """ <tt>/</tt> at its root and another with the user home"""
                """ directory. On a Windows system there will be a hierarchy for"""
                """ each drive on the"""
                """ system.</p>"""
                """<p>Python programs (i.e. those with a <tt>.py</tt> file name"""
                """ suffix) are identified in the hierarchies with a Python"""
                """ icon. The right mouse button will popup a menu which lets"""
                """ you open the file in a Source Viewer window, open the file"""
                """ for debugging or use it for a unittest run.</p>"""
                """<p>The context menu of a class, function or method allows you"""
                """ to open the file defining this class, function or method and"""
                """ will ensure, that the correct source line is visible.</p>"""
                """<p>Qt-Designer files (i.e. those with a <tt>.ui</tt> file"""
                """ name suffix) are shown with a Designer icon. The context"""
                """ menu of these files allows you to start Qt-Designer with"""
                """ that file.</p>"""
                """<p>Qt-Linguist files (i.e. those with a <tt>.ts</tt> file"""
                """ name suffix) are shown with a Linguist icon. The context"""
                """ menu of these files allows you to start Qt-Linguist with"""
                """ that file.</p>"""))

        self.__createPopupMenus()

        self._init()  # perform common initialization tasks

        self._keyboardSearchString = ""
        self._keyboardSearchTimer = QElapsedTimer()
        self._keyboardSearchTimer.invalidate()
コード例 #23
0
ファイル: Watch.py プロジェクト: ChSt98/KraftKonnect
 def __init__(self):
     super().__init__()
     uic.loadUi('src/widgets/default/watch/watch.ui', self)
     self.timer = QElapsedTimer()
     self.timer.start()
コード例 #24
0
def detection():
    while(True):
        try:
            data = str(sock.recv(1024),'utf-8')
        except:
            data = ""
        if (data == 'start_object_detection;#'):
            try:
                percentage = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "confidency_threshold")
            except:
                percentage = "0.9"

            try:
                index = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "camera_index")
            except:
                index = "0"

            if os.path.isfile(CWD_TXT):
                pass
            else:
                with open(CWD_TXT, 'a+') as f:
                    f.write('[]' + '\n')

            if (percentage == ""):
                percentage = "0.9"
            percentage = float(percentage)
            print (index)
            if index == "":
                index = 0
            f = open(CWD_TXT, 'r+')
            f.truncate(0)
            try:
                video = cv2.VideoCapture(int(index))
                width  = video.get(cv2.cv2.CAP_PROP_FRAME_WIDTH)
                height = video.get(cv2.cv2.CAP_PROP_FRAME_HEIGHT)
                cam_fps = video.get(cv2.cv2.CAP_PROP_FPS)
            except:
                pass

            elapsed_timer = QElapsedTimer()
            elapsed_timer.start()

            if video is None or not video.isOpened():
                MessageBox("Vendron","Error No such Camera exist", 64)
                detection()
            else :
                sent = True
                while(True):
                    try:
                        data = str(sock.recv(1024),'utf-8')
                    except:
                        pass
                
                    if (data == 'end_object_detection;#'):
                        sent = False
                        cv2.destroyWindow('Object detector')
                        video.release()
                        socketSend("object_detection_ended;#")
                        break
                    else:
                        data = []
                        myList = []
                        myScore = []
                        result_list = []
                        name = []

                        try:
                            fps = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "frame_rate")
                        except:
                            fps = cam_fps
                        try:
                            ymin_1 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y_min_threshold_1")
                        except:
                            ymin_1 = "80"
                        try:
                            ymax_1 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y_max_threshold_1")
                        except:
                            ymax_1 = "240"
                        try:
                            ymin_2 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y_min_threshold_2")
                        except:
                            ymin_2 = "240"
                        try:
                            ymax_2 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y_max_threshold_2")
                        except:
                            ymax_2 = "400"
                        try:
                            places = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "is_camera_reversed")
                        except:
                            places = "false"
                        try:
                            w2 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "x")
                        except:
                            w2 = "0"
                        try:
                            h2 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "y")
                        except:
                            h2 = "0"
                        try:
                            w1 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "width")
                        except:
                            w1 = "640"
                        try:
                            h1 = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "height")
                        except:
                            h1 = "480"


                        if video is None:
                            pass
                        else:
                            ret, frame = video.read()
                            if(w1 == ""):
                                w1 = "640"
                            if(w2 == ""):
                                w2 = "0"
                            if(h1 == ""):
                                h1 = "480"
                            if(h2 == ""):
                                h2 = "0"

                            w1 = int(w1) + int(w2)
                            h1 = int(h1) + int(h2)
                            frame = frame[int(h2):int(h1),int(w2):int(w1)]
                            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                            frame_expanded = np.expand_dims(frame, axis=0)

                            # Perform the actual detection by running the model with the image as input
                            try:
                                (boxes, scores, classes, num) = sess.run(
                                    [detection_boxes, detection_scores, detection_classes, num_detections],
                                    feed_dict={image_tensor: frame_expanded})
                            except:
                                pass

                            # Draw the results of the detection (aka 'visulaize the results')
                            try:
                                vis_util.visualize_boxes_and_labels_on_image_array(
                                    frame,
                                    np.squeeze(boxes),
                                    np.squeeze(classes).astype(np.int32),
                                    np.squeeze(scores),
                                    category_index,
                                    use_normalized_coordinates=True,
                                    line_thickness=3,
                                    min_score_thresh= percentage)

                                data = [category_index.get(value) for index,value in enumerate(classes[0]) if scores[0,index] > percentage]
                                for cl in data:
                                   if cl != None :
                                        myList.append(str(cl['name']))

                                objects = []
                                for index, value in enumerate(classes[0]):
                                    object_dict = {}
                                    if scores[0, index] > percentage:
                                        object_dict[(category_index.get(value)).get('name').encode('utf8')] = \
                                                                                                        scores[0, index]
                                        objects.append(object_dict)

                                coordinates = vis_util.return_coordinates(
                                                frame,
                                                np.squeeze(boxes),
                                                np.squeeze(classes).astype(np.int32),
                                                np.squeeze(scores),
                                                category_index,
                                                use_normalized_coordinates=True,
                                                line_thickness=3,
                                                min_score_thresh= percentage)
                            except:
                                pass
                        
                            if(sent == True):
                                socketSend("object_detection_started;#")
                                sent = False

                            if(places == ""):
                                places = "false"
                            if(ymin_1 == ""):
                                ymin_1 = "80"
                            if(ymin_2 == ""):
                                ymin_2 = "240"
                            if(ymax_1 == ""):
                                ymax_1 = "240"
                            if(ymax_2 == ""):
                                ymax_2 = "400"

                            try:
                                if(places == "true"):
                                    alpha = 0.3;
                                    overlay = frame.copy()
                                    cv2.rectangle(overlay, (0, int(ymin_1)), (int(width), int(ymin_2)),(0, 0, 255), -1)
                                    cv2.addWeighted(overlay, alpha, frame, 1 - alpha,
                                                    0, frame)
                                    overlay_blue = frame.copy()
                                    cv2.rectangle(overlay_blue, (0, int(ymax_1)), (int(width), int(ymax_2)),(255, 0, 0), -1)
                                    cv2.addWeighted(overlay_blue, alpha, frame, 1 - alpha,
                                                    0, frame)
                            
                                elif(places == "false"):
                                    alpha = 0.3;
                                    overlay = frame.copy()
                                    cv2.rectangle(overlay, (0, int(ymax_1)), (int(width), int(ymax_2)),(0, 0, 255), -1)
                                    cv2.addWeighted(overlay, alpha, frame, 1 - alpha,
                                                0, frame)
                                    overlay_blue = frame.copy()
                                    cv2.rectangle(overlay_blue, (0, int(ymin_1)), (int(width), int(ymin_2)),(255, 0, 0), -1)
                                    cv2.addWeighted(overlay_blue, alpha, frame, 1 - alpha,
                                                    0, frame)
                            except:
                                pass

                            if(fps == ""):
                                fps = cam_fps
                            
                            fps = 1/int(fps)

                            print (type(fps))
        
                            while(elapsed_timer.hasExpired(fps)):
                                if coordinates is None:
                                    print("nothing")
                                else:
                                    if video is None:
                                        sent = False
                                        cv2.destroyWindow('Object detector')
                                        socketSend("object_detection_ended;#")
                                        break
                                    
                                    list_1stesult = myList
                                    coordinates_result = coordinates
                                    for ea_list,ea_coor,score in zip(list_1stesult,coordinates_result,objects):
                                        score = str(score)
                                        score = score.split(":")[1]
                                        score = score.replace("}","")
                                        score = score.replace("]","")
                                        score = float(score) * 100
                                        score = str(round(score))
                                        result = os.path.join(ea_list,",",str(ea_coor),",",score)
                                        result = result.replace("[[","[")
                                        result = result.replace("\\","")
                                        result = result.replace("[","")
                                        result = result.replace("]","")
                                        name.append(ea_list)
                                        result_list.append(result)

                                    print (result_list)
                                    result_list = str(result_list).replace("', '","];[")
                                    result_list = result_list.replace("'","")
                                    result_list = result_list.replace("'","")
                                    result_list = result_list.replace(", ",",")
                                    if result_list:
                                        with open(CWD_TXT, "a") as text_file:
                                            text_file.write(str(result_list) + "\n")

                                    if result_list:
                                        with open(CWD_HISTORY,"a") as text_file:
                                            text_file.write(str(result_list) + "\n")
                            
                                    elapsed_timer.start()
                    

                    # All the results have been drawn on the frame, so it's time to display it.
                            try:
                                path_debug = regkey_value(r"HKEY_CURRENT_USER\Software\Silkron\Vendron\ai_vision_fridge", "debug")
                            except:
                                path_debug = "false"

                            if (path_debug == "true"):
                                try:
                                    cv2.imshow('Object detector', frame)
                                except:
                                    sent = False
                                    cv2.destroyWindow('Object detector')
                                    video.release()
                                    socketSend("object_detection_ended;#")
                                    break
                            else:
                                pass

                            if cv2.waitKey(1) == ord ("q"):
                                pass