예제 #1
0
    def sendRang(self, rectIndex=[]):

        if self.RangeItem.rect() != self.parentRect.rect():
            self.BtnsWidget.setPalActive()
        else:
            self.BtnsWidget.setPalDisActive()
        if self.chartTypes == "Bar":
            v = 3
        else:
            v = 2
        if rectIndex == []:
            maxData = QDateTime.fromMSecsSinceEpoch(
                self.zoomSeries.at(len(self.RangeItem.rangePoints) - v).x())
            minData = QDateTime.fromMSecsSinceEpoch(self.zoomSeries.at(0).x())
        else:
            minData = max(rectIndex[0], 0)
            maxData = min(rectIndex[1], len(self.RangeItem.rangePoints) - v)
            minData = QDateTime.fromMSecsSinceEpoch(
                self.zoomSeries.at(minData).x())
            maxData = QDateTime.fromMSecsSinceEpoch(
                self.zoomSeries.at(maxData).x())

        if minData > maxData:
            if self.RangeItem.handleSelected is None:
                self.resetView()
        else:
            self.BtnsWidget.dateRangeEdit.setDate([
                minData.toString("yyyy-MM-dd"),
                maxData.toString("yyyy-MM-dd")
            ])
            if self.relationState:
                self.rangeSig.emit([
                    minData.toString("yyyy-MM-dd HH:mm:ss"),
                    maxData.toString("yyyy-MM-dd HH:mm:ss"),
                ])
예제 #2
0
    def update_interval(self):
        self.interval_msecs = self.dockwidget.spinBox_duration.value(
        ) * 3600000

        start_time_msecs = self.dockwidget.dateTimeEdit_start.dateTime(
        ).toMSecsSinceEpoch()
        animation_start_time_msecs = floor(
            start_time_msecs / self.interval_msecs) * self.interval_msecs
        self.animation_start_time = QDateTime.fromMSecsSinceEpoch(
            animation_start_time_msecs)

        end_time_msecs = self.dockwidget.dateTimeEdit_end.dateTime(
        ).toMSecsSinceEpoch()
        animation_end_time_msecs = ceil(
            end_time_msecs / self.interval_msecs) * self.interval_msecs
        self.animation_end_time = QDateTime.fromMSecsSinceEpoch(
            animation_end_time_msecs)

        number_of_frames = round(
            (animation_end_time_msecs - animation_start_time_msecs) /
            self.interval_msecs) + 1

        self.dockwidget.label_animation_start.setText(
            self.animation_start_time.toString(
                self.dockwidget.dateTimeEdit_start.displayFormat()))
        self.dockwidget.label_animation_end.setText(
            self.animation_end_time.toString(
                self.dockwidget.dateTimeEdit_end.displayFormat()))
        self.dockwidget.label_frames.setText(u'%s frames' % number_of_frames)

        self.dockwidget.horizontalSlider_frames.setMinimum(1)
        self.dockwidget.horizontalSlider_frames.setMaximum(number_of_frames)
        self.dockwidget.horizontalSlider_frames.setValue(number_of_frames)
예제 #3
0
    async def onBwStats(self, stats):
        dtNow = QDateTime.currentDateTime()
        dtMsecs = dtNow.toMSecsSinceEpoch()

        delta = 120 * 1000
        if not self.seriesPurgedT or (dtMsecs - self.seriesPurgedT) > delta:
            self.removeOldSeries(self.seriesKbIn, dtMsecs - delta)
            self.removeOldSeries(self.seriesKbOut, dtMsecs - delta)
            self.seriesPurgedT = dtMsecs

        rateIn = stats.get('RateIn', 0)
        rateOut = stats.get('RateOut', 0)
        rateInKb = int(rateIn / 1024)
        rateOutKb = int(rateOut / 1024)

        inVector = self.seriesKbIn.pointsVector()
        outVector = self.seriesKbIn.pointsVector()

        inValues = [p.y() for p in inVector]
        outValues = [p.y() for p in outVector]

        if inValues or outValues:
            self.axisY.setMax(max(max(inValues), max(outValues)))

        dateMin = QDateTime.fromMSecsSinceEpoch(dtMsecs - (30 * 1000))
        dateMax = QDateTime.fromMSecsSinceEpoch(dtMsecs + 2000)

        self.seriesKbIn.append(dtMsecs, rateInKb)
        self.seriesKbOut.append(dtMsecs, rateOutKb)
        self.axisX.setRange(dateMin, dateMax)
예제 #4
0
파일: Chart.py 프로젝트: MeisterTJ/Bithumb
    def __updateAxis(self):
        # QLineSerires 객체에 저장된 데이터를 리스트로 얻어온다.
        # pvs에 저장된 리스트 안에는 QPointF 객체로 위치 정보가 저장되어 있다.
        pvs = self.priceData.pointsVector()

        # 가장 오래된 0번 인덱스의 객체를 하나 선택해서 x 좌표에 저장된 값을 가져온다.
        # ms로 변환해서 들어간 좌표 데이터를 fromMSecsSinceEpoch 메서드를 사용해서 QDateTime 객체로 변환한다.
        dtStart = QDateTime.fromMSecsSinceEpoch(int(pvs[0].x()))

        # 데이터가 꽉 차 있다면 최근 시간 정보가 들어 있는 마지막 객체를 선택한다.
        if len(self.priceData) == self.viewLimit:
            dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1].x()))
        # 데이터가 꽉 차 있지 않다면 시작 위치를 기준으로 viewLimit 초 이후까지 출력한다.
        # 항상 viewLimit 개의 데이터를 출력하는데 사용된다.
        else:
            dtLast = dtStart.addSecs(self.viewLimit)

        # 앞서 얻어온 위치 정보를 보여줄 수 있도록 X 축의 범위를 설정한다.
        ax = self.priceChart.axisX()
        ax.setRange(dtStart, dtLast)

        # QPointF 객체에서 y 좌표를 가져와서 최소값, 최대값으로 Y축에 표시될 범위를 지정한다.
        ay = self.priceChart.axisY()
        dataY = [v.y() for v in pvs]
        ay.setRange(min(dataY), max(dataY))
예제 #5
0
파일: chart.py 프로젝트: sangcle/GreatFirst
 def __updateAxis(self):
     pvs = self.tm
     dtStart = QDateTime.fromMSecsSinceEpoch(int(pvs[0]))
     if len(self.priceData) == self.viewLimit:
         dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1]))
     else:
         dtLast = dtStart.addSecs(self.viewLimit)
     ax = self.priceChart.axisX()
     ax.setRange(dtStart, dtLast)
예제 #6
0
    def __updateAxis(self):
        pvs = self.priceData.pointsVector()
        dtStart = QDateTime.fromMSecsSinceEpoch(int(pvs[0].x()))
        if len(self.priceData) == self.viewLimit:
            dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1].x()))
        else:
            dtLast = dtStart.addSecs(self.viewLimit)
        ax = self.priceChart.axisX()
        ax.setRange(dtStart, dtLast)

        ay = self.priceChart.axisY()
        dataY = [v.y() for v in pvs]
        ay.setRange(min(dataY), max(dataY))
예제 #7
0
 def _update_data_sync_status(self):
     app_data = self._wow_helper.get_app_data()
     if not app_data:
         self.set_main_window_sync_status_data.emit([])
         return
     # check data sync status versions
     sync_status = []
     for realm_name, info in self._data_sync_status.items():
         last_auctiondb_update = app_data.last_update(
             "AUCTIONDB_MARKET_DATA", realm_name)
         if info['auctiondb'] > last_auctiondb_update:
             # an update is pending
             auctiondb_status = {'text': "Updating..."}
             if last_auctiondb_update > 0:
                 update_time_status = {
                     'text':
                     QDateTime.fromMSecsSinceEpoch(
                         last_auctiondb_update * 1000).toString(
                             Qt.SystemLocaleShortDate)
                 }
             else:
                 update_time_status = {'text': "-"}
         else:
             auctiondb_status = {'text': "Up to date"}
             if last_auctiondb_update > 0:
                 update_time_status = {
                     'text':
                     QDateTime.fromMSecsSinceEpoch(
                         last_auctiondb_update * 1000).toString(
                             Qt.SystemLocaleShortDate)
                 }
             else:
                 update_time_status = {'text': "-"}
         if 'shopping' not in info:
             shopping_status = {'text': "N/A"}
         elif info['shopping'] == -1:
             # they aren't premium so don't get shopping data
             shopping_status = {'text': "Go premium to enable"}
         elif info['shopping'] > app_data.last_update(
                 "SHOPPING_SEARCHES", realm_name):
             # an update is pending
             shopping_status = {'text': "Updating..."}
         else:
             shopping_status = {'text': "Up to date"}
         name = "{}-{}".format(
             info['region'],
             realm_name) if info['type'] == "realm" else realm_name
         sync_status.append([{
             'text': name
         }, auctiondb_status, shopping_status, update_time_status])
     self.set_main_window_sync_status_data.emit(sync_status)
예제 #8
0
	def Rescale_Axes( self, index ):
		x = self.temperatureSeries.at( index ).x()
		x_rescaled = False
		if( x < self.xMin ):
			self.xMin = x
			x_rescaled = True
		if( x > self.xMax ):
			self.xMax = x
			x_rescaled = True
		if( x_rescaled ):
			full_range = min( self.xMax - self.xMin, 5 * 60 * 1000 )
			margin = full_range * 0.05

			self.chart.axisX().setRange( QDateTime.fromMSecsSinceEpoch(self.xMax - full_range - margin), QDateTime.fromMSecsSinceEpoch(self.xMax + margin) )
			
		y = self.temperatureSeries.at( index ).y()
		y_rescaled = False
		if( y < self.yMin ):
			self.yMin = y
			y_rescaled = True
		if( y > self.yMax ):
			self.yMax = y
			y_rescaled = True
		if( y_rescaled ):
			full_range = self.yMax - self.yMin
			margin = full_range * 0.05
			self.chart.axisY().setRange( self.yMin - margin, self.yMax + margin )
			
예제 #9
0
 def _select_source_file(self):
     options = QFileDialog.Options(QFileDialog.DontUseNativeDialog)
     filename, _ = QFileDialog.getOpenFileName(
         self,
         'Select source file',
         self._source_filename_txt.text(),
         filter='Video files (*.avi *.mpeg *.mp4);;All files (*)',
         options=options)
     if filename:
         movie_file = self._update_source_filename(filename)
         if movie_file:
             # update acquisition time from the file name which should contain the start of the acquisition
             acq_time_group = re.search('SR(\d{8}T\d{6})_movie.*', filename)
             if acq_time_group is not None:
                 self._update_acq_time(
                     QDateTime.fromString(acq_time_group.group(1),
                                          'yyyyMMddTHHmmss'))
             else:
                 movie_file_path = Path(filename)
                 movie_file_ts_millis = movie_file_path.stat(
                 ).st_mtime * 1000
                 self._update_acq_time(
                     QDateTime.fromMSecsSinceEpoch(
                         int(movie_file_ts_millis)))
             # update image size
             image_size = movie_file.get_size()
             self._update_image_width(image_size[0])
             self._update_image_height(image_size[1])
 def set_current_capture(self, capture_number):
     capture_id = self.distances[capture_number - 1][0]
     capture_filename = 'IMG_{}.jpg'.format(capture_id)
     capture = QPixmap(os.path.join(self.dir, capture_filename))
     self.captureViewLabel.setPixmap(capture)
     self.captureDateTimeEdit.setDateTime(
         QDateTime.fromMSecsSinceEpoch(int(capture_id)))
     self.distancesLineEdit.setText('|' +
                                    '|'.join(self.distances[capture_number -
                                                            1][1:]) + '|')
예제 #11
0
    def reset_axes(self):
        """Resets the chart axes."""
        r = self.rankLine.pointsVector()
        p = self.priceLine.pointsVector()

        # If there is only one data point, set the min and max to the day before and the day after
        if len(r) == 1:
            tmin = QDateTime.fromMSecsSinceEpoch(r[0].x(), Qt.LocalTime).addDays(-1)
            tmax = QDateTime.fromMSecsSinceEpoch(r[0].x(), Qt.LocalTime).addDays(+1)
        else:
            tmin = min(r, key=lambda pt: pt.x(), default=QPointF(QDateTime.currentDateTime().addDays(-1).toMSecsSinceEpoch(), 0)).x()
            tmax = max(r, key=lambda pt: pt.x(), default=QPointF(QDateTime.currentDateTime().addDays(+1).toMSecsSinceEpoch(), 0)).x()
            tmin = QDateTime.fromMSecsSinceEpoch(tmin, Qt.LocalTime)
            tmax = QDateTime.fromMSecsSinceEpoch(tmax, Qt.LocalTime)

        self.timeAxis.setMin(tmin)
        self.timeAxis.setMax(tmax)

        # Find the min and max values of the series
        min_point = lambda pts: min(pts, key=lambda pt: pt.y(), default=QPointF(0, 0))
        max_point = lambda pts: max(pts, key=lambda pt: pt.y(), default=QPointF(0, 0))

        rmin = min_point(r)
        rmax = max_point(r)
        pmin = min_point(p)
        pmax = max_point(p)

        # Scale the mins and maxes to 'friendly' values
        scalemin = lambda v, step: ((v - step / 2) // step) * step
        scalemax = lambda v, step: ((v + step / 2) // step + 1) * step

        # The the axis bounds

        rmin = max(scalemin(rmin.y(), 1000), 0)
        rmax = scalemax(rmax.y(), 1000)
        pmin = max(scalemin(pmin.y(), 5), 0)
        pmax = scalemax(pmax.y(), 5)

        self.rankAxis.setMin(rmin)
        self.rankAxis.setMax(rmax)
        self.priceAxis.setMin(pmin)
        self.priceAxis.setMax(pmax)
예제 #12
0
    async def onPeersCount(self, count):
        dtNow = QDateTime.currentDateTime()
        dtMsecs = dtNow.toMSecsSinceEpoch()

        delta = 120 * 1000
        if not self.seriesPurgedT or (dtMsecs - self.seriesPurgedT) > delta:
            self.removeOldSeries(self.seriesPeers, dtMsecs - delta)
            self.seriesPurgedT = dtMsecs

        peersVector = self.seriesPeers.pointsVector()
        values = [p.y() for p in peersVector]

        if values:
            self.axisY.setMax(max(values) + 10)
            self.axisY.setMin(min(values) - 10)

        dateMin = QDateTime.fromMSecsSinceEpoch(dtMsecs - (30 * 1000))
        dateMax = QDateTime.fromMSecsSinceEpoch(dtMsecs + 2000)

        self.seriesPeers.append(dtMsecs, count)
        self.axisX.setRange(dateMin, dateMax)
예제 #13
0
파일: __init__.py 프로젝트: teoc98/Core
	def get_str(self, url):
		try:
			mtime = self._get_mtime(url)
		except OSError:
			return ''
		if mtime is None:
			return ''
		mtime_qt = QDateTime.fromMSecsSinceEpoch(int(mtime.timestamp() * 1000))
		time_format = QLocale().dateTimeFormat(QLocale.ShortFormat)
		# Always show two-digit years, not four digits:
		time_format = time_format.replace('yyyy', 'yy')
		return mtime_qt.toString(time_format)
예제 #14
0
    def update_linechart(self):
        if self.axisTime in self.chart.axes():
            self.chart.removeAxis(self.axisTime)

        if self.axisCurrentTime in self.chart.axes():
            self.chart.removeAxis(self.axisCurrentTime)

        if self.axisValue in self.chart.axes():
            self.chart.removeAxis(self.axisValue)

        if self.series in self.chart.series():
            self.chart.removeSeries(self.series)

        self.series.clear()

        self.axisValue.setMax(50)
        self.axisValue.setMin(-50)

        req = """
              SELECT tmp, time_from_epoch
              FROM short_term_data
              WHERE (time_from_epoch - ?) < 86400 AND NOT tmp = ?
              """

        cur = self.con.cursor()
        result = list(cur.execute(req, (int(dt.datetime.now().timestamp()), ERROR_CODE)))

        for measure in result:
            self.series.append(measure[1] * 1000, measure[0])

        self.axisTime.setMin(QDateTime.fromMSecsSinceEpoch(int(dt.datetime.now().timestamp()) * 1000 - 86390000))
        self.axisTime.setMax(QDateTime.fromMSecsSinceEpoch(int(dt.datetime.now().timestamp()) * 1000))

        self.chart.addSeries(self.series)
        self.chart.addAxis(self.axisTime, Qt.AlignBottom)
        self.series.attachAxis(self.axisTime)
        self.chart.addAxis(self.axisValue, Qt.AlignLeft)
        self.series.attachAxis(self.axisValue)

        self.chart.setTitle('Температура')
예제 #15
0
    def do_candleClicked(self, dataSet):
        valOpen = dataSet.open()
        valClose = dataSet.close()
        valHigh = dataSet.high()
        valLow = dataSet.low()
        price = "开盘%.2f, 收盘%.2f, 最高%.2f, 最低%.2f" % (valOpen, valClose, valHigh,
                                                    valLow)

        timeStamp = dataSet.timestamp()  #时间戳数据
        dt = QDateTime.fromMSecsSinceEpoch(timeStamp)
        dateStr = dt.toString("yyyy-MM-dd, ")

        self.__labClickXY.setText(dateStr + price)
예제 #16
0
    def get_price(self, cur_price):
        if len(self.series) == 128:
            self.series.remove(0)  # delete first data

        # append current price
        dt = QDateTime.currentDateTime()
        ts = dt.toMSecsSinceEpoch()
        self.series.append(ts, cur_price)
        print(ts, cur_price)

        # update asis
        data = self.series.pointsVector()
        first_ts = data[0].x()
        last_ts = data[-1].x()
        first_dt = QDateTime.fromMSecsSinceEpoch(first_ts)
        last_dt = QDateTime.fromMSecsSinceEpoch(last_ts)

        axis_x = self.chart.axisX()
        axis_x.setRange(first_dt, last_dt)

        axis_y = self.chart.axisY()
        axis_y.setRange(70000000, 71000000)
예제 #17
0
def main():
    import sys

    a = QApplication(sys.argv)

    acmeSeries = QCandlestickSeries()
    acmeSeries.setName("Acme Ltd")
    acmeSeries.setIncreasingColor(QColor(Qt.green))
    acmeSeries.setDecreasingColor(QColor(Qt.red))

    acmeData = QFile(":acme")
    if not acmeData.open(QIODevice.ReadOnly | QIODevice.Text):
        sys.exit(1)

    categories = []

    dataReader = CandlestickDataReader(acmeData)
    while not dataReader.atEnd():
        _set = dataReader.readCandlestickSet()
        if _set is not None:
            acmeSeries.append(_set)
            categories.append(
                QDateTime.fromMSecsSinceEpoch(int(
                    _set.timestamp())).toString("dd"))

    chart = QChart()
    chart.addSeries(acmeSeries)
    chart.setTitle("Acme Ltd Historical Data (July 2015)")
    chart.setAnimationOptions(QChart.SeriesAnimations)

    chart.createDefaultAxes()

    axisX = chart.axes(Qt.Horizontal)[0]
    axisX.setCategories(categories)

    axisY = chart.axes(Qt.Vertical)[0]
    axisY.setMax(axisY.max() * 1.01)
    axisY.setMin(axisY.min() * 0.99)

    chart.legend().setVisible(True)
    chart.legend().setAlignment(Qt.AlignBottom)

    chartView = QChartView(chart)
    chartView.setRenderHint(QPainter.Antialiasing)

    window = QMainWindow()
    window.setCentralWidget(chartView)
    window.resize(800, 600)
    window.show()

    sys.exit(a.exec_())
예제 #18
0
 def update_slider(self):
     frame_epoch = ((self.dockwidget.horizontalSlider_frames.value() - 1) *
                    self.interval_msecs
                    ) + self.animation_start_time.toMSecsSinceEpoch()
     frame_time = QDateTime.fromMSecsSinceEpoch(frame_epoch)
     self.frame_time = frame_time
     self.dockwidget.label_actual_frame.setText(
         'frame: %s (%s)' %
         (self.dockwidget.horizontalSlider_frames.value(),
          frame_time.toString(
              self.dockwidget.dateTimeEdit_end.displayFormat())))
     #self.dockwidget.label_actual_frame.setText('frame: %s' % ())
     #self.log('update request')
     self.update_map(frame_epoch)
예제 #19
0
    def __updateAxis(self):
        #pointsVector 메서드를 사용해서 QLineSeries 객체에 저장된 데이터를 리스트로 얻어 옴
        pvs = self.priceData.pointsVector()
        dtStart = QDateTime.fromMSecsSinceEpoch(int(
            pvs[0].x()))  #가장 오래된 0번 인덱스 x 좌표에 저장된 값을 가져옴
        if len(self.priceData) == self.viewLimit:
            dtLast = QDateTime.fromMSecsSinceEpoch(int(pvs[-1].x(
            )))  #마지막 데이터는 119 번 인덱스에 저장 = 최근 시간 정보가 들어 있는 마지막 객체를 선택
        else:
            dtLast = dtStart.addSecs(
                self.viewLimit
            )  #viewLimit 보다 작다면 시작 위치 0번을 기준으로 viewLimit 초 이후까지 출력

        ax = self.priceChart.axisX()
        ax.setRange(dtStart, dtLast)

        ay = self.priceChart.axisY()
        dataY = [v.y() for v in pvs]
        ay.setRange(min(dataY), max(dataY))

        self.priceView.setChart(self.priceChart)
        self.priceView.setRenderHints(
            QPainter.Antialiasing)  #차트에 anti-aliasing을 적용
예제 #20
0
def tab_with_history(fake_web_tab, tabbed_browser_stubs, info, monkeypatch):
    """Returns a fake tab with some fake history items."""
    pytest.importorskip('PyQt5.QtWebEngineWidgets')
    tab = fake_web_tab(QUrl('https://github.com'), 'GitHub', 0)
    current_idx = 2
    monkeypatch.setattr(
        tab.history,
        'current_idx',
        lambda: current_idx,
    )

    history = []
    now = time.time()
    for url, title, ts in [
        ("http://example.com/index", "list of things", now),
        ("http://example.com/thing1", "thing1 detail", now + 5),
        ("http://example.com/thing2", "thing2 detail", now + 10),
        ("http://example.com/thing3", "thing3 detail", now + 15),
        ("http://example.com/thing4", "thing4 detail", now + 20),
    ]:
        entry = mock.Mock(spec=QWebEngineHistoryItem)
        entry.url.return_value = QUrl(url)
        entry.title.return_value = title
        dt = QDateTime.fromMSecsSinceEpoch(int(ts * 1000))
        entry.lastVisited.return_value = dt
        history.append(entry)
    tab.history._history = mock.Mock(spec=QWebEngineHistory)
    tab.history._history.items.return_value = history
    monkeypatch.setattr(
        tab.history,
        'back_items',
        lambda *_args:
        (entry for idx, entry in enumerate(tab.history._history.items())
         if idx < current_idx),
    )
    monkeypatch.setattr(
        tab.history,
        'forward_items',
        lambda *_args:
        (entry for idx, entry in enumerate(tab.history._history.items())
         if idx > current_idx),
    )

    tabbed_browser_stubs[0].widget.tabs = [tab]
    tabbed_browser_stubs[0].widget.current_index = 0

    info.cur_tab = tab
    return tab
예제 #21
0
    def do_candleHovered(self, status, dataSet):
        if status == False:
            self.__labHoverXY.setText("Hovered candle")
            return

        valOpen = dataSet.open()
        valClose = dataSet.close()
        valHigh = dataSet.high()
        valLow = dataSet.low()
        price = "开盘%.2f, 收盘%.2f, 最高%.2f, 最低%.2f" % (valOpen, valClose, valHigh,
                                                    valLow)

        timeStamp = dataSet.timestamp()  #时间戳数据
        dt = QDateTime.fromMSecsSinceEpoch(timeStamp)
        dateStr = dt.toString("yyyy-MM-dd, ")

        self.__labHoverXY.setText(dateStr + price)
예제 #22
0
    def setSamples(self, sample_list: SampleList) -> None:
        '''
        Replace current point data with given time samples.

        :param sample_list: Queue time samples to replace series data with
        '''
        points = []
        max_time = QDateTime.fromMSecsSinceEpoch(0)
        max_value = 10
        # Parse sample data
        for sample in sample_list:
            time = QDateTime.fromString(sample['time'], 'yyyy-MM-dd hh:mm')
            point = DetailedPointF(
                time.toMSecsSinceEpoch(),
                sample['queue_length']
            )
            if isinstance(self._user_data, dict):
                name = self._user_data.get('name')
            else:
                name = None
            point.setUserData({
                'name': name,
                'open_counters': sample['open_counters'],
                'queue_length': sample['queue_length'],
                'current_number': sample['current_number']})
            points.append(point)
            # Look for the newest sample time...
            if time > max_time:
                max_time = time
            # ...and the greates sample value
            if sample['queue_length'] > max_value:
                max_value = sample['queue_length']
        self.replace(points)
        chart = self.chart()
        if chart is not None:
            if chart.topSeriesIndex() == chart.series().index(self):
                chart.series()[-1].replace(points)
        # Move chart's horizontal axis according to the newest sample
        self.attachedAxes()[0].setRange(max_time.addSecs(-3600), max_time)
        self.attachedAxes()[0].hide()
        self.attachedAxes()[0].show()
        # Scale chart's vertical axis according to the greatest sample
        self.attachedAxes()[1].setMax(max_value)
        self.attachedAxes()[1].hide()
        self.attachedAxes()[1].show()
예제 #23
0
    def __init__(self, details, parent=None):
        """
        Constructor
        
        @param details dictionary containing the package details
        @type dict
        @param parent reference to the parent widget
        @type QWidget
        """
        super(CondaPackageDetailsWidget, self).__init__(parent)
        self.setupUi(self)

        self.headerLabel.setText(
            self.tr("<b>{0} / {1} / {2}</b>").format(details["name"],
                                                     details["version"],
                                                     details["build"]))
        if "fn" in details:
            self.filenameLabel.setText(details["fn"])
        if "size" in details:
            self.sizeLabel.setText(dataString(details["size"]))
        if "channel" in details:
            self.channelLabel.setText(details["channel"])
        if "url" in details:
            self.urlLabel.setText(details["url"])
        if "md5" in details:
            self.md5Label.setText(details["md5"])
        if "license" in details:
            self.licenseLabel.setText(details["license"])
        if "subdir" in details:
            self.platformLabel.setText(details["subdir"])
        elif "platform" in details:
            self.platformLabel.setText(details["platform"])
        else:
            self.platformLabel.setText(self.tr("unknown"))
        if "depends" in details:
            self.dependenciesEdit.setPlainText("\n".join(details["depends"]))

        if "timestamp" in details:
            dt = QDateTime.fromMSecsSinceEpoch(details["timestamp"], Qt.UTC)
            self.timestampLabel.setText(dt.toString("yyyy-MM-dd hh:mm:ss t"))

        self.resize(600, 450)
예제 #24
0
    def txt_from_tuple(self, item, column_tuple):
        value = getattr(item, column_tuple[0].name)

        if isinstance(column_tuple[0], peewee.ForeignKeyField):
            fk_obj = column_tuple[0].rel_model.get_by_id(value)
            txt = str(getattr(fk_obj, column_tuple[1]))
        elif isinstance(column_tuple[0], ChoiceField):
            for v in column_tuple[0].values:
                if v['id'] == value:
                    txt = column_tuple[0].values[value][column_tuple[1]]
        elif (isinstance(column_tuple[0], peewee.DateField)
              and value is not None):
            txt = QDate(value).toString(column_tuple[1])
        elif (isinstance(column_tuple[0], peewee.DateTimeField)
              and value is not None):
            import time
            secs_since_epoch = time.mktime(value.timetuple()) * 1000
            txt = QDateTime.fromMSecsSinceEpoch(secs_since_epoch).toString(
                column_tuple[1])
        else:
            txt = value
        return txt
예제 #25
0
    def fill_entries(self, planet, add, add_shared, skip):
        skip()
        add_shared(
            QDateTime.fromMSecsSinceEpoch(self._player.timestamp * 1000,
                                          Qt.LocalTime).toString(
                                              Qt.DefaultLocaleLongDate))
        add_shared(self._player.identity.name)
        if self._player.identity.HasField('alliance_name'):
            add_shared('{} ({})'.format(self._player.identity.alliance_name,
                                        self._player.identity.alliance_tag))
        else:
            add_shared('')
        add_shared(self._player.score.points)
        add_shared(self._player.score.honorific_points)
        add_shared('{} / {}'.format(self._player.score.rank,
                                    self._player.score.num_players))

        skip()
        add(planet.name)
        add('{}:{}:{}'.format(planet.coordinates.galaxy,
                              planet.coordinates.system,
                              planet.coordinates.position))
        add('{} km'.format(planet.diameter_km))
        add('{} / {}'.format(planet.size, planet.capacity))
        add('{} ºC to {} ºC'.format(planet.min_temperature,
                                    planet.max_temperature))

        skip()
        add(planet.resources.metal)
        add(planet.resources.crystal)
        add(planet.resources.deuterium)
        add(planet.resources.energy)
        add_shared(planet.resources.dark_matter)

        skip()
        if planet.mines.metal:
            add('Lvl {} ({}x)'.format(planet.mines.metal,
                                      planet.production_rates.metal))
        else:
            skip()
        if planet.mines.crystal:
            add('Lvl {} ({}x)'.format(planet.mines.crystal,
                                      planet.production_rates.crystal))
        else:
            skip()
        if planet.mines.deuterium:
            add('Lvl {} ({}x)'.format(planet.mines.deuterium,
                                      planet.production_rates.deuterium))
        else:
            skip()
        if planet.mines.solar_plant:
            add('Lvl {} ({}x)'.format(planet.mines.solar_plant,
                                      planet.production_rates.solar_plant))
        else:
            skip()
        if planet.mines.fusion_reactor:
            add('Lvl {} ({}x)'.format(planet.mines.fusion_reactor,
                                      planet.production_rates.fusion_reactor))
        else:
            skip()
        if planet.shipyard.solar_satellites:
            add('{} ({}x)'.format(planet.shipyard.solar_satellites,
                                  planet.production_rates.solar_satellites))
        else:
            skip()
        add('Lvl {}'.format(planet.mines.metal_storage))
        add('Lvl {}'.format(planet.mines.crystal_storage))
        add('Lvl {}'.format(planet.mines.deuterium_storage))

        skip()
        for facility in [
                'robotics_factory',
                'shipyard',
                'research_lab',
                'missile_silo',
                'nanite_factory',
                'space_dock',
                'lunar_base',
                'sensor_phalanx',
                'jump_gate',
        ]:
            level = getattr(planet.facilities, facility)
            if level:
                add('Lvl {}'.format(level))
            else:
                skip()

        skip()
        for research in [
                'energy',
                'laser',
                'ion',
                'hyperspace',
                'plasma',
                'espionage',
                'computer',
                'astrophysics',
                'combustion_drive',
                'impulse_drive',
                'hyperspace_drive',
                'weapons',
                'shielding',
                'armor',
        ]:
            level = getattr(self._player.research, research)
            if level:
                add_shared('Lvl {}'.format(level))
            else:
                skip()

        skip()
        for vessel in [
                'light_fighters',
                'heavy_fighters',
                'cruisers',
                'battleships',
                'battlecruisers',
                'bombers',
                'destroyers',
                'deathstars',
                'small_cargos',
                'large_cargos',
                'colony_ships',
                'recyclers',
                'espionage_probes',
                'solar_satellites',
        ]:
            num = getattr(planet.shipyard, vessel)
            if num:
                add(num)
            else:
                skip()

        skip()
        for defense in [
                'rocket_launchers',
                'light_lasers',
                'heavy_lasers',
                'gauss_canons',
                'ion_canons',
                'plasma_turrets',
                'anti_ballistic_missiles',
                'interplanetary_missiles',
        ]:
            num = getattr(planet.defense, defense)
            if num:
                add(num)
            else:
                skip()
        add('Yes' if planet.defense.has_small_shield_dome else 'No')
        add('Yes' if planet.defense.has_large_shield_dome else 'No')

        skip()
        add_shared(self._player.universe.name)
        add_shared(self._player.universe.speed)
        add_shared(self._player.universe.fleet_speed)
        add_shared('Yes' if self._player.universe.donut_galaxy else 'No')
        add_shared('Yes' if self._player.universe.donut_system else 'No')

        skip()
        add_shared('Yes' if self._player.officers.has_commander else 'No')
        add_shared('Yes' if self._player.officers.has_admiral else 'No')
        add_shared('Yes' if self._player.officers.has_engineer else 'No')
        add_shared('Yes' if self._player.officers.has_geologist else 'No')
        add_shared('Yes' if self._player.officers.has_technocrat else 'No')
예제 #26
0
#!/usr/bin/env python3

from PyQt5.QtCore import QDateTime, Qt

now = QDateTime.currentDateTime()

unix_time = now.toMSecsSinceEpoch()
print(unix_time)

d = QDateTime.fromMSecsSinceEpoch(unix_time)
print(d.toString(Qt.ISODate))
예제 #27
0
 def __get_qdatetime(self, py_datetime):
     epoch = time.mktime(py_datetime)
     self.log(epoch)
     result = QDateTime.fromMSecsSinceEpoch(epoch * 1000)
     self.log(result)
     return result
예제 #28
0
def extractProfileBulletDict(data, aw):
    try:
        res = {}  # the interpreted data set

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        return res
    except:
        #        import traceback
        #        import sys
        #        traceback.print_exc(file=sys.stdout)
        return {}
예제 #29
0
 def getCreationTime(self) -> QDateTime:
     time = QDateTime.fromMSecsSinceEpoch(self.lastsave)
     return time