Пример #1
0
/**
 * @brief TTiming::addWallClockIntervalOptimized skips to long distances
 * @param actual
 * @param calculated
 * @return
 */
QDateTime TTiming::addWallClockIntervalOptimized(QDateTime actual, QDateTime calculated)
{
    if (wall_clock.period.years == 0)
        calculated = calculated.addYears(actual.date().year()-calculated.date().year()); // should give 0 on iterations
    else
        calculated = calculated.addYears(wall_clock.period.years);
    if (wall_clock.period.months == 0)
        calculated = calculated.addMonths(actual.date().month()-calculated.date().month());
    else
        calculated = calculated.addMonths(wall_clock.period.months);

    if (wall_clock.period.days == 0)
        calculated = calculated.addDays(actual.date().day()-calculated.date().day());
    else
        calculated = calculated.addDays(wall_clock.period.days);
    if (wall_clock.period.hours == 0)
        calculated = calculated.addSecs((actual.time().hour()-calculated.time().hour())*3600);
    else
        calculated = calculated.addSecs(wall_clock.period.hours*3600);
    if (wall_clock.period.minutes == 0)
        calculated = calculated.addSecs((actual.time().minute()-calculated.time().minute())*60);
    else
        calculated = calculated.addSecs(wall_clock.period.minutes*60);
    return calculated.addSecs(wall_clock.period.seconds);
}
Пример #2
0
QDateTime TTiming::addWallClockInterval(QDateTime calculated)
{
    calculated = calculated.addYears(wall_clock.period.years);
    calculated = calculated.addMonths(wall_clock.period.months);
    calculated = calculated.addDays(wall_clock.period.days);
    return calculated.addSecs((wall_clock.period.hours*3600) + (wall_clock.period.minutes*60) + (wall_clock.period.seconds));
}
Пример #3
0
void DateVariable::update()
{
    QDateTime target;
    switch (m_type) {
    case Fixed:
        target = m_time;
        break;
    case AutoUpdate:
        target = QDateTime::currentDateTime();
        break;
    }
    target = target.addSecs(m_secsOffset);
    target = target.addDays(m_daysOffset);
    target = target.addMonths(m_monthsOffset);
    target = target.addYears(m_yearsOffset);
    switch (m_displayType) {
    case Custom:
        setValue(target.toString(m_definition));
        break;
    case Time:
        setValue(target.time().toString(Qt::LocalDate));
        break;
    case Date:
        setValue(target.date().toString(Qt::LocalDate));
        break;
    }
}
Пример #4
0
void QgsDateTimeEdit::resetBeforeChange( int delta )
{
  QDateTime dt = QDateTime::currentDateTime();
  switch ( currentSection() )
  {
    case QDateTimeEdit::DaySection:
      dt = dt.addDays( delta );
      break;
    case QDateTimeEdit::MonthSection:
      dt = dt.addMonths( delta );
      break;
    case QDateTimeEdit::YearSection:
      dt = dt.addYears( delta );
      break;
    default:
      break;
  }
  if ( dt < minimumDateTime() )
  {
    dt = minimumDateTime();
  }
  else if ( dt > maximumDateTime() )
  {
    dt = maximumDateTime();
  }
  QDateTimeEdit::setDateTime( dt );
}
void RollingFileAppender::computeFrequency()
{
  QMutexLocker locker(&m_rollingMutex);

  const QDateTime startTime(QDate(1999, 1, 1), QTime(0, 0));
  const QString startString = startTime.toString(m_datePatternString);

  if (startString != startTime.addSecs(60).toString(m_datePatternString))
    m_frequency = MinutelyRollover;
  else if (startString != startTime.addSecs(60 * 60).toString(m_datePatternString))
    m_frequency = HourlyRollover;
  else if (startString != startTime.addSecs(60 * 60 * 12).toString(m_datePatternString))
    m_frequency = HalfDailyRollover;
  else if (startString != startTime.addDays(1).toString(m_datePatternString))
    m_frequency = DailyRollover;
  else if (startString != startTime.addDays(7).toString(m_datePatternString))
    m_frequency = WeeklyRollover;
  else if (startString != startTime.addMonths(1).toString(m_datePatternString))
    m_frequency = MonthlyRollover;
  else
  {
    Q_ASSERT_X(false, "DailyRollingFileAppender::computeFrequency", "The pattern '%1' does not specify a frequency");
    return;
  }
}
Пример #6
0
QStringList EventModel::getOccurrences(int range, QDate dateFrom)const
{
    int securityCounter = 1000;
    QStringList result;

    QDateTime tmpDateTime = dateTime;
    do
    {
        if ((tmpDateTime.date().daysTo(QDate::currentDate()) <=0) && (QDate::currentDate().daysTo(tmpDateTime.date()) <= range ))
        result.push_back(tmpDateTime.toString(dateTimeFormatString));
        switch(repeatPeriod)
        {
        case(1):
            tmpDateTime = tmpDateTime.addDays(repeatEvery);
            break;
        case(7):
            tmpDateTime = tmpDateTime.addDays(repeatEvery*7);
            break;
        case(30):
            tmpDateTime = tmpDateTime.addMonths(repeatEvery);
            break;
        case(0):
        default:
            break;
        }
        securityCounter--;

    } while ((securityCounter > 0) && (QDate::currentDate().daysTo(tmpDateTime.date()) <= range ) && (repeatPeriod!=0) );
    return result;
}
void
NetworkActivityWidget::fetchMonthCharts()
{
    QDateTime to = QDateTime::currentDateTime();
    QDateTime monthAgo = to.addMonths( -1 );
    DatabaseCommand_NetworkCharts* monthCharts = new DatabaseCommand_NetworkCharts( monthAgo, to );
    monthCharts->setLimit( numberOfNetworkChartEntries );
    connect( monthCharts, SIGNAL( done( QList<Tomahawk::track_ptr> ) ), SLOT( monthlyCharts( QList<Tomahawk::track_ptr> ) ) );
    Database::instance()->enqueue( Tomahawk::dbcmd_ptr( monthCharts ) );
}
Пример #8
0
int Indications::New(int id_pok_old, QString value_home)
{
    int id_new = -1;
    int date_old = -1, id_ListApart=-1;
    QString str;
    QStringList column, value;
    QSqlQuery query;

    //  найдём дату текущих показаний
    str = "SELECT date_pokazanie, id_list_app_usluga FROM pokazanie WHERE id_pokazanie=%1";
    str = str.arg(id_pok_old);

    if (query.exec(str)){
        if (query.next()){
            date_old =  query.value(0).toInt();
            id_ListApart = query.value(1).toInt();
        }else{
            qDebug() << "not record" << "575af8aa8da14fec062ce2bc5ef9e1e8 " << str;
        }
    } else{
            qDebug()<<query.lastError();
    }
    QDateTime time;
    time = time.fromTime_t(date_old);
    time = time.addMonths(1);
    DateOfUnixFormat date(time.date());

    //Проверим на существование показаний на след месяц
    str = "SELECT id_pokazanie FROM pokazanie "
            "WHERE date_pokazanie=%1 AND id_list_app_usluga=%2";
    str = str.arg(date.Second())
            .arg(QString::number(id_ListApart));
    QString id_pok_var;
    BD::SelectFromTable(str,&id_pok_var);
    if(id_pok_var == ""){//если нет записей
        //добавим новое показание на след месяц
        column.clear();
        column<<"id_list_app_usluga"<<"date_pokazanie"<<"pokazanie_home"<<"pokazanie_end";
        value.append(QString::number(id_ListApart));
        value.append(QString::number(date.Second()));
        value.append(value_home);
        value.append(QString::number(0));
        if (BD::add("pokazanie",column,value).number() != 0){
            return -1;
        }
    }else{//иначе
        //Обновим запись
        BD::UpdateTable("pokazanie","pokazanie_home",value_home,"id_pokazanie",id_pok_var);
        return id_pok_var.toInt();
    }
    return id_new;
}
Пример #9
0
void AlarmView::snoozeClicked()
{
    mAlarmTimer.stop();

    /* Snooze for some amount of time (configured in settings, say) */
    int snoozeindex = mSnoozeChoices->currentIndex();

    int snoozedelay = 60;
    // Make sure we set alarms on the minute by rounding
    QDateTime now = QDateTime::currentDateTime();
    int seconds = now.time().second();
    if (seconds >= 30)
        now = now.addSecs(60 - seconds);
    else
        now = now.addSecs(-seconds);

    switch(snoozeindex) {
        case 0: // 5 minutes
            snoozedelay = 300;
            break;
        case 1: // 10 minutes
            snoozedelay = 600;
            break;
        case 2: // 15 minutes
            snoozedelay = 900;
            break;
        case 3: // 30 minutes
            snoozedelay = 1800;
            break;
        case 4: // 1 hour
            snoozedelay = 3600;
            break;
        case 5: // 1 day
            snoozedelay = 24 * 60;
            break;
        case 6: // 1 week
            snoozedelay = 7 * 24 * 60;
            break;
        case 7: // 1 month hmm
            {
                QDateTime then = now.addMonths(1);
                snoozedelay = now.secsTo(then);
            }
            break;
    }

    QDateTime snoozeTime = now.addSecs(snoozedelay);
    Qtopia::addAlarm(snoozeTime, "Calendar", "alarm(QDateTime,int)", snoozeTime.secsTo(mStartTime) / 60);

    emit closeView();
}
Пример #10
0
/*! Paints the month scale header.
 * \sa paintHeader()
 */
void DateTimeGrid::paintMonthScaleHeader( QPainter* painter,  const QRectF& headerRect, const QRectF& exposedRect,
                                        qreal offset, QWidget* widget )
{
    QStyle* style = widget?widget->style():QApplication::style();

    // Paint a section for each month
    QDateTime sdt = d->chartXtoDateTime( offset+exposedRect.left() );
    sdt.setTime( QTime( 0, 0, 0, 0 ) );
    sdt = sdt.addDays( 1 - sdt.date().day() );
    QDateTime dt = sdt;
    for ( qreal x = d->dateTimeToChartX( dt ); x < exposedRect.right()+offset;
            dt = dt.addMonths( 1 ),x=d->dateTimeToChartX( dt ) ) {
        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x-offset, headerRect.top()+headerRect.height()/2., dayWidth()*dt.date().daysInMonth(), headerRect.height()/2. ).toRect();
        opt.text = QDate::shortMonthName( dt.date().month() );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }
    }

    // Paint a section for each year
    dt = sdt;
    for ( qreal x2 = d->dateTimeToChartX( dt ); x2 < exposedRect.right()+offset; x2=d->dateTimeToChartX( dt ) ) {
        //qDebug()<<"paintMonthScaleHeader()"<<dt;
        QDate next = dt.date().addYears( 1 );
        next = next.addMonths( 1 - next.month() );

        QStyleOptionHeader opt;
        opt.init( widget );
        opt.rect = QRectF( x2-offset, headerRect.top(), dayWidth()*dt.date().daysTo( next ), headerRect.height()/2. ).toRect();
        opt.text = QString::number( dt.date().year() );
        opt.textAlignment = Qt::AlignCenter;
        // NOTE:CE_Header does not honor clipRegion(), so we do the CE_Header logic here
        style->drawControl( QStyle::CE_HeaderSection, &opt, painter, widget );
        QStyleOptionHeader subopt = opt;
        subopt.rect = style->subElementRect( QStyle::SE_HeaderLabel, &opt, widget );
        if ( subopt.rect.isValid() ) {
            style->drawControl( QStyle::CE_HeaderLabel, &subopt, painter, widget );
        }

        dt.setDate( next );
    }
}
Пример #11
0
void CDlgBulkRegister::OnBulkMonth( int nMonth )
{
    QDateTimeEdit* pDt = NULL;
    QDateTime dtStart;

    for ( int nRow = 0; nRow < ui->tabRecord->rowCount( ); nRow++ ) {
        pDt = ( QDateTimeEdit* ) ui->tabRecord->cellWidget( nRow, 5 );
        dtStart = pDt->dateTime( );

        pDt = ( QDateTimeEdit* ) ui->tabRecord->cellWidget( nRow, 6 );
        dtStart = dtStart.addMonths( nMonth );
        //qDebug( ) << dtStart.toString( ) << endl;
        pDt->setDateTime( dtStart );
    }
}
void DateTimePickerRecipe::onValueChanged(QDateTime value)
{
    QDateTime today = QDateTime::currentDateTime();

    // We compare the date that is set on the Picker to the current date and set different
    // images depending on how far in the future (or past) that date is.
    if (value < today.addDays(-1)) {
        mTimeWarpFruit->setImageSource(QUrl("asset:///images/picker/banana_past.png"));
    } else if (value >= today.addDays(-1) && value <= today.addDays(3)) {
        mTimeWarpFruit->setImageSource(QUrl("asset:///images/picker/banana_new.png"));
    } else if ( value < today.addMonths(1) ) {
        mTimeWarpFruit->setImageSource(QUrl("asset:///images/picker/banana_old.png"));
    } else {
        mTimeWarpFruit->setImageSource(QUrl("asset:///images/picker/banana_ancient.png"));
    }
}
Пример #13
0
void CDlgBulkRegister::AddMonthRow( const QString &strCardID )
{
    ui->tabRecord->insertRow( 0 );
    QDateTime dt = QDateTime::currentDateTime( );
    QString strText;

    for ( int nIndex = 0; nIndex  < ui->tabRecord->columnCount( ); nIndex++ ) {
        switch ( nIndex ) {
        case 0 :
            AddItem( strCardID, 0, nIndex, ui->tabRecord );
            break;

        case 1 :
        case 2 :
        case 3 :
            AddCheckBoxItem( 0, nIndex, ui->tabRecord );
            break;

        case 4 :
        case 7 :
            AddComboBoxItem( 0, nIndex, 0, ( 7 == nIndex ), ui->tabRecord );
            break;

        case 5 :
        case 6 :
            if ( 6 == nIndex ) {
                dt = dt.addMonths( nBulkEndMonth );
            }
            AddDateTimeItem( 0, nIndex, dt, ui->tabRecord );
            break;

        case 8 :
            GetSelfNumber( strText );
            AddItem( strText, 0, nIndex, ui->tabRecord );
            break;

        case 9 :
            strText = "未知";
            AddItem( strText, 0, nIndex, ui->tabRecord );
            break;

        case 10 :
            AddItem( strCreator, 0, nIndex, ui->tabRecord );
            break;
        }
    }
}
Пример #14
0
void Validity::setDiff(const Validity *start, int number, int range)
{
	QDateTime dt = start->dateTime();

	switch (range) {
		case 0: dt = dt.addDays(number); break;
		case 1: dt = dt.addMonths(number); break;
		case 2: dt = dt.addYears(number); break;
	}

	// one day less if we go from 0:00:00 to 23:59:59
	if (midnight)
		dt = dt.addDays(-1);

	setDateTime(dt);
	mytime = start->mytime;
}
Пример #15
0
void databaseMain::purgeStuff() {

    QSqlQuery databaseEntry;
    QDateTime dateTime;
    dateTime = dateTime.currentDateTime();
    if(purgeUnits == "Minutes")
    {
        dateTime = dateTime.addSecs(-purgeNum*60);
    }
    if(purgeUnits == "Hours")
    {
        dateTime = dateTime.addSecs(-purgeNum*3600);
    }
    if(purgeUnits == "Days")
    {
        dateTime = dateTime.addDays(-purgeNum);
    }
    if(purgeUnits == "Months")
    {
        dateTime = dateTime.addMonths(-purgeNum);
    }
    if(purgeUnits == "Years")
    {
        dateTime = dateTime.addYears(-purgeNum);
    }

    QString testString = dateTime.toString();

    //qDebug() << "Purgetime!!!!!!!" << testString;

    databaseEntry.exec("SELECT Timestamp FROM packets");
    while(databaseEntry.next()){
        if(databaseEntry.value(0).toString() < testString)
        {
            qDebug() << "DatabaseTimeStamp: " << databaseEntry.value(0).toString();

            databaseEntry.prepare("DELETE FROM packets WHERE Timestamp = :Time");
            databaseEntry.bindValue(":Time",databaseEntry.value(0).toString());
            qDebug() << dataBase.lastError() << "---------------";
            databaseEntry.exec();
            qDebug() << databaseEntry.lastError() << "---------------";
        }

    }

}
Пример #16
0
void FileLogger::deleteOld(const int age, const FileLogAgeType ageType)
{
    QDateTime date = QDateTime::currentDateTime();
    QDir dir(Utils::Fs::branchPath(m_path));

    foreach (const QFileInfo file, dir.entryInfoList(QStringList("qbittorrent.log.bak*"), QDir::Files | QDir::Writable, QDir::Time | QDir::Reversed)) {
        QDateTime modificationDate = file.lastModified();
        switch (ageType) {
        case DAYS:
            modificationDate = modificationDate.addDays(age);
            break;
        case MONTHS:
            modificationDate = modificationDate.addMonths(age);
            break;
        default:
            modificationDate = modificationDate.addYears(age);
        }
        if (modificationDate > date)
            break;
        Utils::Fs::forceRemove(file.absoluteFilePath());
    }
}
Пример #17
0
void AlarmView::snoozeClicked()
{
    mAlarmTimer.stop();

    /* Snooze for some amount of time (configured in settings, say) */
    int snoozeindex = mSnoozeChoices->currentIndex();

    int snoozedelay = 60;
    // Make sure we set alarms on the minute by rounding
    QDateTime now = QDateTime::currentDateTime();
    int seconds = now.time().second();
    if (seconds >= 30)
        now = now.addSecs(60 - seconds);
    else
        now = now.addSecs(-seconds);

    switch(snoozeindex) {
        case 0: // 5 minutes
            snoozedelay = 300;
            break;
        case 1: // 10 minutes
            snoozedelay = 600;
            break;
        case 2: // 15 minutes
            snoozedelay = 900;
            break;
        case 3: // 30 minutes
            snoozedelay = 1800;
            break;
        case 4: // 1 hour
            snoozedelay = 3600;
            break;
        case 5: // 1 day
            snoozedelay = 24 * 60;
            break;
        case 6: // 1 week
            snoozedelay = 7 * 24 * 60;
            break;
        case 7: // 1 month hmm
            {
                QDateTime then = now.addMonths(1);
                snoozedelay = now.secsTo(then);
            }
            break;
    }

    QDateTime snoozeTime = now.addSecs(snoozedelay);

    /* Now store the snoozed alarm settings .. */
    QSettings config("Trolltech","DateBook");
    config.beginGroup("ActiveAlarms");

    /* get a sequence number... if you snooze more than 4 billion times, you'll need a new alarm clock */
    int index = config.value("SequenceNumber", 123).toInt();
    config.setValue("SequenceNumber", index + 1);
    config.sync();

    config.beginGroup(QString("AlarmID-%1").arg(index));
    config.setValue("EventTime", mStartTime);
    config.setValue("AlarmDelta", mDelay);

    Qtopia::addAlarm(snoozeTime, "Calendar", "snooze(QDateTime,int)", index);

    emit closeView();
}
Пример #18
0
/*
  Function used for finding the old backup directories to remove.
  Kaveau keeps:
  - hourly backups for the past 24 hours
  - daily backups for the past month
  - weekly backups until the external disk is full
*/
void TestCommon::testFindBackupDirectoriesToDelete_data()
{
  QTest::addColumn<QStringList>( "dirs" );
  QTest::addColumn<QStringList>( "expected" );

  QStringList input;
  QStringList output;
  QDateTime now = QDateTime::currentDateTime();
  QDateTime dateTime;

  // empty lists
  input.clear();
  output.clear();
  QTest::newRow("emtpy list") << input << output;

  // 24h backups
  input.clear();
  output.clear();
  dateTime = now;
  dateTime.setTime(QTime(now.time().hour(), 10, 00));

  for (int i = 0; i < 5; i++) {
    QDateTime time_to_keep = dateTime.addSecs(-i*3600); // i hour(s) ago
    QDateTime time_to_delete = time_to_keep.addSecs(-60); // i hour(s) and 1m ago
    input << time_to_keep.toString(DATE_FORMAT);
    input << time_to_delete.toString(DATE_FORMAT);
    output << time_to_delete.toString(DATE_FORMAT);
  }

  QTest::newRow("last 24 hours backups") << input << output;
  
  // last month backups
  dateTime = now;
  dateTime.setTime(QTime(now.time().hour(), 10, 00));

  for (int i = 2; i < 5; i++) {
    QDateTime time_to_keep = dateTime.addDays(-i); // i days ago
    QDateTime time_to_delete = time_to_keep.addSecs(-60); // i day(s) and 1m ago
    input << time_to_keep.toString(DATE_FORMAT);
    input << time_to_delete.toString(DATE_FORMAT);
    output << time_to_delete.toString(DATE_FORMAT);
  }
  
  QTest::newRow("last 24 hours + last month backups") << input << output;
  
  // weekly backups
  dateTime = now;
  dateTime.setTime(QTime(now.time().hour(), 10, 00));
  dateTime = dateTime.addMonths(-2); // 2 months ago

  for (int i = 1; i < 5; i++) {
    QDateTime time_to_keep = dateTime.addDays(-i*7); // i week(s) ago
    QDateTime time_to_delete = time_to_keep.addSecs(-60); // i week(s) and 1m ago
    input << time_to_keep.toString(DATE_FORMAT);
    input << time_to_delete.toString(DATE_FORMAT);
    output << time_to_delete.toString(DATE_FORMAT);
  }

  QTest::newRow("last 24 hours + last month + some weeks backups") << input << output;

  // nothing to delete
  input.clear();
  output.clear();

  dateTime = now;
  dateTime.setTime(QTime(now.time().hour(), 10, 00));

  for (int i = 0; i < 5; i++) {
    QDateTime time_to_keep = dateTime.addSecs(-i*3600); // i hour(s) ago
    input << time_to_keep.toString(DATE_FORMAT);
  }

  for (int i = 2; i < 5; i++) {
    QDateTime time_to_keep = dateTime.addDays(-i); // i days ago
    input << time_to_keep.toString(DATE_FORMAT);
  }

  for (int i = 1; i < 5; i++) {
    QDateTime time_to_keep = dateTime.addDays(-i*7); // i week(s) ago
    input << time_to_keep.toString(DATE_FORMAT);
  }

  QTest::newRow("nothing to delete") << input << output;
}
void RollingFileAppender::computeRollOverTime()
{
  Q_ASSERT_X(!m_datePatternString.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern");

  QDateTime now = QDateTime::currentDateTime();
  QDate nowDate = now.date();
  QTime nowTime = now.time();
  QDateTime start;

  switch (m_frequency)
  {
    case MinutelyRollover:
    {
      start = QDateTime(nowDate, QTime(nowTime.hour(), nowTime.minute(), 0, 0));
      m_rollOverTime = start.addSecs(60);
    }
    break;
    case HourlyRollover:
    {
      start = QDateTime(nowDate, QTime(nowTime.hour(), 0, 0, 0));
      m_rollOverTime = start.addSecs(60*60);
    }
    break;
    case HalfDailyRollover:
    {
      int hour = nowTime.hour();
      if (hour >=  12)
        hour = 12;
      else
        hour = 0;
      start = QDateTime(nowDate, QTime(hour, 0, 0, 0));
      m_rollOverTime = start.addSecs(60*60*12);
    }
    break;
    case DailyRollover:
    {
      start = QDateTime(nowDate, QTime(0, 0, 0, 0));
      m_rollOverTime = start.addDays(1);
    }
    break;
    case WeeklyRollover:
    {
      // Qt numbers the week days 1..7. The week starts on Monday.
      // Change it to being numbered 0..6, starting with Sunday.
      int day = nowDate.dayOfWeek();
      if (day == Qt::Sunday)
        day = 0;
      start = QDateTime(nowDate, QTime(0, 0, 0, 0)).addDays(-1 * day);
      m_rollOverTime = start.addDays(7);
    }
    break;
    case MonthlyRollover:
    {
      start = QDateTime(QDate(nowDate.year(), nowDate.month(), 1), QTime(0, 0, 0, 0));
      m_rollOverTime = start.addMonths(1);
    }
    break;
    default:
      Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant");
      m_rollOverTime = QDateTime::fromTime_t(0);
  }

  m_rollOverSuffix = start.toString(m_datePatternString);
  Q_ASSERT_X(now.toString(m_datePatternString) == m_rollOverSuffix,
      "DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval");
  Q_ASSERT_X(m_rollOverSuffix != m_rollOverTime.toString(m_datePatternString),
      "DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover");
}
Пример #20
0
static QwtScaleDiv qwtDivideToMonths( 
    QDateTime &minDate, const QDateTime &maxDate,
    double stepSize, int maxMinSteps ) 
{
    // months are intervals with non 
    // equidistant ( in ms ) steps: we have to build the 
    // scale division manually

    int minStepDays = 0;
    int minStepSize = 0.0; 

    if ( maxMinSteps > 1 )
    {
        if ( stepSize == 1 )
        {
            if ( maxMinSteps >= 30 )
                minStepDays = 1;
            else if ( maxMinSteps >= 6 )
                minStepDays = 5;
            else if ( maxMinSteps >= 3 )
                minStepDays = 10;

            minStepDays = 15;
        }
        else
        {
            minStepSize = qwtDivideMajorStep( 
                stepSize, maxMinSteps, QwtDate::Month );
        }
    }

    QList<double> majorTicks;
    QList<double> mediumTicks;
    QList<double> minorTicks;

    for ( QDateTime dt = minDate; 
        dt <= maxDate; dt = dt.addMonths( stepSize ) )
    {
        if ( !dt.isValid() )
            break;

        majorTicks += QwtDate::toDouble( dt );

        if ( minStepDays > 0 )
        {
            for ( int days = minStepDays; 
                days < 30; days += minStepDays )
            {
                const double tick = QwtDate::toDouble( dt.addDays( days ) );

                if ( days == 15 && minStepDays != 15 )
                    mediumTicks += tick;
                else
                    minorTicks += tick;
            }
        }
        else if ( minStepSize > 0.0 )
        {
            const int numMinorSteps = qRound( stepSize / (double) minStepSize );

            for ( int i = 1; i < numMinorSteps; i++ )
            {
                const double minorValue =
                    QwtDate::toDouble( dt.addMonths( i * minStepSize ) );

                if ( ( numMinorSteps % 2 == 0 ) && ( i == numMinorSteps / 2 ) )
                    mediumTicks += minorValue;
                else
                    minorTicks += minorValue;
            }
        }
    }

    QwtScaleDiv scaleDiv;
    scaleDiv.setInterval( QwtDate::toDouble( minDate ),
        QwtDate::toDouble( maxDate ) );

    scaleDiv.setTicks( QwtScaleDiv::MajorTick, majorTicks );
    scaleDiv.setTicks( QwtScaleDiv::MediumTick, mediumTicks );
    scaleDiv.setTicks( QwtScaleDiv::MinorTick, minorTicks );

    return scaleDiv;
}
Пример #21
0
CEphList::CEphList(QWidget *parent, mapView_t *view) :
  QDialog(parent),
  ui(new Ui::CEphList)
{
  ui->setupUi(this);

  cELColumn[0] = tr("JD");
  cELColumn[1] = tr("Date");
  cELColumn[2] = tr("Time");
  cELColumn[3] = tr("Magnitude");
  cELColumn[4] = tr("Phase");
  cELColumn[5] = tr("Position angle");
  cELColumn[6] = tr("Size X");
  cELColumn[7] = tr("Size Y");
  cELColumn[8] = tr("Local R.A.");
  cELColumn[9] = tr("Local Dec.");
  cELColumn[10] = tr("Local R.A. (J2000.0)");
  cELColumn[11] = tr("Local Dec. (J2000.0)");
  cELColumn[12] = tr("Geo. R.A.");
  cELColumn[13] = tr("Geo. Dec.");
  cELColumn[14] = tr("Azimuth");
  cELColumn[15] = tr("Altitude");
  cELColumn[16] = tr("Dist. to Earth (R)");
  cELColumn[17] = tr("Helio. dist. (r)");
  cELColumn[18] = tr("Elongation");
  cELColumn[19] = tr("Helio. longitude");
  cELColumn[20] = tr("Helio. latitude");
  cELColumn[21] = tr("Helio. rect. X");
  cELColumn[22] = tr("Helio. rect. Y");
  cELColumn[23] = tr("Helio. rect. Z");
  cELColumn[24] = tr("Light time");

  if (firstTime)
  {
    for (int i = 0; i < EL_COLUMN_COUNT; i++)
    {
      bChecked[i] = Qt::Checked;
      columnOrder[i] = i;
    }
  }

  m_view = *view;

  ui->comboBox->addItem(tr("Minute(s)"));
  ui->comboBox->addItem(tr("Hour(s)"));
  ui->comboBox->addItem(tr("Day(s)"));

  for (int i = 0; i < EL_COLUMN_COUNT; i++)
  {
    QListWidgetItem *item = new QListWidgetItem;

    item->setText(cELColumn[columnOrder[i]]);
    item->setFlags(Qt::ItemIsSelectable |
                   Qt::ItemIsUserCheckable |
                   Qt::ItemIsEnabled);
    item->setCheckState(bChecked[columnOrder[i]]);
    item->setData(Qt::UserRole + 1, columnOrder[i]);

    ui->listWidget_2->addItem(item);
  }

  for (int i = 0; i < PT_PLANET_COUNT; i++)
  {
    QListWidgetItem *item = new QListWidgetItem;

    item->setText(cAstro.getName(i));
    ui->listWidget->addItem(item);
  }

  for (int i = 0; i < tComets.count(); i++)
  {
    if (tComets[i].selected)
    {
      QListWidgetItem *item = new QListWidgetItem;

      item->setText(tComets[i].name);
      item->setData(Qt::UserRole + 1, i);
      ui->listWidget_3->addItem(item);
    }
  }

  for (int i = 0; i < tAsteroids.count(); i++)
  {
    if (tAsteroids[i].selected)
    {
      QListWidgetItem *item = new QListWidgetItem;

      item->setText(tAsteroids[i].name);
      item->setData(Qt::UserRole + 1, i);
      ui->listWidget_4->addItem(item);
    }
  }

  ui->checkBox->setChecked(isUTC);
  ui->comboBox->setCurrentIndex(nCombo);
  ui->spinBox->setValue(nStep);

  if (firstTime)
  {
    QDateTime t;

    jdConvertJDTo_DateTime(m_view.jd, &t);

    ui->dateTimeEdit->setDate(t.date());
    ui->dateTimeEdit->setTime(QTime(12, 0, 0));

    t = t.addMonths(1);

    ui->dateTimeEdit_2->setDate(t.date());
    ui->dateTimeEdit_2->setTime(QTime(12, 0, 0));

    firstTime = false;
  }
  else
  {
    ui->dateTimeEdit->setDateTime(timeFrom);
    ui->dateTimeEdit_2->setDateTime(timeTo);
  }
}
Пример #22
0
Collections::QueryMaker*
ConstraintTypes::TagMatch::initQueryMaker( Collections::QueryMaker* qm ) const
{
    if ( ( m_fieldsModel->type_of( m_field ) == FieldTypeInt ) ) {
        int v = m_value.toInt();
        int range = static_cast<int>( m_comparer->rangeNum( m_strictness, m_fieldsModel->meta_value_of( m_field ) ) );
        if ( m_comparison == CompareNumEquals ) {
            if ( !m_invert ) {
                if ( m_strictness < 0.99 ) { // fuzzy approximation of "1.0"
                    qm->beginAnd();
                    qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), v - range, Collections::QueryMaker::GreaterThan );
                    qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), v + range, Collections::QueryMaker::LessThan );
                    qm->endAndOr();
                } else {
                    qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), v, Collections::QueryMaker::Equals );
                }
            } else {
                if ( m_strictness > 0.99 ) {
                    qm->excludeNumberFilter( m_fieldsModel->meta_value_of( m_field ), v, Collections::QueryMaker::Equals );
                }
            }
        } else if ( m_comparison == CompareNumGreaterThan ) {
            if ( m_invert )
                qm->excludeNumberFilter( m_fieldsModel->meta_value_of( m_field ), v + range, Collections::QueryMaker::GreaterThan );
            else
                qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), v - range, Collections::QueryMaker::GreaterThan );
        } else if ( m_comparison == CompareNumLessThan ) {
            if ( m_invert )
                qm->excludeNumberFilter( m_fieldsModel->meta_value_of( m_field ), v - range, Collections::QueryMaker::LessThan );
            else
                qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), v + range, Collections::QueryMaker::LessThan );
        }
    } else if ( m_fieldsModel->type_of( m_field ) == FieldTypeDate ) {
        uint referenceDate = 0;
        int range = m_comparer->rangeDate( m_strictness );
        if ( m_comparison == CompareDateBefore ) {
            referenceDate = m_value.toDateTime().toTime_t();
            if ( m_invert )
                qm->excludeNumberFilter( m_fieldsModel->meta_value_of( m_field ), referenceDate - range, Collections::QueryMaker::LessThan );
            else
                qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), referenceDate + range, Collections::QueryMaker::LessThan );
        } else if ( m_comparison == CompareDateOn ) {
            referenceDate = m_value.toDateTime().toTime_t();
            if ( !m_invert ) {
                qm->beginAnd();
                qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), referenceDate - range, Collections::QueryMaker::GreaterThan );
                qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), referenceDate + range, Collections::QueryMaker::LessThan );
                qm->endAndOr();
            }
        } else if ( m_comparison == CompareDateAfter ) {
            referenceDate = m_value.toDateTime().toTime_t();
            if ( m_invert )
                qm->excludeNumberFilter( m_fieldsModel->meta_value_of( m_field ), referenceDate + range, Collections::QueryMaker::GreaterThan );
            else
                qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), referenceDate - range, Collections::QueryMaker::GreaterThan );
        } else if ( m_comparison == CompareDateWithin ) {
            QDateTime now = QDateTime::currentDateTime();
            DateRange r = m_value.value<DateRange>();
            switch ( r.second ) {
                case 0:
                    referenceDate = now.addDays( -1 * r.first ).toTime_t();
                    break;
                case 1:
                    referenceDate = now.addMonths( -1 * r.first ).toTime_t();
                    break;
                case 2:
                    referenceDate = now.addYears( -1 * r.first ).toTime_t();
                    break;
                default:
                    break;
            }
            if ( m_invert )
                qm->excludeNumberFilter( m_fieldsModel->meta_value_of( m_field ), referenceDate + range, Collections::QueryMaker::GreaterThan );
            else
                qm->addNumberFilter( m_fieldsModel->meta_value_of( m_field ), referenceDate - range, Collections::QueryMaker::GreaterThan );
        }
    } else if ( m_fieldsModel->type_of( m_field ) == FieldTypeString ) {
        if ( m_comparison == CompareStrEquals ) {
            if ( m_invert )
                qm->excludeFilter( m_fieldsModel->meta_value_of( m_field ), m_value.toString(), true, true );
            else
                qm->addFilter( m_fieldsModel->meta_value_of( m_field ), m_value.toString(), true, true );
        } else if ( m_comparison == CompareStrStartsWith ) {
            if ( m_invert )
                qm->excludeFilter( m_fieldsModel->meta_value_of( m_field ), m_value.toString(), true, false );
            else
                qm->addFilter( m_fieldsModel->meta_value_of( m_field ), m_value.toString(), true, false );
        } else if ( m_comparison == CompareStrEndsWith ) {
            if ( m_invert )
                qm->excludeFilter( m_fieldsModel->meta_value_of( m_field ), m_value.toString(), false, true );
            else
                qm->addFilter( m_fieldsModel->meta_value_of( m_field ), m_value.toString(), false, true );
        } else if ( m_comparison == CompareStrContains ) {
            if ( m_invert )
                qm->excludeFilter( m_fieldsModel->meta_value_of( m_field ), m_value.toString(), false, false );
            else
                qm->addFilter( m_fieldsModel->meta_value_of( m_field ), m_value.toString(), false, false );
        }
        // TODO: regexp
    } else {
        error() << "TagMatch cannot initialize QM for unknown type";
    }

    return qm;
}
Пример #23
0
/*!
  Align a date/time value for a step size

  For Qt::Day alignments there is no "natural day 0" -
  instead the first day of the year is used to avoid jumping 
  major ticks positions when panning a scale. For other alignments
  ( f.e according to the first day of the month ) alignDate()
  has to be overloaded.

  \param dateTime Date/time value
  \param stepSize Step size
  \param intervalType Interval type
  \param up When true dateTime is ceiled - otherwise it is floored

  \return Aligned date/time value
 */
QDateTime QwtDateScaleEngine::alignDate( 
    const QDateTime &dateTime, double stepSize, 
    QwtDate::IntervalType intervalType, bool up ) const
{
    // what about: (year == 1582 && month == 10 && day > 4 && day < 15) ??

    QDateTime dt = dateTime;

    if ( dateTime.timeSpec() == Qt::OffsetFromUTC )
    {
        dt.setUtcOffset( 0 );
    }

    switch( intervalType )
    {
        case QwtDate::Millisecond:
        {
            const int ms = qwtAlignValue( 
                dt.time().msec(), stepSize, up ) ;

            dt = QwtDate::floor( dateTime, QwtDate::Second );
            dt = dt.addMSecs( ms );

            break;
        }
        case QwtDate::Second:
        {
            int second = dt.time().second();
            if ( up )
            {
                if ( dt.time().msec() > 0 )
                    second++;
            }

            const int s = qwtAlignValue( second, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Minute );
            dt = dt.addSecs( s );

            break;
        }
        case QwtDate::Minute:
        {
            int minute = dt.time().minute();
            if ( up )
            {
                if ( dt.time().msec() > 0 || dt.time().second() > 0 )
                    minute++;
            }

            const int m = qwtAlignValue( minute, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Hour );
            dt = dt.addSecs( m * 60 );

            break;
        }
        case QwtDate::Hour:
        {
            int hour = dt.time().hour();
            if ( up )
            {
                if ( dt.time().msec() > 0 || dt.time().second() > 0
                    || dt.time().minute() > 0 )
                {
                    hour++;
                }
            }
            const int h = qwtAlignValue( hour, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Day );
            dt = dt.addSecs( h * 3600 );

            break;
        }
        case QwtDate::Day:
        {
            // What date do we expect f.e. from an alignment of 5 days ??
            // Aligning them to the beginning of the year avoids at least
            // jumping major ticks when panning

            int day = dt.date().dayOfYear();
            if ( up )
            {
                if ( dt.time() > QTime( 0, 0 ) )
                    day++;
            }

            const int d = qwtAlignValue( day, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Year );
            dt = dt.addDays( d - 1 );

            break;
        }
        case QwtDate::Week:
        {
            const QDate date = QwtDate::dateOfWeek0(
                dt.date().year(), d_data->week0Type );

            int numWeeks = date.daysTo( dt.date() ) / 7;
            if ( up )
            {
                if ( dt.time() > QTime( 0, 0 ) ||
                    date.daysTo( dt.date() ) % 7 )
                {
                    numWeeks++;
                }
            }

            const int d = qwtAlignValue( numWeeks, stepSize, up ) * 7;

            dt = QwtDate::floor( dt, QwtDate::Day );
            dt.setDate( date );
            dt = dt.addDays( d );

            break;
        }
        case QwtDate::Month:
        {
            int month = dt.date().month();
            if ( up )
            {
                if ( dt.date().day() > 1 ||
                    dt.time() > QTime( 0, 0 ) )
                {
                    month++;
                }
            }

            const int m = qwtAlignValue( month - 1, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Year );
            dt = dt.addMonths( m );

            break;
        }
        case QwtDate::Year:
        {
            int year = dateTime.date().year();
            if ( up )
            {
                if ( dateTime.date().dayOfYear() > 1 ||
                    dt.time() > QTime( 0, 0 ) )
                {
                    year++;
                }
            }

            const int y = qwtAlignValue( year, stepSize, up );

            dt = QwtDate::floor( dt, QwtDate::Day );
            if ( y == 0 )
            {
                // there is no year 0 in the Julian calendar
                dt.setDate( QDate( stepSize, 1, 1 ).addYears( -stepSize ) );
            }
            else
            {
                dt.setDate( QDate( y, 1, 1 ) );
            }

            break;
        }
    }

    if ( dateTime.timeSpec() == Qt::OffsetFromUTC )
    {
        dt.setUtcOffset( dateTime.utcOffset() );
    }

    return dt;
}
Пример #24
0
	void DailyRollingFileAppender::computeRollOverTime()
	{
	    // Q_ASSERT_X(, "DailyRollingFileAppender::computeRollOverTime()", "Lock must be held by caller")
	    Q_ASSERT_X(!mActiveDatePattern.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern");
	
	    QDateTime now = QDateTime::currentDateTime();
	    QDate now_date = now.date();
	    QTime now_time = now.time();
	    QDateTime start;
	    
	    switch (mFrequency)
	    {
	        case MINUTELY_ROLLOVER:
	            {
	                start = QDateTime(now_date,
	                                  QTime(now_time.hour(),
	                                        now_time.minute(),
	                                        0, 0));
	                mRollOverTime = start.addSecs(60);
	            } 
	            break;
	        case HOURLY_ROLLOVER:
	            {
	                start = QDateTime(now_date,
	                                  QTime(now_time.hour(),
	                                        0, 0, 0));
	                mRollOverTime = start.addSecs(60*60);
	            }
	            break;
	        case HALFDAILY_ROLLOVER:
	            {
	                int hour = now_time.hour();
	                if (hour >=  12)
	                    hour = 12;
	                else
	                    hour = 0;
	                start = QDateTime(now_date,
	                                  QTime(hour, 0, 0, 0));
	                mRollOverTime = start.addSecs(60*60*12);
	            }
	            break;
	        case DAILY_ROLLOVER:
	            {
	                start = QDateTime(now_date,
	                                  QTime(0, 0, 0, 0));
	                mRollOverTime = start.addDays(1);
	            }
	            break;
	        case WEEKLY_ROLLOVER:
	            { 
	                // QT numbers the week days 1..7. The week starts on Monday.
	                // Change it to being numbered 0..6, starting with Sunday.
	                int day = now_date.dayOfWeek();
	                if (day == Qt::Sunday)
	                    day = 0;
	                start = QDateTime(now_date,
	                                  QTime(0, 0, 0, 0)).addDays(-1 * day);
	                mRollOverTime = start.addDays(7);
	            }
	            break;
	        case MONTHLY_ROLLOVER:
	            {
	                start = QDateTime(QDate(now_date.year(),
	                                        now_date.month(),
	                                        1),
	                                  QTime(0, 0, 0, 0));
	                mRollOverTime = start.addMonths(1);
	            }
	            break;
	        default:
	            Q_ASSERT_X(false, "DailyRollingFileAppender::computeInterval()", "Invalid datePattern constant");
	            mRollOverTime = QDateTime::fromTime_t(0);
	    }
	    
	    mRollOverSuffix = static_cast<DateTime>(start).toString(mActiveDatePattern);
	    Q_ASSERT_X(static_cast<DateTime>(now).toString(mActiveDatePattern) == mRollOverSuffix, 
	               "DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval");
	    Q_ASSERT_X(mRollOverSuffix != static_cast<DateTime>(mRollOverTime).toString(mActiveDatePattern),
	               "DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover");
	    
	    logger()->trace("Computing roll over time from %1: The interval start time is %2. The roll over time is %3",
	                    now,
	                    start,
	                    mRollOverTime);
	}
Пример #25
0
static QwtScaleDiv qwtDivideToYears( 
    const QDateTime &minDate, const QDateTime &maxDate,
    double stepSize, int maxMinSteps ) 
{
    QList<double> majorTicks;
    QList<double> mediumTicks;
    QList<double> minorTicks;

    double minStepSize = 0.0;

    if ( maxMinSteps > 1 )
    {
        minStepSize = qwtDivideMajorStep( 
            stepSize, maxMinSteps, QwtDate::Year );
    }

    int numMinorSteps = 0;
    if ( minStepSize > 0.0 )
        numMinorSteps = qFloor( stepSize / minStepSize );

    bool dateBC = minDate.date().year() < -1;

    for ( QDateTime dt = minDate; dt <= maxDate;
        dt = dt.addYears( stepSize ) )
    {
        if ( dateBC && dt.date().year() > 1 )
        {
            // there is no year 0 in the Julian calendar
            dt = dt.addYears( -1 );
            dateBC = false;
        }

        if ( !dt.isValid() )
            break;

        majorTicks += QwtDate::toDouble( dt );

        for ( int i = 1; i < numMinorSteps; i++ )
        {
            QDateTime tickDate;

            const double years = qRound( i * minStepSize );
            if ( years >= INT_MAX / 12 )
            {
                tickDate = dt.addYears( years );
            }
            else
            {
                tickDate = dt.addMonths( qRound( years * 12 ) );
            }

            const bool isMedium = ( numMinorSteps > 2 ) &&
                ( numMinorSteps % 2 == 0 ) && ( i == numMinorSteps / 2 );

            const double minorValue = QwtDate::toDouble( tickDate );
            if ( isMedium )
                mediumTicks += minorValue;
            else
                minorTicks += minorValue;
        }

        if ( QwtDate::maxDate().addYears( -stepSize ) < dt.date() )
        {
            break;
        }
    }   

    QwtScaleDiv scaleDiv;
    scaleDiv.setInterval( QwtDate::toDouble( minDate ),
        QwtDate::toDouble( maxDate ) );

    scaleDiv.setTicks( QwtScaleDiv::MajorTick, majorTicks );
    scaleDiv.setTicks( QwtScaleDiv::MediumTick, mediumTicks );
    scaleDiv.setTicks( QwtScaleDiv::MinorTick, minorTicks );

    return scaleDiv;
}
QVector<struct timetick> TimeAxis::getTicks()
{
    uint64_t delta = (uint64_t) (this->domainHi - this->domainLo);

    uint64_t deltatick;
    Timescale granularity;

    /* First find deltatick. In the case of months and years, which are
     * of variable length, just find the number of months or years.
     */
    if (delta < MAX_NANOTICK * TIMEAXIS_MAXTICKS)
    {
        deltatick = getTimeTickDelta(NANOTICK_INTERVALS, NANOTICK_INTERVALS_LEN, delta);
        granularity = Timescale::NANOSECOND;
    }
    else if (delta < MAX_MILLITICK * TIMEAXIS_MAXTICKS)
    {
        deltatick = getTimeTickDelta(MILLITICK_INTERVALS, MILLITICK_INTERVALS_LEN, delta);
        granularity = Timescale::MILLISECOND;
    }
    else if (delta < MAX_SECTICK * TIMEAXIS_MAXTICKS)
    {
        deltatick = getTimeTickDelta(SECTICK_INTERVALS, SECTICK_INTERVALS_LEN, delta);
        granularity = Timescale::SECOND;
    }
    else if (delta < MAX_MINUTETICK * TIMEAXIS_MAXTICKS)
    {
        deltatick = getTimeTickDelta(MINUTETICK_INTERVALS, MINUTETICK_INTERVALS_LEN, delta);
        granularity = Timescale::MINUTE;
    }
    else if (delta < MAX_HOURTICK * TIMEAXIS_MAXTICKS)
    {
        deltatick = getTimeTickDelta(HOURTICK_INTERVALS, HOURTICK_INTERVALS_LEN, delta);
        granularity = Timescale::HOUR;
    }
    else if (delta < MAX_DAYTICK * TIMEAXIS_MAXTICKS)
    {
        deltatick = getTimeTickDelta(DAYTICK_INTERVALS, DAYTICK_INTERVALS_LEN, delta);
        granularity = Timescale::DAY;
    }
    else if (delta < MAX_MONTHTICK * TIMEAXIS_MAXTICKS)
    {
        deltatick = getTimeTickDelta(MONTHTICK_INTERVALS, MONTHTICK_INTERVALS_LEN, delta);
        granularity = Timescale::MONTH;
    }
    else
    {
        deltatick = getTimeTickDelta(YEARTICK_INTERVALS, YEARTICK_INTERVALS_LEN, delta);
        granularity = Timescale::YEAR;
    }

    QVector<struct timetick> ticks;

    int64_t domainLoMSecs = this->domainLo / MILLISECOND_NS;
    int64_t domainLoNSecs = this->domainLo % MILLISECOND_NS;
    if (domainLoNSecs < 0)
    {
        domainLoMSecs -= 1;
        domainLoNSecs += MILLISECOND_NS;
    }

    int64_t starttime, prevstart;

    switch(granularity)
    {
    case Timescale::YEAR:
    {
        int yeardelta = (int) (deltatick / YEAR_NS);
        Q_ASSERT((deltatick % YEAR_NS) == 0);

        QDateTime date = QDateTime::fromMSecsSinceEpoch(domainLoMSecs - 1, this->tz);
        int curryear = ceildiv(date.date().year(), yeardelta) * yeardelta;
        date.setDate(QDate(curryear, 1, 1));
        date.setTime(QTime());

        if (domainLoMSecs == date.toMSecsSinceEpoch() && domainLoNSecs > 0)
        {
            date = date.addYears(yeardelta);
        }

        /* TODO: this multiplication might overflow */
        starttime = date.toMSecsSinceEpoch() * MILLISECOND_NS;
        prevstart = starttime;

        /* This is the lowest granularity, so we need to check for overflow. */
        while (starttime <= this->domainHi && starttime >= prevstart)
        {
            ticks.append({ starttime, getTimeTickLabel(starttime, date, granularity, !this->promoteTicks) });
            date = date.addYears(yeardelta);
            prevstart = starttime;
            starttime = date.toMSecsSinceEpoch() * MILLISECOND_NS;
        }
        break;
    }
    case Timescale::MONTH:
    {
        int monthdelta = (int) (deltatick / MONTH_NS);
        Q_ASSERT((deltatick % MONTH_NS) == 0);

        QDateTime date = QDateTime::fromMSecsSinceEpoch(domainLoMSecs - 1, this->tz);
        date.setTime(QTime());

        /* currmonth is an int from 0 to 11. */
        int currmonth = ceildiv(date.date().month() - 1, monthdelta) * monthdelta;
        int curryear = date.date().year() + (currmonth / 12);
        currmonth %= 12;
        date.setDate(QDate(curryear, currmonth + 1, 1));
        date.setTime(QTime());

        if (domainLoMSecs == date.toMSecsSinceEpoch() && domainLoNSecs > 0)
        {
            date = date.addMonths(monthdelta);
        }

        starttime = date.toMSecsSinceEpoch() * (int64_t) MILLISECOND_NS;
        prevstart = starttime;
        while (starttime <= this->domainHi && starttime >= prevstart)
        {
            ticks.append({ starttime, getTimeTickLabel(starttime, date, granularity, !this->promoteTicks) });
            date = date.addMonths(monthdelta);
            prevstart = starttime;
            starttime = date.toMSecsSinceEpoch() * (int64_t) MILLISECOND_NS;
        }
        break;
    }
    default:
        starttime = ceildiv(this->domainLo, (int64_t) deltatick) * deltatick;
        if (granularity == Timescale::DAY || granularity == Timescale::HOUR)
        {
            /* I'm assuming that the timezone offset is never in smaller granularity than minutes. */
            QDateTime d = QDateTime::fromMSecsSinceEpoch(ceildiv(starttime, MILLISECOND_NS), this->tz);
            starttime -= SECOND_NS * (int64_t) d.offsetFromUtc();
            while (starttime > this->domainLo)
            {
                starttime -= deltatick;
            }
            while (starttime < this->domainLo)
            {
                starttime += deltatick;
            }
        }
        prevstart = starttime;
        while (starttime <= this->domainHi && starttime >= prevstart) {
            // Add the tick to ticks
            QDateTime date = QDateTime::fromMSecsSinceEpoch(ceildiv(starttime, MILLISECOND_NS), this->tz);
            ticks.append({ starttime, getTimeTickLabel(starttime, date, granularity, !this->promoteTicks) });
            prevstart = starttime;
            starttime += deltatick;
        }
        break;
    }

    return ticks;
}
Пример #27
0
/*!
  Ceil a datetime according the interval type

  \param dateTime Datetime value
  \param intervalType Interval type, how to ceil. 
                      F.e. when intervalType = QwtDate::Months, the result
                      will be ceiled to the next beginning of a month
  \return Ceiled datetime
  \sa floor()
 */
QDateTime QwtDate::ceil( const QDateTime &dateTime, IntervalType intervalType )
{
    if ( dateTime.date() >= QwtDate::maxDate() )
        return dateTime;

    QDateTime dt = dateTime;

    switch ( intervalType )
    {
        case QwtDate::Millisecond:
        {
            break;
        }
        case QwtDate::Second:
        {
            qwtFloorTime( QwtDate::Second, dt );
            if ( dt < dateTime )
                dt = dt.addSecs( 1 );

            break;
        }
        case QwtDate::Minute:
        {
            qwtFloorTime( QwtDate::Minute, dt );
            if ( dt < dateTime )
                dt = dt.addSecs( 60 );

            break;
        }
        case QwtDate::Hour:
        {
            qwtFloorTime( QwtDate::Hour, dt );
            if ( dt < dateTime )
                dt = dt.addSecs( 3600 );

            break;
        }
        case QwtDate::Day:
        {
            dt.setTime( QTime( 0, 0 ) );
            if ( dt < dateTime )
                dt = dt.addDays( 1 );

            break;
        }
        case QwtDate::Week:
        {
            dt.setTime( QTime( 0, 0 ) );
            if ( dt < dateTime )
                dt = dt.addDays( 1 );

            int days = qwtFirstDayOfWeek() - dt.date().dayOfWeek();
            if ( days < 0 )
                days += 7;

            dt = dt.addDays( days );

            break;
        }
        case QwtDate::Month:
        {
            dt.setTime( QTime( 0, 0 ) );
            dt.setDate( qwtToDate( dateTime.date().year(), 
                dateTime.date().month() ) );

            if ( dt < dateTime )
                dt = dt.addMonths( 1 );

            break;
        }
        case QwtDate::Year:
        {
            dt.setTime( QTime( 0, 0 ) );

            const QDate d = dateTime.date();

            int year = d.year();
            if ( d.month() > 1 || d.day() > 1 || !dateTime.time().isNull() )
                year++;

            if ( year == 0 )
                year++; // there is no year 0

            dt.setDate( qwtToDate( year ) );
            break;
        }
    }

    return dt;
}
Пример #28
0
QList<MetaPaket> DB_QMDB_SQL::getTracksFromQuick(int y1, int y2, uint t, int p, bool br)
{
    QList<MetaPaket> list;
    MetaPaket metaPaket;
    QDateTime dateTime = QDateTime::currentDateTime();
    dateTime = dateTime.addMonths(-3);
    QString coverUrl;
    QString album;
    QString interpret;
    QString queryString ("SELECT pfad, title, tracknr, t_artist.name, t_album.name, t_year.name, "
                         "wertung, gespielt, erfasst FROM t_title "
               "INNER JOIN t_artist ON t_title.artist = t_artist.id "
               "INNER JOIN t_album ON t_title.album = t_album.id "
               "INNER JOIN t_year ON t_title.year = t_year.id ");

    QString stringWhere = "";
    QString stringAnd = "";
    bool boolWhere = false;

    if(y1 && y2)
    {
        stringWhere = QString("WHERE t_year.name > '%1' ").arg(y1);
        boolWhere = true;
        stringAnd = QString("AND t_year.name < '%1' ").arg(y2);
    }

    if(t)
    {
        if(boolWhere)
        {
            stringAnd = stringAnd + QString("AND t_title.erfasst > " + QString("%1").arg(t) + " ");
        }
        else
        {
            stringWhere = QString("WHERE t_title.erfasst > " + QString("%1").arg(t) + " ");
            boolWhere = true;
        }
    }

    if(p)
    {
        if(boolWhere)
        {
            stringAnd = stringAnd + QString("AND t_title.wertung > " + QString("%1").arg(p) + " ");
        }

        else
        {
            stringWhere = QString("WHERE t_title.wertung > " + QString("%1").arg(p) + " ");
            boolWhere = true;
        }
    }

    if(br)
    {
        queryString = queryString + " WHERE t_title.gespielt < "
                                    + QString("%1").arg(dateTime.toTime_t()) +
                                    " ORDER BY RAND() LIMIT 50" ;

    }
    else
    {
        queryString = queryString + stringWhere + stringAnd;
    }
    qDebug() << queryString;
    QSqlQuery query(db);

    query.exec(queryString);

    while(query.next())
    {
        metaPaket.isEmpty = false;
        metaPaket.url = query.value(0).toString();
        metaPaket.title = query.value(1).toString();
        metaPaket.interpret = query.value(3).toString();
        metaPaket.album = query.value(4).toString();
        metaPaket.coverUrl = getCoverPath(metaPaket.interpret, metaPaket.album);
        metaPaket.points = query.value(6).toInt();
        metaPaket.lastPlayed = query.value(7).toUInt();;
        list.append(metaPaket);
    }

  
    return list;
}