예제 #1
0
def _wait_for_clipboard(qtbot, clipboard, mode, expected):
    timeout = 1000
    timer = QElapsedTimer()
    timer.start()

    while True:
        if clipboard.text(mode=mode) == expected:
            return

        # We need to poll the clipboard, as for some reason it can change with
        # emitting changed (?).
        with qtbot.waitSignal(clipboard.changed, timeout=100, raising=False):
            pass

        if timer.hasExpired(timeout):
            mode_names = {
                QClipboard.Clipboard: 'clipboard',
                QClipboard.Selection: 'primary selection',
            }
            raise WaitForClipboardTimeout(
                "Timed out after {timeout}ms waiting for {what}:\n"
                "   expected: {expected!r}\n"
                "  clipboard: {clipboard!r}\n"
                "    primary: {primary!r}.".format(
                    timeout=timeout, what=mode_names[mode],
                    expected=expected,
                    clipboard=clipboard.text(mode=QClipboard.Clipboard),
                    primary=clipboard.text(mode=QClipboard.Selection))
            )
예제 #2
0
def _wait_for_clipboard(qtbot, clipboard, mode, expected):
    timeout = 1000
    timer = QElapsedTimer()
    timer.start()

    while True:
        if clipboard.text(mode=mode) == expected:
            return

        # We need to poll the clipboard, as for some reason it can change with
        # emitting changed (?).
        with qtbot.waitSignal(clipboard.changed, timeout=100, raising=False):
            pass

        if timer.hasExpired(timeout):
            mode_names = {
                QClipboard.Clipboard: 'clipboard',
                QClipboard.Selection: 'primary selection',
            }
            raise WaitForClipboardTimeout(
                "Timed out after {timeout}ms waiting for {what}:\n"
                "   expected: {expected!r}\n"
                "  clipboard: {clipboard!r}\n"
                "    primary: {primary!r}.".format(
                    timeout=timeout,
                    what=mode_names[mode],
                    expected=expected,
                    clipboard=clipboard.text(mode=QClipboard.Clipboard),
                    primary=clipboard.text(mode=QClipboard.Selection)))
예제 #3
0
    def __init__(self, **kwargs):
        QObject.__init__(self)
        self.filename = kwargs.get("filename")
        self.text_code = kwargs.get("code")
        self.__python_exec = kwargs.get("python_exec")
        self.pre_script = kwargs.get("pre_script")
        self.post_script = kwargs.get("post_script")
        self.__params = kwargs.get("params")
        self.__elapsed = QElapsedTimer()

        self.outputw = None

        self.__current_process = None

        self.main_process = QProcess(self)
        self.main_process.started.connect(self._process_started)
        self.main_process.finished.connect(self._process_finished)
        self.main_process.finished.connect(self.__post_execution)
        self.main_process.readyReadStandardOutput.connect(self._refresh_output)
        self.main_process.readyReadStandardError.connect(self._refresh_error)

        self.pre_process = QProcess(self)
        self.pre_process.started.connect(self._process_started)
        self.pre_process.finished.connect(self._process_finished)
        self.pre_process.finished.connect(self.__main_execution)
        self.pre_process.readyReadStandardOutput.connect(self._refresh_output)
        self.pre_process.readyReadStandardError.connect(self._refresh_error)

        self.post_process = QProcess(self)
        self.post_process.started.connect(self._process_started)
        self.post_process.finished.connect(self._process_finished)
        self.post_process.readyReadStandardOutput.connect(self._refresh_output)
        self.post_process.readyReadStandardError.connect(self._refresh_error)
예제 #4
0
 def nextQuestion(self):
     timer = QElapsedTimer()
     timer.start()
     questionWidget = Question(self.mainWindow, self.questionNum + 1,
                               self.result, timer, self.selectedInx)
     self.mainWindow.widgetList.addWidget(questionWidget)
     self.mainWindow.widgetList.setCurrentWidget(questionWidget)
예제 #5
0
    def generateSolution(self):
        """
        Generate a solution for the current cubestring and display in the GUI
        """
        self.statusbar.showMessage("Generating Solution")
        msg = "Generating solution for cubestring: " + self.cube.cubestring
        self.addLogEntry(msg)

        timer = QElapsedTimer()
        timer.start()
        solution = "No Solution"
        try:
            solution = kociemba.solve(self.cube.cubestring)
        except Exception as err:
            print(err)
            error_dialog = QErrorMessage()
            error_dialog.showMessage(err.args[0])
            error_dialog.exec_()
            solution = err.args[0]
            self.statusbar.showMessage("Solution generation failed!")
            msg = "Solution could not be calculated: " + solution
            self.addLogEntry(msg)

        self.lineEdit_InOut.setText(solution)
        self.label_CurrentString.setText("Solution:")
        self.statusbar.showMessage("Generated Solution")
        msg = "Solution calculation took: {} ms".format(timer.nsecsElapsed() /
                                                        1000000)
        self.addLogEntry(msg)

        # self.timer1ms.stop()
        pass
예제 #6
0
    def __init__(self, parent=None):
        super().__init__(parent)

        self._margin_x = 0.0
        self._margin_y = 0.0
        self._offset_x = 1.0
        self._offset_y = 1.0
        self._ampl_x = 1.0
        self._ampl_y = 1.0
        self._coeff_x = 5.0
        self._coeff_y = 4.0
        self._coeff_delta = 0.0
        self._t = 0.0
        self._circle_size = 20

        self._pen = QPen()
        self._pen.setWidth(2)
        self._pen.setColor(Qt.black)
        self._brush = QBrush(Qt.yellow)

        self._elapsed_timer = QElapsedTimer()
        self._timer = QTimer()
        self._timer.setInterval(1000 / 60)
        self._timer.timeout.connect(self.update)

        self.resize(800, 600)
        self.setWindowTitle('Eyetracker calibration')

        self._elapsed_timer.start()
        self._timer.start()
예제 #7
0
    def __init__(self):
        super().__init__()
        self.setWindowTitle("KOSAN KEDİ...")
        self.resize(512, 256)

        self.sprite_sheet = QImage("sprites-cat-running.png")
        self.sw = 512
        self.sh = 256
        self.frame_index = 0
        self.x = 0
        self.y = 0
        self.frames = []
        for i in range(2):
            for j in range(4):
                self.frames.append(QPoint(j * self.sw, i * self.sh))
                print(i, j)
        self.delta_time = 0
        self.animation_time = 0
        self.animation_speed = 100

        self.timer = QTimer()
        self.timer.timeout.connect(self.animationLoop)
        self.elapsedTimer = QElapsedTimer()
        self.timer.start(50)
        print("Timer start")
예제 #8
0
    def _wait_for_new(self, timeout, do_skip, **kwargs):
        """Wait for a log message which doesn't exist yet.

        Called via wait_for.
        """
        __tracebackhide__ = lambda e: e.errisinstance(WaitForTimeout)
        message = kwargs.get('message', None)
        if message is not None:
            elided = quteutils.elide(repr(message), 100)
            self._log("\n----> Waiting for {} in the log".format(elided))

        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                if message is not None:
                    self._log("----> found it")
                return match

        raise quteutils.Unreachable
예제 #9
0
    def _wait_for_new(self, timeout, do_skip, **kwargs):
        """Wait for a log message which doesn't exist yet.

        Called via wait_for.
        """
        __tracebackhide__ = lambda e: e.errisinstance(WaitForTimeout)
        message = kwargs.get('message', None)
        if message is not None:
            elided = quteutils.elide(repr(message), 50)
            self._log("\n----> Waiting for {} in the log".format(elided))

        spy = QSignalSpy(self.new_data)
        elapsed_timer = QElapsedTimer()
        elapsed_timer.start()

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                if message is not None:
                    self._log("----> found it")
                return match
예제 #10
0
    def wait_for(self,
                 timeout=None,
                 *,
                 override_waited_for=False,
                 do_skip=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.
            do_skip: If set, call pytest.skip on a timeout.

        Return:
            The matched line.
        """
        __tracebackhide__ = True

        if timeout is None:
            if do_skip:
                timeout = 2000
            elif 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        if not kwargs:
            raise TypeError("No keyword arguments given!")
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        existing = self._wait_for_existing(override_waited_for, **kwargs)
        if existing is not None:
            return existing

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

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                return match
예제 #11
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
        if not kwargs:
            raise TypeError("No keyword arguments given!")
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        existing = self._wait_for_existing(override_waited_for, **kwargs)
        if existing is not None:
            return existing

        # 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
예제 #12
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
        if not kwargs:
            raise TypeError("No keyword arguments given!")
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        existing = self._wait_for_existing(override_waited_for, **kwargs)
        if existing is not None:
            return existing

        # 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
예제 #13
0
    def wait_for(self, timeout=None, **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.

        Return:
            The matched line.
        """
        if timeout is None:
            if 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        # 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:
                # 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
예제 #14
0
 def toRate(self):
     self.updateResult()
     self.updateTime()
     timer = QElapsedTimer()
     timer.start()
     rateWidget = Rate(self.mainWindow, self.questionNum, self.result,
                       self.selectedInx, timer)
     self.mainWindow.widgetList.addWidget(rateWidget)
     self.mainWindow.widgetList.setCurrentWidget(rateWidget)
예제 #15
0
    def wait_for(self, timeout=None, *, override_waited_for=False,
                 do_skip=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.
            do_skip: If set, call pytest.skip on a timeout.

        Return:
            The matched line.
        """
        __tracebackhide__ = True

        if timeout is None:
            if do_skip:
                timeout = 2000
            elif 'CI' in os.environ:
                timeout = 15000
            else:
                timeout = 5000
        if not kwargs:
            raise TypeError("No keyword arguments given!")
        for key in kwargs:
            assert key in self.KEYS

        # Search existing messages
        existing = self._wait_for_existing(override_waited_for, **kwargs)
        if existing is not None:
            return existing

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

        while True:
            # Skip if there are pending messages causing a skip
            self._maybe_skip()
            got_signal = spy.wait(timeout)
            if not got_signal or elapsed_timer.hasExpired(timeout):
                msg = "Timed out after {}ms waiting for {!r}.".format(
                    timeout, kwargs)
                if do_skip:
                    pytest.skip(msg)
                else:
                    raise WaitForTimeout(msg)

            match = self._wait_for_match(spy, kwargs)
            if match is not None:
                return match
예제 #16
0
class Timer(Text):
    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)

    def set_current_state(self, state):

        self._current_state = state
        self.stateChanged.emit(state)

    def set_speed(self, speed):
        try:
            self.speed = float(speed)
            self._elapsed_time.start()
        except BaseException:
            logging.exception("Failed to set timer speed")

    def set_time(self, time):

        try:
            time = time.strip()

            if time[0] in '+-':
                self.seconds += float(time)
            else:
                self.seconds = float(time)
        except BaseException:
            logging.exception("Failed to set timer time")

    @pyqtSlot()
    def _update(self):
        self.seconds += self.speed * self._elapsed_time.elapsed() / 1000
        self.seconds = max(self.seconds, 0)
        self._elapsed_time.start()
        h, m, s = self.split_time(self.seconds)
        self.setText(f'{h:02}:{m:02}:{s:02}')

    @classmethod
    def split_time(cls, seconds):

        hours, remaining = divmod(seconds, 3600)
        minutes, seconds = divmod(remaining, 60)
        return int(hours), int(minutes), int(seconds)
    def initTimer(self):

        self.gameTimer = QBasicTimer()
        self.gameTimer.start(TICK_INTERVALL, self)

        # For deltaTime
        self.elapsedTimer = QElapsedTimer()
        self.elapsedTimer.start()
        self.previous = 0
        self.tickCounter = 0
예제 #18
0
	def _searchBatch(self):
		with self.safeBatch():
			start_time = QElapsedTimer()
			start_time.start()

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

			self.timer.stop()
			self.finished.emit(0)
예제 #19
0
    def __init__(self):
        super(DedeNimeur, self).__init__()
        self.statusBar()

        self.size, self.height, self.width, self.mines = 30, 10, 10, 10
        self.lcd = QLCDNumber()
        self.lcd.setFixedSize(300, 60)
        self.board = Board(self.height, self.width, self.mines, self.size)
        self.timer = QBasicTimer()
        self.real_timer = QElapsedTimer()

        vbox = QVBoxLayout()
        vbox.addWidget(self.lcd)
        vbox.addWidget(self.board)

        central = QWidget()
        central.setLayout(vbox)
        self.setCentralWidget(central)

        start = QAction('Start', self)
        start.setStatusTip('Start')
        start.setShortcut('Ctrl+N')
        start.triggered.connect(self.init)

        exit = QAction('Exit', self)
        exit.setStatusTip('Exit')
        exit.setShortcut('Ctrl+Q')
        exit.triggered.connect(qApp.quit)

        height = QAction('Height', self)
        height.setStatusTip('Set board width')
        height.triggered.connect(self.set_height)
        width = QAction('Width', self)
        width.setStatusTip('Set board height')
        width.triggered.connect(self.set_width)
        mines = QAction('Mines', self)
        mines.setStatusTip('Set board mines')
        mines.triggered.connect(self.set_mines)
        size = QAction('Size', self)
        size.setStatusTip('Set button size')
        size.triggered.connect(self.set_size)

        toolbar = self.addToolBar('Toolbar')
        toolbar.addAction(start)
        toolbar.addAction(width)
        toolbar.addAction(height)
        toolbar.addAction(mines)
        toolbar.addAction(size)
        toolbar.addAction(exit)

        self.setWindowTitle(u'DédéNimeur')
        self.show()
예제 #20
0
class Bullet:
	"""Bullet contains:
		1 StartPosition
		2 EndPosition
		3 Color
		4 Text( A String)
		5 Duration
		It uses the "window"  to draw it selft
	"""
	#这个叫做  类的属性  
	Count=0# 通过类名Bullet.bullet访问,就是一个静态变量
	Height=GLOBAL.BULLETFONTSIZE+6 #一个Bullet占用的像素高度
	def __init__(self, Text, Color,Duration):
		Bullet.Count+=1
		#这个里面self给定的内容则只属于当前对象
		self.Text=Text
		self.Color=Color
		self.Duration=Duration*1000 #单位是毫秒,输入的是秒
		self.IsExpired=False

	"""this method must be called when this 
		bullet is ready to shoot at the first time
	"""
	def prepare(self):
		self.elapsedTimer=QElapsedTimer()
		self.elapsedTimer.start() #start time
		self.StartPosition=QPoint(GLOBAL.WINDOWWIDTH+random.randrange(200,500,20),\
			(Bullet.Height+(Bullet.Count%(GLOBAL.WINDOWHEIGHT//Bullet.Height))*Bullet.Height))
		self.EndPosition=QPoint(-2000 ,self.StartPosition.y())
	"""Draw this bullet at position x,y ,use painter
		Returns True indicates this bullet is out of screen
	"""
	def draw(self,painter):
		ratio=self.elapsedTimer.elapsed()/self.Duration
		if(ratio>0.9):
			self.IsExpired=True
		# pos=ratio*self.EndPosition+(1-ratio)*self.StartPosition
		pos=QPoint(ratio*self.EndPosition.x()+(1-ratio)*self.StartPosition.x(),self.StartPosition.y())
		#这里需要插入绘制字体阴影的代码
		#
		# font.setFixedPitch(True)
		# painter.setFont(font)
		painter.save()
		painter.drawText(pos+QPoint(2,2),self.Text)
		painter.setPen(QPen(self.Color))
		painter.drawText(pos,self.Text)
		painter.restore()

	# def __del__(self):
		# Count-=1
		# print ("刚刚自动Delete了一个bullet\n")
예제 #21
0
    def __init__(self, project, type_, parent=None):
        """
        Constructor
        
        @param project reference to the project object
        @param type_ project browser type (string)
        @param parent parent widget of this browser
        """
        QTreeView.__init__(self, parent)

        self.project = project

        self._model = project.getModel()
        self._sortModel = ProjectBrowserSortFilterProxyModel(type_)
        self._sortModel.setSourceModel(self._model)
        self.setModel(self._sortModel)

        self.selectedItemsFilter = [ProjectBrowserFileItem]

        # contains codes for special menu entries
        # 1 = specials for Others browser
        self.specialMenuEntries = []
        self.isTranslationsBrowser = False
        self.expandedNames = []

        self.SelectFlags = QItemSelectionModel.SelectionFlags(
            QItemSelectionModel.Select | QItemSelectionModel.Rows)
        self.DeselectFlags = QItemSelectionModel.SelectionFlags(
            QItemSelectionModel.Deselect | QItemSelectionModel.Rows)

        self._activating = False

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self._contextMenuRequested)
        self.activated.connect(self._openItem)
        self._model.rowsInserted.connect(self.__modelRowsInserted)
        self._connectExpandedCollapsed()

        self._createPopupMenus()

        self.currentItemName = None

        self._init()  # perform common initialization tasks

        self._keyboardSearchString = ""
        self._keyboardSearchTimer = QElapsedTimer()
        self._keyboardSearchTimer.invalidate()

        self._initHookMethods()  # perform initialization of the hooks
        self.hooksMenuEntries = {}
예제 #22
0
 def __init__(self):
     super().__init__()
     self.conn_status = False
     self.query_status = False
     self.sckt = None
     self.new_tcp_host = "192.168.43.67"  #TCP_HOST_IP
     self.init_ui()
     self.q_p1_x = 116.30
     self.q_p1_y = 39.97
     self.q_p2_x = 116.32
     self.q_p2_y = 40.00
     self.query_elapsed = None
     self.proc_elapsed = 0
     self.timer = QElapsedTimer()
예제 #23
0
    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)
예제 #24
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)
예제 #25
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
예제 #26
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
예제 #27
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)
예제 #28
0
파일: calibrate.py 프로젝트: Sasza/pisak
    def __init__(self, parent=None):
        super().__init__(parent)

        self._margin_x = 0.0
        self._margin_y = 0.0
        self._offset_x = 1.0
        self._offset_y = 1.0
        self._ampl_x = 1.0
        self._ampl_y = 1.0
        self._coeff_x = 5.0
        self._coeff_y = 4.0
        self._coeff_delta = 0.0
        self._t = 0.0
        self._circle_size = 20

        self._pen = QPen()
        self._pen.setWidth(2)
        self._pen.setColor(Qt.black)
        self._brush = QBrush(Qt.yellow)

        self._elapsed_timer = QElapsedTimer()
        self._timer = QTimer()
        self._timer.setInterval(1000 / 60)
        self._timer.timeout.connect(self.update)

        self.resize(800, 600)
        self.setWindowTitle("Eyetracker calibration")

        self._elapsed_timer.start()
        self._timer.start()
예제 #29
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)
예제 #30
0
파일: view.py 프로젝트: duniter/sakia
    def __init__(self, parent):
        """
        Constructor
        """
        super().__init__(parent)
        self.setupUi(self)
        self.last_speed = 0.1
        self.average_speed = 1
        self.timer = QElapsedTimer()
        self.edit_uid.textChanged.connect(self.values_changed)
        self.edit_password.textChanged.connect(self.values_changed)
        self.edit_password_repeat.textChanged.connect(self.values_changed)
        self.edit_salt.textChanged.connect(self.values_changed)
        self.edit_pubkey.textChanged.connect(self.values_changed)
        self.button_generate.clicked.connect(self.action_show_pubkey)
        self.text_license.setReadOnly(True)

        self.combo_scrypt_params.currentIndexChanged.connect(self.handle_combo_change)
        self.scrypt_params = ScryptParams(4096, 16, 1)
        self.spin_n.setMaximum(2 ** 20)
        self.spin_n.setValue(self.scrypt_params.N)
        self.spin_n.valueChanged.connect(self.handle_n_change)
        self.spin_r.setMaximum(128)
        self.spin_r.setValue(self.scrypt_params.r)
        self.spin_r.valueChanged.connect(self.handle_r_change)
        self.spin_p.setMaximum(128)
        self.spin_p.setValue(self.scrypt_params.p)
        self.spin_p.valueChanged.connect(self.handle_p_change)
        self.label_info.setTextFormat(Qt.RichText)
예제 #31
0
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("KOSAN KEDİ...")
        self.resize(512, 256)

        self.sprite_sheet = QImage("sprites-cat-running.png")
        self.sw = 512
        self.sh = 256
        self.frame_index = 0
        self.x = 0
        self.y = 0
        self.frames = []
        for i in range(2):
            for j in range(4):
                self.frames.append(QPoint(j * self.sw, i * self.sh))
                print(i, j)
        self.delta_time = 0
        self.animation_time = 0
        self.animation_speed = 100

        self.timer = QTimer()
        self.timer.timeout.connect(self.animationLoop)
        self.elapsedTimer = QElapsedTimer()
        self.timer.start(50)
        print("Timer start")

    def animationLoop(self):
        print("Timer started...")

        self.delta_time = self.elapsedTimer.elapsed()
        self.elapsedTimer.restart()
        self.animation_time += self.delta_time
        if self.animation_time <= self.animation_speed:
            print("self.animation_time >= self.animation_speed")
            self.animation_time = 0
            self.x = self.frames[self.frame_index].x()
            self.y = self.frames[self.frame_index].y()
            self.frame_index += 1
            if self.frame_index >= len(self.frames):
                self.frame_index = 0
                print("self.frame_index = 0")
        self.update()

    def paintEvent(self, event):
        qp = QPainter(self)
        qp.drawImage(0, 0, self.sprite_sheet, self.x, self.y, self.sw, self.sh)
예제 #32
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()
예제 #33
0
class Watch(QWidget):

    required_keys = []
    update_interval = 30

    def __init__(self):
        super().__init__()
        uic.loadUi('src/widgets/default/watch/watch.ui', self)
        self.timer = QElapsedTimer()
        self.timer.start()

    def update_data(self, data):
        pass

    def redraw(self):
        self.lcd.display(format(self.timer.elapsed() / 1000, '.3f'))
        self.progress.setValue(self.timer.elapsed() % 1000 / 10)
예제 #34
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]))
예제 #35
0
 def __init__(self):
     super().__init__()
     self.targetHostReplyMessage = False
     self.targetHostReply = False
     self.proxyisWorking = False
     self.error = False
     self.errorCode = False
     self.errorString = False
     self.elapsedTime = False
     self.elapsedTimer = QElapsedTimer()
예제 #36
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
예제 #37
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")
예제 #38
0
    def __init__(self):
        super(DedeNimeur, self).__init__()
        self.statusBar()

        self.size, self.height, self.width, self.mines = 30, 10, 10, 10
        self.lcd = QLCDNumber()
        self.lcd.setFixedSize(300, 60)
        self.board = Board(self.height, self.width, self.mines, self.size)
        self.timer = QBasicTimer()
        self.real_timer = QElapsedTimer()

        vbox = QVBoxLayout()
        vbox.addWidget(self.lcd)
        vbox.addWidget(self.board)

        central = QWidget()
        central.setLayout(vbox)
        self.setCentralWidget(central)

        start = QAction('Start', self)
        start.setStatusTip('Start')
        start.setShortcut('Ctrl+N')
        start.triggered.connect(self.init)

        exit = QAction('Exit', self)
        exit.setStatusTip('Exit')
        exit.setShortcut('Ctrl+Q')
        exit.triggered.connect(qApp.quit)

        height = QAction('Height', self)
        height.setStatusTip('Set board width')
        height.triggered.connect(self.set_height)
        width = QAction('Width', self)
        width.setStatusTip('Set board height')
        width.triggered.connect(self.set_width)
        mines = QAction('Mines', self)
        mines.setStatusTip('Set board mines')
        mines.triggered.connect(self.set_mines)
        size = QAction('Size', self)
        size.setStatusTip('Set button size')
        size.triggered.connect(self.set_size)

        toolbar = self.addToolBar('Toolbar')
        toolbar.addAction(start)
        toolbar.addAction(width)
        toolbar.addAction(height)
        toolbar.addAction(mines)
        toolbar.addAction(size)
        toolbar.addAction(exit)

        self.setWindowTitle(u'DédéNimeur')
        self.show()
예제 #39
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)
예제 #40
0
class MainWindow(WgpuCanvas):
    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

    def mainloop(self):
        """ Main update loop """

        if self.is_closed():
            self.timer.stop()
            return

        # Get current time since launch
        t = self.timing.elapsed() / 1000

        # Call draw fonction with the time
        self.drawFunction(t)

        # Display FPS
        if t - self.oldTime > 0:
            print(round(1 / (t - self.oldTime), 2), "FPS")
        self.oldTime = t
    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()
예제 #42
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)
예제 #43
0
파일: calibrate.py 프로젝트: Sasza/pisak
class CalibrationWidget(QWidget):

    cursorPos = pyqtSignal(float, float, "qint64")

    def __init__(self, parent=None):
        super().__init__(parent)

        self._margin_x = 0.0
        self._margin_y = 0.0
        self._offset_x = 1.0
        self._offset_y = 1.0
        self._ampl_x = 1.0
        self._ampl_y = 1.0
        self._coeff_x = 5.0
        self._coeff_y = 4.0
        self._coeff_delta = 0.0
        self._t = 0.0
        self._circle_size = 20

        self._pen = QPen()
        self._pen.setWidth(2)
        self._pen.setColor(Qt.black)
        self._brush = QBrush(Qt.yellow)

        self._elapsed_timer = QElapsedTimer()
        self._timer = QTimer()
        self._timer.setInterval(1000 / 60)
        self._timer.timeout.connect(self.update)

        self.resize(800, 600)
        self.setWindowTitle("Eyetracker calibration")

        self._elapsed_timer.start()
        self._timer.start()

    def resizeEvent(self, event):
        w, h = self.width(), self.height()
        self._margin_x = 0.05 * w
        self._margin_y = 0.08 * h
        self._offset_x = 0.5 * w
        self._offset_y = 0.5 * h
        self._ampl_x = 0.5 * (w - 2.0 * self._margin_x)
        self._ampl_y = 0.5 * (h - 2.0 * self._margin_y)
        self._circle_size = 0.05 * h
        self._pen.setWidth(0.005 * h)

    def paintEvent(self, event):
        qp = QPainter()
        qp.begin(self)

        qp.setRenderHint(QPainter.Antialiasing)

        elapsed = self._elapsed_timer.restart()
        if elapsed > 100:
            elapsed = 100
        self._t += 0.0002 * elapsed

        x = self._offset_x + self._ampl_x * math.sin(self._coeff_x * self._t + self._coeff_delta)

        y = self._offset_y + self._ampl_y * math.sin(self._coeff_y * self._t)

        qp.setPen(self._pen)
        qp.setBrush(self._brush)
        qp.drawEllipse(QPointF(x, y), self._circle_size, self._circle_size)

        qp.end()

        self.cursorPos.emit(x, y, QDateTime.currentMSecsSinceEpoch())
예제 #44
0
class Program(QObject):

    def __init__(self, **kwargs):
        QObject.__init__(self)
        self.filename = kwargs.get("filename")
        self.text_code = kwargs.get("code")
        self.__python_exec = kwargs.get("python_exec")
        self.pre_script = kwargs.get("pre_script")
        self.post_script = kwargs.get("post_script")
        self.__params = kwargs.get("params")
        self.__elapsed = QElapsedTimer()

        self.outputw = None

        self.__current_process = None

        self.main_process = QProcess(self)
        self.main_process.started.connect(self._process_started)
        self.main_process.finished.connect(self._process_finished)
        self.main_process.finished.connect(self.__post_execution)
        self.main_process.readyReadStandardOutput.connect(self._refresh_output)
        self.main_process.readyReadStandardError.connect(self._refresh_error)

        self.pre_process = QProcess(self)
        self.pre_process.started.connect(self._process_started)
        self.pre_process.finished.connect(self._process_finished)
        self.pre_process.finished.connect(self.__main_execution)
        self.pre_process.readyReadStandardOutput.connect(self._refresh_output)
        self.pre_process.readyReadStandardError.connect(self._refresh_error)

        self.post_process = QProcess(self)
        self.post_process.started.connect(self._process_started)
        self.post_process.finished.connect(self._process_finished)
        self.post_process.readyReadStandardOutput.connect(self._refresh_output)
        self.post_process.readyReadStandardError.connect(self._refresh_error)

    def start(self):
        self.__pre_execution()
        self.outputw.setFocus()

    def __pre_execution(self):
        """Execute a script before executing the project"""
        self.__current_process = self.pre_process
        file_pre_exec = QFile(self.pre_script)
        if file_pre_exec.exists():
            ext = file_manager.get_file_extension(self.pre_script)
            args = []
            if ext == "py":
                program = self.python_exec
                # -u: Force python to unbuffer stding ad stdout
                args.append("-u")
                args.append(self.pre_script)
            elif ext == "sh":
                program = "bash"
                args.append(self.pre_script)
            else:
                program = self.pre_script
            self.pre_process.setProgram(program)
            self.pre_process.setArguments(args)
            self.pre_process.start()
        else:
            self.__main_execution()

    def __main_execution(self):
        self.__elapsed.start()
        self.__current_process = self.main_process
        if not self.only_text:
            # In case a text is executed and not a file or project
            file_directory = file_manager.get_folder(self.filename)
            self.main_process.setWorkingDirectory(file_directory)
        self.main_process.setProgram(self.python_exec)
        self.main_process.setArguments(self.arguments)
        environment = QProcessEnvironment()
        system_environment = self.main_process.systemEnvironment()
        for env in system_environment:
            key, value = env.split("=", 1)
            environment.insert(key, value)
        self.main_process.setProcessEnvironment(environment)
        self.main_process.start()

    def __post_execution(self):
        """Execute a script after executing the project."""
        self.__current_process = self.post_process
        file_pre_exec = QFile(self.post_script)
        if file_pre_exec.exists():
            ext = file_manager.get_file_extension(self.post_script)
            args = []
            if ext == "py":
                program = self.python_exec
                # -u: Force python to unbuffer stding ad stdout
                args.append("-u")
                args.append(self.post_script)
            elif ext == "sh":
                program = "bash"
                args.append(self.post_script)
            else:
                program = self.post_script
            self.post_process.setProgram(program)
            self.post_process.setArguments(args)
            self.post_process.start()

    @property
    def process_name(self):
        proc = self.__current_process
        return proc.program() + " " + " ".join(proc.arguments())

    def update(self, **kwargs):
        self.text_code = kwargs.get("code")
        self.__python_exec = kwargs.get("python_exec")
        self.pre_script = kwargs.get("pre_script")
        self.post_script = kwargs.get("post_script")
        self.__params = kwargs.get("params")

    def set_output_widget(self, ow):
        self.outputw = ow
        self.outputw.inputRequested.connect(self._write_input)

    def _write_input(self, data):
        self.main_process.write(data.encode())
        self.main_process.write(b"\n")

    def is_running(self):
        running = False
        if self.main_process.state() == QProcess.Running:
            running = True
        return running

    def _process_started(self):
        time_str = QTime.currentTime().toString("hh:mm:ss")
        text = time_str + " Running: " + self.process_name
        self.outputw.append_text(text)
        self.outputw.setReadOnly(False)

    def _process_finished(self, code, status):
        frmt = OutputWidget.Format.NORMAL
        if status == QProcess.NormalExit == code:
            text = translations.TR_PROCESS_EXITED_NORMALLY % code
        else:
            text = translations.TR_PROCESS_INTERRUPTED
            frmt = OutputWidget.Format.ERROR
        self.outputw.append_text(text, frmt)
        if self.__current_process is self.main_process:
            tformat = QTime(0, 0, 0, 0).addMSecs(
                self.__elapsed.elapsed() + 500)
            time = tformat.toString("h:mm:ss")
            if time.startswith("0:"):
                # Don't display zero hours
                time = time[2:]
            self.outputw.append_text(translations.TR_ELAPSED_TIME.format(time))
        self.outputw.setReadOnly(True)

    def _refresh_output(self):
        data = self.__current_process.readAllStandardOutput().data().decode()
        for line in data.splitlines():
            self.outputw.append_text(
                line, text_format=OutputWidget.Format.NORMAL)

    def _refresh_error(self):
        data = self.__current_process.readAllStandardError().data().decode()
        for line_text in data.splitlines():
            frmt = OutputWidget.Format.ERROR
            if self.outputw.patLink.match(line_text):
                frmt = OutputWidget.Format.ERROR_UNDERLINE
            self.outputw.append_text(line_text, frmt)

    def display_name(self):
        name = "New document"
        if not self.only_text:
            name = file_manager.get_basename(self.filename)
        return name

    @property
    def only_text(self):
        return self.filename is None

    @property
    def python_exec(self):
        py_exec = self.__python_exec
        if not py_exec:
            py_exec = settings.PYTHON_EXEC
        return py_exec

    @property
    def arguments(self):
        args = []
        if self.text_code:
            args.append("-c")
            args.append(self.text_code)
        else:
            # Force python to unbuffer stding and stdout
            args.append("-u")
            args += settings.EXECUTION_OPTIONS.split()
            args.append(self.filename)
        return args

    def kill(self):
        self.main_process.kill()
예제 #45
0
	def prepare(self):
		self.elapsedTimer=QElapsedTimer()
		self.elapsedTimer.start() #start time
		self.StartPosition=QPoint(GLOBAL.WINDOWWIDTH+random.randrange(200,500,20),\
			(Bullet.Height+(Bullet.Count%(GLOBAL.WINDOWHEIGHT//Bullet.Height))*Bullet.Height))
		self.EndPosition=QPoint(-2000 ,self.StartPosition.y())
예제 #46
0
class DedeNimeur(QMainWindow):
    def __init__(self):
        super(DedeNimeur, self).__init__()
        self.statusBar()

        self.size, self.height, self.width, self.mines = 30, 10, 10, 10
        self.lcd = QLCDNumber()
        self.lcd.setFixedSize(300, 60)
        self.board = Board(self.height, self.width, self.mines, self.size)
        self.timer = QBasicTimer()
        self.real_timer = QElapsedTimer()

        vbox = QVBoxLayout()
        vbox.addWidget(self.lcd)
        vbox.addWidget(self.board)

        central = QWidget()
        central.setLayout(vbox)
        self.setCentralWidget(central)

        start = QAction('Start', self)
        start.setStatusTip('Start')
        start.setShortcut('Ctrl+N')
        start.triggered.connect(self.init)

        exit = QAction('Exit', self)
        exit.setStatusTip('Exit')
        exit.setShortcut('Ctrl+Q')
        exit.triggered.connect(qApp.quit)

        height = QAction('Height', self)
        height.setStatusTip('Set board width')
        height.triggered.connect(self.set_height)
        width = QAction('Width', self)
        width.setStatusTip('Set board height')
        width.triggered.connect(self.set_width)
        mines = QAction('Mines', self)
        mines.setStatusTip('Set board mines')
        mines.triggered.connect(self.set_mines)
        size = QAction('Size', self)
        size.setStatusTip('Set button size')
        size.triggered.connect(self.set_size)

        toolbar = self.addToolBar('Toolbar')
        toolbar.addAction(start)
        toolbar.addAction(width)
        toolbar.addAction(height)
        toolbar.addAction(mines)
        toolbar.addAction(size)
        toolbar.addAction(exit)

        self.setWindowTitle(u'DédéNimeur')
        self.show()

    def init(self):
        if self.mines < self.height * self.width:
            self.board.height = self.height
            self.board.width = self.width
            self.board.mines = self.mines
            self.board.size = self.size
            self.board.init()
        else:
            QMessageBox.question(self, 'NOPE', u"Va falloir spécifier un truc cohérent…", QMessageBox.Ok)

    def set_height(self):
        text, ok = QInputDialog.getText(self, 'Settings', 'height')
        if ok:
            self.height = int(text)
            self.init()

    def set_width(self):
        text, ok = QInputDialog.getText(self, 'Settings', 'width')
        if ok:
            self.width = int(text)
            self.init()

    def set_mines(self):
        text, ok = QInputDialog.getText(self, 'Settings', 'mines')
        if ok:
            self.mines = int(text)
            self.init()

    def set_size(self):
        text, ok = QInputDialog.getText(self, 'Settings', 'size')
        if ok:
            self.size = int(text)
            self.init()

    def start_timers(self):
        self.timer.start(100, self)
        self.real_timer.start()
        self.lcd.display(int(self.real_timer.elapsed() / 1000))

    def stop_timers(self):
        self.timer.stop()
        return self.real_timer.elapsed()

    def timerEvent(self, e):
        self.lcd.display(int(self.real_timer.elapsed() / 1000))
예제 #47
0
파일: view.py 프로젝트: duniter/sakia
class ConnectionConfigView(QDialog, Ui_ConnectionConfigurationDialog):
    """
    Connection config view
    """
    values_changed = pyqtSignal()

    def __init__(self, parent):
        """
        Constructor
        """
        super().__init__(parent)
        self.setupUi(self)
        self.last_speed = 0.1
        self.average_speed = 1
        self.timer = QElapsedTimer()
        self.edit_uid.textChanged.connect(self.values_changed)
        self.edit_password.textChanged.connect(self.values_changed)
        self.edit_password_repeat.textChanged.connect(self.values_changed)
        self.edit_salt.textChanged.connect(self.values_changed)
        self.edit_pubkey.textChanged.connect(self.values_changed)
        self.button_generate.clicked.connect(self.action_show_pubkey)
        self.text_license.setReadOnly(True)

        self.combo_scrypt_params.currentIndexChanged.connect(self.handle_combo_change)
        self.scrypt_params = ScryptParams(4096, 16, 1)
        self.spin_n.setMaximum(2 ** 20)
        self.spin_n.setValue(self.scrypt_params.N)
        self.spin_n.valueChanged.connect(self.handle_n_change)
        self.spin_r.setMaximum(128)
        self.spin_r.setValue(self.scrypt_params.r)
        self.spin_r.valueChanged.connect(self.handle_r_change)
        self.spin_p.setMaximum(128)
        self.spin_p.setValue(self.scrypt_params.p)
        self.spin_p.valueChanged.connect(self.handle_p_change)
        self.label_info.setTextFormat(Qt.RichText)

    def handle_combo_change(self, index):
        strengths = [
            (2 ** 12, 16, 1),
            (2 ** 14, 32, 2),
            (2 ** 16, 32, 4),
            (2 ** 18, 64, 8),
        ]
        self.spin_n.blockSignals(True)
        self.spin_r.blockSignals(True)
        self.spin_p.blockSignals(True)
        self.spin_n.setValue(strengths[index][0])
        self.spin_r.setValue(strengths[index][1])
        self.spin_p.setValue(strengths[index][2])
        self.spin_n.blockSignals(False)
        self.spin_r.blockSignals(False)
        self.spin_p.blockSignals(False)

    def set_license(self, currency):
        license_text = self.tr(G1_LICENCE)
        self.text_license.setText(license_text)

    def handle_n_change(self, value):
        spinbox = self.sender()
        self.scrypt_params.N = ConnectionConfigView.compute_power_of_2(spinbox, value, self.scrypt_params.N)

    def handle_r_change(self, value):
        spinbox = self.sender()
        self.scrypt_params.r = ConnectionConfigView.compute_power_of_2(spinbox, value, self.scrypt_params.r)

    def handle_p_change(self, value):
        spinbox = self.sender()
        self.scrypt_params.p = ConnectionConfigView.compute_power_of_2(spinbox, value, self.scrypt_params.p)

    @staticmethod
    def compute_power_of_2(spinbox, value, param):
        if value > 1:
            if value > param:
                value = pow(2, ceil(log(value) / log(2)))
            else:
                value -= 1
                value = 2 ** int(log(value, 2))
        else:
            value = 1

        spinbox.blockSignals(True)
        spinbox.setValue(value)
        spinbox.blockSignals(False)

        return value

    def display_info(self, info):
        self.label_info.setText(info)

    def set_currency(self, currency):
        self.label_currency.setText(currency)

    def add_node_parameters(self):
        server = self.lineedit_add_address.text()
        port = self.spinbox_add_port.value()
        return server, port

    async def show_success(self, notification):
        if notification:
            toast.display(self.tr("UID broadcast"), self.tr("Identity broadcasted to the network"))
        else:
            await QAsyncMessageBox.information(self, self.tr("UID broadcast"),
                                               self.tr("Identity broadcasted to the network"))

    def show_error(self, notification, error_txt):
        if notification:
            toast.display(self.tr("UID broadcast"), error_txt)
        self.label_info.setText(self.tr("Error") + " " + error_txt)

    def set_nodes_model(self, model):
        self.tree_peers.setModel(model)

    def set_creation_layout(self, currency):
        """
        Hide unecessary buttons and display correct title
        """
        self.setWindowTitle(self.tr("New connection to {0} network").format(ROOT_SERVERS[currency]["display"]))

    def action_show_pubkey(self):
        salt = self.edit_salt.text()
        password = self.edit_password.text()
        pubkey = SigningKey(salt, password, self.scrypt_params).pubkey
        self.label_info.setText(pubkey)

    def account_name(self):
        return self.edit_account_name.text()

    def set_communities_list_model(self, model):
        """
        Set communities list model
        :param sakia.models.communities.CommunitiesListModel model:
        """
        self.list_communities.setModel(model)

    def stream_log(self, log):
        """
        Add log to
        :param str log:
        """
        self.plain_text_edit.appendPlainText(log)

    def progress(self, step_ratio):
        """

        :param float ratio: the ratio of progress of current step (between 0 and 1)
        :return:
        """
        SMOOTHING_FACTOR = 0.005
        if self.timer.elapsed() > 0:
            value = self.progress_bar.value()
            next_value = value + 1000000*step_ratio
            speed_percent_by_ms = (next_value - value) / self.timer.elapsed()
            self.average_speed = SMOOTHING_FACTOR * self.last_speed + (1 - SMOOTHING_FACTOR) * self.average_speed
            remaining = (self.progress_bar.maximum() - next_value) / self.average_speed
            self.last_speed = speed_percent_by_ms
            displayed_remaining_time = QDateTime.fromTime_t(remaining).toUTC().toString("hh:mm:ss")
            self.progress_bar.setFormat(self.tr("{0} remaining...".format(displayed_remaining_time)))
            self.progress_bar.setValue(next_value)
            self.timer.restart()

    def set_progress_steps(self, steps):
        self.progress_bar.setValue(0)
        self.timer.start()
        self.progress_bar.setMaximum(steps*1000000)

    def set_step(self, step):
        self.progress_bar.setValue(step * 1000000)

    async def show_register_message(self, blockchain_parameters):
        """

        :param sakia.data.entities.BlockchainParameters blockchain_parameters:
        :return:
        """
        days, hours, minutes, seconds = timestamp_to_dhms(blockchain_parameters.idty_window)
        expiration_time_str = self.tr("{days} days, {hours}h  and {min}min").format(days=days,
                                                                                    hours=hours,
                                                                                    min=minutes)

        dialog = QDialog(self)
        about_dialog = Ui_CongratulationPopup()
        about_dialog.setupUi(dialog)
        dialog.setWindowTitle("Registration")
        about_dialog.label.setText(self.tr("""
<p><b>Congratulations !</b><br>
<br>
You just published your identity to the network.<br>
For your identity to be registered, you will need<br>
<b>{certs} certifications</b> from members.<br>
Once you got the required certifications, <br>
you will be able to validate your registration<br>
by <b>publishing your membership request !</b><br>
Please notice that your identity document <br>
<b>will expire in {expiration_time_str}.</b><br>
If you failed to get {certs} certifications before this time, <br>
the process will have to be restarted from scratch.</p>
""".format(certs=blockchain_parameters.sig_qty, expiration_time_str=expiration_time_str)))

        await dialog_async_exec(dialog)