void LXQtClockConfiguration::createDateFormats() { ui->dateFormatCOB->clear(); QString systemDateLocale = QLocale::system().dateFormat(QLocale::ShortFormat).toUpper(); if (systemDateLocale.indexOf("Y") < systemDateLocale.indexOf("D")) // Big-endian (year, month, day) -> in some Asia countires like China or Japan { addDateFormat("MMM d"); addDateFormat("MMMM d"); addDateFormat("MMM d, ddd"); addDateFormat("MMMM d, dddd"); addDateFormat("yyyy MMM d"); addDateFormat("yyyy MMMM d"); addDateFormat("yyyy MMM d, ddd"); addDateFormat("yyyy MMMM d, dddd"); addDateFormat("MMM dd"); addDateFormat("MMMM dd"); addDateFormat("MMM dd, ddd"); addDateFormat("MMMM dd, dddd"); addDateFormat("yyyy MMM dd"); addDateFormat("yyyy MMMM dd"); addDateFormat("yyyy MMM dd, ddd"); addDateFormat("yyyy MMMM dd, dddd"); } else if (systemDateLocale.indexOf("M") < systemDateLocale.indexOf("D")) // Middle-endian (month, day, year) -> USA { addDateFormat("MMM d"); addDateFormat("MMMM d"); addDateFormat("ddd, MMM d"); addDateFormat("dddd, MMMM d"); addDateFormat("MMM d yyyy"); addDateFormat("MMMM d yyyy"); addDateFormat("ddd, MMM d yyyy"); addDateFormat("dddd, MMMM d yyyy"); addDateFormat("MMM dd"); addDateFormat("MMMM dd"); addDateFormat("ddd, MMM dd"); addDateFormat("dddd, MMMM dd"); addDateFormat("MMM dd yyyy"); addDateFormat("MMMM dd yyyy"); addDateFormat("ddd, MMM dd yyyy"); addDateFormat("dddd, MMMM dd yyyy"); } else // Little-endian (day, month, year) -> most of Europe { addDateFormat("d MMM"); addDateFormat("d MMMM"); addDateFormat("ddd, d MMM"); addDateFormat("dddd, d MMMM"); addDateFormat("d MMM yyyy"); addDateFormat("d MMMM yyyy"); addDateFormat("ddd, d MMM yyyy"); addDateFormat("dddd, d MMMM yyyy"); addDateFormat("dd MMM"); addDateFormat("dd MMMM"); addDateFormat("ddd, dd MMM"); addDateFormat("dddd, dd MMMM"); addDateFormat("dd MMM yyyy"); addDateFormat("dd MMMM yyyy"); addDateFormat("ddd, dd MMM yyyy"); addDateFormat("dddd, dd MMMM yyyy"); } addDateFormat(QLocale::system().dateFormat(QLocale::ShortFormat)); addDateFormat(QLocale::system().dateFormat(QLocale::LongFormat)); addDateFormat("yyyy-MM-dd"); // ISO if (mCustomDateFormat.isEmpty()) ui->dateFormatCOB->addItem("Custom ...", QVariant(mCustomDateFormat)); else ui->dateFormatCOB->addItem(QString("Custom (%1) ...").arg(QDate(currentYear, 1, 1).toString(mCustomDateFormat)), QVariant(mCustomDateFormat)); }
FAT_IRSALIYE_SATIR_SECIMI::FAT_IRSALIYE_SATIR_SECIMI ( QString p_fatura_tarihi, int p_cari_hesap_id, int p_fatura_turu, QWidget * p_parent ) : SECIM_KERNELI ( p_parent ) { SQL_QUERY sql_query ( DB ); SET_HELP_PAGE ( "fat_irsaliye_satir_secimi.html" ); SET_PAGE_TITLE ( "FAT - İRSALİYE SATIRI SEÇİMİ " ); m_irsaliye_tarihi_bitis = p_fatura_tarihi; m_cari_hesap_id = p_cari_hesap_id; switch ( p_fatura_turu ) { case ENUM_FAT_ELLE_IRSALIYE_FATURALASTIRMA_ALIS : m_irsaliye_turu = ENUM_IRS_NORMAL_GIRIS; break; case ENUM_FAT_ELLE_IRSALIYE_FATURALASTIRMA_SATIS : m_irsaliye_turu = ENUM_IRS_NORMAL_CIKIS; break; case ENUM_FAT_ELLE_IRSALIYE_FATURALASTIRMA_KONSINYE_ALIS : m_irsaliye_turu = ENUM_IRS_KONSINYE_GIRIS; break; case ENUM_FAT_ELLE_IRSALIYE_FATURALASTIRMA_KONSINYE_SATIS: m_irsaliye_turu = ENUM_IRS_KONSINYE_CIKIS; break; default : m_irsaliye_turu = -1; break; } sql_query.PREPARE_SELECT ( "e9_sabit_degerler","irs_faturalandirilacak_gun" ,"sabit_deger_id = :sabit_deger_id"); sql_query.SET_VALUE(":sabit_deger_id" , 1); if ( sql_query.SELECT() EQ 0 ) { return; } sql_query.NEXT(); int faturandirilacak_gun = sql_query.VALUE(0).toInt(); QDate irsaliye_tarihi_bitis = QDate::fromString ( m_irsaliye_tarihi_bitis, "yyyy.MM.dd" ); int irsaliye_tarihi_bitis_month = irsaliye_tarihi_bitis.month(); QDate irsaliye_tarihi_baslangic = irsaliye_tarihi_bitis.addDays ( -1 * faturandirilacak_gun ); int irsaliye_tarihi_baslangic_month = irsaliye_tarihi_baslangic.month(); if ( irsaliye_tarihi_baslangic_month NE irsaliye_tarihi_bitis_month ) { m_irsaliye_tarihi_baslangic = QDate( irsaliye_tarihi_bitis.year(), irsaliye_tarihi_bitis_month, 01 ).toString("yyyy.MM.dd"); } else { m_irsaliye_tarihi_baslangic = irsaliye_tarihi_baslangic.toString("yyyy.MM.dd"); } SET_SORTING ( false ); SET_WINDOW_SIZE ( 600, 1100 ); SET_HEADERS ( QStringList () <<tr("irsaliye_satiri_id")<<tr("İrs. No")<<tr("İrs. S. No")<<tr("İrsaliye Tarihi") <<tr("Ürün Kodu")<<tr("Ürün Adı")<<tr("S. No/P. Kodu")<<tr("Kalan Miktar") <<tr("Birimi")<<tr("Birim Fiyat")<<tr("KDV")<<tr("KDV %")<<tr("ÖTV %") <<tr("Fiyatı")<<tr("Para Brm")<< DVZ_GET_TEMEL_PARA_BIRIMI_KODU() + tr(" Tutarı")); INIT_KERNEL ( DB ); QTableWidget * tableWidget = GET_TABLE_WIDGET(); tableWidget->setColumnWidth ( IRSALIYE_NO_COLUMN , 45 ); tableWidget->setColumnWidth ( IRSALIYE_BELGE_SERI_NO_COLUMN , 58 ); tableWidget->setColumnWidth ( IRSALIYE_TARIHI_COLUMN , 103 ); tableWidget->setColumnWidth ( URUN_KODU_COLUMN , 70 ); tableWidget->setColumnWidth ( URUN_ADI_COLUMN , 100 ); tableWidget->setColumnWidth ( SERI_NO_PARTI_KODU_COLUMN , 80 ); tableWidget->setColumnWidth ( KALAN_MIKTAR_COLUMN , 80 ); tableWidget->setColumnWidth ( URUN_BIRIMI_COLUMN , 60 ); tableWidget->setColumnWidth ( BIRIM_FIYAT_COLUMN , 75 ); tableWidget->setColumnWidth ( KDV_DAHIL_MI_COLUMN , 50 ); tableWidget->setColumnWidth ( KDV_ORANI_COLUMN , 47 ); tableWidget->setColumnWidth ( OTV_ORANI_COLUMN , 47 ); tableWidget->setColumnWidth ( FIYAT_COLUMN , 80 ); tableWidget->setColumnWidth ( PARA_BIRIMI_COLUMN , 60 ); tableWidget->setColumnWidth ( TEMEL_PARA_BIRIMI_TUTARI_COLUMN , 80 ); SET_SETTING_NAME ( "FAT_IRSALIYE_SATIR_SECIMI" ); QFont tableWidget_font = tableWidget->font(); int font_point_size = tableWidget_font.pointSize(); tableWidget_font.setPointSize ( font_point_size -1 ); tableWidget->setFont ( tableWidget_font ); tableWidget->hideColumn( IRSALIYE_SATIRI_ID_COLUMN ); }
QTime::isValid(21, 10, 30); // returns true QTime::isValid(22, 5, 62); // returns false //! [9] //! [10] QTime t; t.start(); some_lengthy_task(); qDebug("Time elapsed: %d ms", t.elapsed()); //! [10] //! [11] QDateTime now = QDateTime::currentDateTime(); QDateTime xmas(QDate(now.date().year(), 12, 25), QTime(0, 0)); qDebug("There are %d seconds to Christmas", now.secsTo(xmas)); //! [11] //! [12] QTime time1 = QTime::fromString("131", "HHh"); // time1 is 13:00:00 QTime time1 = QTime::fromString("1apA", "1amAM"); // time1 is 01:00:00 QDateTime dateTime2 = QDateTime::fromString("M1d1y9800:01:02", "'M'M'd'd'y'yyhh:mm:ss"); // dateTime is 1 January 1998 00:01:02 //! [12]
QDate YearlyRecurrence::nextOccurrence(const QDate &date, bool include_equals) const { const KCalendarSystem *calSys = KGlobal::locale()->calendar(); if(!include_equals) { if(date < startDate()) return firstOccurrence(); } else { if(date <= startDate()) return firstOccurrence(); } QDate nextdate = date; if(!include_equals) nextdate = calSys->addDays(nextdate, 1); if(!endDate().isNull() && nextdate > endDate()) return QDate(); if(calSys->year(nextdate) == calSys->year(startDate())) { nextdate = calSys->addYears(nextdate, i_frequency); calSys->setYMD(nextdate, calSys->year(nextdate), 1, 1); } else if(i_frequency != 1) { int i = (calSys->year(nextdate) - calSys->year(startDate())) % i_frequency; if(i != 0) { nextdate = calSys->addYears(nextdate, i_frequency - i); calSys->setYMD(nextdate, calSys->year(nextdate), 1, 1); } } if(i_dayofyear > 0) { if(calSys->dayOfYear(nextdate) > i_dayofyear) { nextdate = calSys->addYears(nextdate, i_frequency); } if(i_dayofyear > calSys->daysInYear(nextdate)) { int i = 10; do { if(i == 0) return QDate(); nextdate = calSys->addYears(nextdate, i_frequency); i--; } while(i_dayofyear > calSys->daysInYear(nextdate)); } nextdate = calSys->addDays(nextdate, i_dayofyear - calSys->dayOfYear(nextdate)); } else { int day = i_dayofmonth; if(i_dayofweek > 0) day = get_day_in_month(calSys->year(nextdate), i_month, i_week, i_dayofweek); if(day == 0 || calSys->month(nextdate) > i_month || (calSys->month(nextdate) == i_month && calSys->day(nextdate) > day)) { do { nextdate = calSys->addYears(nextdate, i_frequency); day = get_day_in_month(calSys->year(nextdate), i_month, i_week, i_dayofweek); if(!endDate().isNull() && calSys->year(nextdate) > calSys->year(endDate())) return QDate(); } while(day == 0); } if(i_dayofweek <= 0) { calSys->setYMD(nextdate, calSys->year(nextdate), i_month, 1); if(day > calSys->daysInMonth(nextdate)) { int i = 10; do { if(i == 0) return QDate(); nextdate = calSys->addYears(nextdate, i_frequency); calSys->setYMD(nextdate, calSys->year(nextdate), i_month, 1); i--; } while(day > calSys->daysInMonth(nextdate)); } } calSys->setYMD(nextdate, calSys->year(nextdate), i_month, day); } if(!endDate().isNull() && nextdate > endDate()) return QDate(); if(hasException(nextdate)) return nextOccurrence(nextdate); return nextdate; }
CalendarGraphicsItem::CalendarGraphicsItem(CalendarControl * cc, QGraphicsItem * parent) : QGraphicsRectItem(0.0, 0.0, __width, __height, parent) { _controller = cc; QDate today = QDate::currentDate(); QDate firstMonthDay = QDate(today.year(), today.month(), 1); QDate firstCalendarDay = firstMonthDay.addDays(firstMonthDay.dayOfWeek() * -1); if(firstMonthDay.dayOfWeek() < 2) firstCalendarDay = firstCalendarDay.addDays(-7); _selectedDay = today; QString prev = QObject::tr("<"); QString prevprev = QObject::tr("<<"); QString next = QObject::tr(">"); QString nextnext = QObject::tr(">>"); QGraphicsSimpleTextItem * textItem; QGraphicsRectItem * rectItem; rectItem = new QGraphicsRectItem(0.0, 0.0, __width, __titleHeight, this); rectItem->setBrush(blackFill); _items.insert("titleBackground", rectItem); textItem = new QGraphicsSimpleTextItem(today.toString("MMMM yyyy"), this); textItem->setFont(monthfont); textItem->setZValue(2); textItem->setBrush(whiteFill); QPointF ct = rectItem->boundingRect().center(); QRectF rt = textItem->boundingRect(); textItem->setPos(ct.x() - (rt.width() / 2), ct.y() - (rt.height() / 2)); _items.insert("title", textItem); qreal offset = 0.1 * __dpi; qreal nw = 0; GraphicsTextButtonItem * tbtnItem = 0; tbtnItem = new GraphicsTextButtonItem(prevprev, this); tbtnItem->setFont(navfont); tbtnItem->setZValue(3); tbtnItem->setBrush(Qt::lightGray); tbtnItem->setRolloverBrush(Qt::green); tbtnItem->scale(0.5, 1); tbtnItem->setReceiver(this); rt = tbtnItem->boundingRect(); tbtnItem->setPos(offset, ct.y() - (rt.height() / 2)); nw = rt.width(); _items.insert("fastrewind", tbtnItem); tbtnItem = new GraphicsTextButtonItem(nextnext, this); tbtnItem->setFont(navfont); tbtnItem->setZValue(3); tbtnItem->setBrush(Qt::lightGray); tbtnItem->setRolloverBrush(Qt::green); tbtnItem->scale(0.5, 1); tbtnItem->setReceiver(this); rt = tbtnItem->boundingRect(); tbtnItem->setPos(rectItem->boundingRect().right() - offset - (rt.width() / 2), ct.y() - (rt.height() / 2)); nw = qMax(nw, rt.width()) / 2; offset += (nw * 1.5); _items.insert("fastforward", tbtnItem); tbtnItem = new GraphicsTextButtonItem(prev, this); tbtnItem->setFont(navfont); tbtnItem->setZValue(3); tbtnItem->setBrush(Qt::lightGray); tbtnItem->setRolloverBrush(Qt::green); tbtnItem->scale(0.5, 1); tbtnItem->setReceiver(this); rt = tbtnItem->boundingRect(); tbtnItem->setPos(offset, ct.y() - (rt.height() / 2)); _items.insert("rewind", tbtnItem); tbtnItem = new GraphicsTextButtonItem(next, this); tbtnItem->setFont(navfont); tbtnItem->setZValue(3); tbtnItem->setBrush(Qt::lightGray); tbtnItem->setRolloverBrush(Qt::green); tbtnItem->scale(0.5, 1); tbtnItem->setReceiver(this); rt = tbtnItem->boundingRect(); tbtnItem->setPos(rectItem->boundingRect().right() - offset - (rt.width() / 2), ct.y() - (rt.height() / 2)); _items.insert("forward", tbtnItem); QDate date; qreal dayWidth = __width / 7.0; QApplication::setOverrideCursor(Qt::WaitCursor); for(int wday = 0; wday < 7; wday++) { for(int week = 0; week < 6; week++) { date = firstCalendarDay.addDays((7 * week) + wday); if(0 == week) { rectItem = new QGraphicsRectItem(wday * dayWidth, 0.5 * __dpi, dayWidth, 0.25 * __dpi, this); _items.insert(QString("weekday%1").arg(week), rectItem); textItem = new QGraphicsSimpleTextItem(date.toString("dddd"), this); textItem->setFont(wdayfont); textItem->setZValue(2); ct = rectItem->boundingRect().center(); rt = textItem->boundingRect(); textItem->setPos(ct.x() - (rt.width() / 2), ct.y() - (rt.height() / 2)); _items.insert(QString("weekday%1Text").arg(week), textItem); } QBrush fill; QBrush dayFill = blackFill; if(date == _selectedDay) fill = selectedFill; else if(date.month() != today.month()) { fill = nonMonthFill; dayFill = nonMonthDayFill; } else if(date == today) fill = todayFill; else if(date.dayOfWeek() > 5) fill = weekendFill; rectItem = new QGraphicsRectItem(wday * dayWidth, (0.75 + (1.25 * week)) * __dpi, dayWidth, 1.25 * __dpi, this); rectItem->setBrush(fill); _items.insert(QString("day%1").arg((7 * week) + wday), rectItem); rt = QRectF(rectItem->pos(), rectItem->boundingRect().size()); double offset = rt.width() / 3; textItem = new QGraphicsSimpleTextItem(QString::number(date.day()), this); textItem->setFont(dayfont); textItem->setZValue(2); textItem->setBrush(dayFill); textItem->setPos(rectItem->boundingRect().topLeft()); textItem->moveBy(5.0, 5.0); _items.insert(QString("day%1Number").arg((7 * week) + wday), textItem); rt = QRectF(textItem->pos(), textItem->boundingRect().size()); QString additionalText; if(_controller) additionalText = _controller->contents(date); textItem = new QGraphicsSimpleTextItem(additionalText, this); textItem->setFont(notesfont); textItem->setZValue(2); textItem->setBrush(dayFill); textItem->setPos(rt.left() + offset, rt.top() + (rt.height() * 1.5)); _items.insert(QString("day%1Text").arg((7 * week) + wday), textItem); } } QApplication::restoreOverrideCursor(); }
void XDateEdit::parseDate() { QString dateString = text().trimmed(); bool isNumeric; if (DEBUG) qDebug("%s::parseDate() with dateString %s, _currentDate %s, _allowNull %d", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateString), qPrintable(_currentDate.toString()), _allowNull); #ifdef GUIClient_h QDate today = ofmgThis->dbDate(); #else QDate today = QDate::currentDate(); #endif if (_parsed) { if (DEBUG) qDebug("%s::parseDate() looks like we've already parsed this string", qPrintable(parent() ? parent()->objectName() : objectName())); return; } _valid = false; if (dateString.contains(QRegExp("[0-9]+[-][0-9]+"))) //user enters hyphens instead of slashes { dateString.replace("-", "/"); } if (dateString == _nullString || dateString.isEmpty()) setNull(); else if (dateString == "0") // today checkDate(today); else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today { int offset = dateString.toInt(&isNumeric); if (isNumeric) checkDate(today.addDays(offset)); } else if (dateString[0] == '#') // julian day { int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric); if (isNumeric) { if (offset < 0) checkDate(QDate(today.year(), 12, 31).addDays(offset + 1)); else checkDate(QDate(today.year(), 1, 1).addDays(offset - 1)); } } else if (dateString.contains(QRegExp("^[0-9][0-9]?$"))) // date in month { int offset = dateString.toInt(&isNumeric, 10); if (isNumeric) { if (offset > today.daysInMonth()) offset = today.daysInMonth(); checkDate(QDate(today.year(), today.month(), 1).addDays(offset - 1)); } } else // interpret with locale { QString dateFormatStr = QLocale().dateFormat(QLocale::ShortFormat); if (DEBUG) qDebug("%s::parseDate() trying to parse with %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateFormatStr)); QDate tmp = QDate::fromString(dateString, dateFormatStr); bool twodigitformat = !(dateFormatStr.indexOf(QRegExp("y{4}")) >= 0); if (tmp.isValid()) { if (twodigitformat && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so { qDebug("%s::parseDate() found valid 2-digit year %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit qDebug("%s::parseDate() altered year to %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); } } else if (twodigitformat) { // try 4 digits, ignoring the possibility of '-literals in the format str dateFormatStr.replace(QRegExp("y{2}"), "yyyy"); if (DEBUG) qDebug("%s::parseDate() rewriting 2-digit year format string to %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateFormatStr)); tmp = QDate::fromString(dateString, dateFormatStr); if (tmp.isValid()) { if (tmp.year() < 10) tmp = tmp.addYears(today.year() - today.year() % 100); if (DEBUG) qDebug("%s::parseDate() after changing to 4-digit year, year = %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); } else if (DEBUG) qDebug("%s::parseDate() after changing to 4-digit year, date still isn't valid", qPrintable(parent() ? parent()->objectName() : objectName())); } else { // try 2 digits, ignoring the possibility of '-literals in the format str dateFormatStr.replace(QRegExp("y{4}"), "yy"); if (DEBUG) qDebug("%s::parseDate() rewriting 4-digit year format string to %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(dateFormatStr)); tmp = QDate::fromString(dateString, dateFormatStr); if (tmp.isValid() && tmp.year() < 1950) // Qt docs say 2-digit years are 1900-based so { qDebug("%s::parseDate() found valid 2-digit year %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); tmp = tmp.addYears(100); // add backwards-compat with pre-3.0 DLineEdit qDebug("%s::parseDate() altered year to %d", qPrintable(parent() ? parent()->objectName() : objectName()), tmp.year()); } } if(!tmp.isValid()) { // still no match -- we will decompose the format and input and // build a date based on that information QRegExp rx("(\\d+)"); QRegExp rx2("(m+|y+|d+)"); rx2.setCaseSensitivity(Qt::CaseInsensitive); QStringList numberList; QStringList formatList; int pos = 0; while ((pos = rx.indexIn(dateString, pos)) != -1) { numberList << rx.cap(1); pos += rx.matchedLength(); } pos = 0; while((pos = rx2.indexIn(dateFormatStr, pos)) != -1) { formatList << rx2.cap(1); pos += rx2.matchedLength(); } if (DEBUG) qDebug("%s::parseDate() aligning numberList %s with formatList %s", qPrintable(parent() ? parent()->objectName() : objectName()), qPrintable(numberList.join(":")), qPrintable(formatList.join(":"))); // if we don't have exactly 3 and the numberList is not 2 or 3 then don't bother if(formatList.size() == 3 && (numberList.size() == 2 || numberList.size() == 3)) { int year = today.year(); int day = -1; int month = -1; pos = 0; for (int i = 0; i < formatList.size(); ++i) { QChar ch = formatList.at(i).toLower().at(0); if(ch == 'y' && numberList.size() == 3) { year = numberList.at(pos).toInt(); pos++; } else if(ch == 'm') { month = numberList.at(pos).toInt(); pos++; } else if(ch == 'd') { day = numberList.at(pos).toInt(); pos++; } } // if single digit year, move it to the current century if (year < 10) year += today.year() - today.year() % 100; if(day > 0 && month > 0 && year > 0) tmp = QDate(year, month, day); } else if(formatList.size() == 3 && numberList.size() == 1) { QString ns = numberList.at(0); bool isNumber = false; (void)ns.toInt(&isNumber); if(isNumber && (ns.length() == 6 || ns.length() == 8)) { int year = today.year(); int day = -1; int month = -1; pos = 0; for (int i = 0; i < formatList.size(); ++i) { QChar ch = formatList.at(i).toLower().at(0); if(ch == 'y') { if(ns.length() == 8) { year = ns.mid(pos, 4).toInt(); pos+=4; } else { year = ns.mid(pos, 2).toInt(&isNumber); pos+=2; if(isNumber) { if(year < 50) year += 2000; else year += 1900; } } } else if(ch == 'm') { month = ns.mid(pos, 2).toInt(); pos+=2; } else if(ch == 'd') { day = ns.mid(pos, 2).toInt(); pos+=2; } } if(day > 0 && month > 0 && year > 0) tmp = QDate(year, month, day); } } } checkDate(QDate(tmp.year(), tmp.month(), tmp.day())); } if (!_valid) setText(""); _parsed = true; }
void CurrDisplay::reset() { clear(); setId(_baseId); setEffective(QDate().currentDate()); }
QT_BEGIN_NAMESPACE //internal static void addTagToMap(const GstTagList *list, const gchar *tag, gpointer user_data) { QMap<QByteArray, QVariant> *map = reinterpret_cast<QMap<QByteArray, QVariant>* >(user_data); GValue val; val.g_type = 0; gst_tag_list_copy_value(&val,list,tag); switch( G_VALUE_TYPE(&val) ) { case G_TYPE_STRING: { const gchar *str_value = g_value_get_string(&val); map->insert(QByteArray(tag), QString::fromUtf8(str_value)); break; } case G_TYPE_INT: map->insert(QByteArray(tag), g_value_get_int(&val)); break; case G_TYPE_UINT: map->insert(QByteArray(tag), g_value_get_uint(&val)); break; case G_TYPE_LONG: map->insert(QByteArray(tag), qint64(g_value_get_long(&val))); break; case G_TYPE_BOOLEAN: map->insert(QByteArray(tag), g_value_get_boolean(&val)); break; case G_TYPE_CHAR: #if GLIB_CHECK_VERSION(2,32,0) map->insert(QByteArray(tag), g_value_get_schar(&val)); #else map->insert(QByteArray(tag), g_value_get_char(&val)); #endif break; case G_TYPE_DOUBLE: map->insert(QByteArray(tag), g_value_get_double(&val)); break; default: // GST_TYPE_DATE is a function, not a constant, so pull it out of the switch #if GST_CHECK_VERSION(1,0,0) if (G_VALUE_TYPE(&val) == G_TYPE_DATE) { const GDate *date = (const GDate *)g_value_get_boxed(&val); #else if (G_VALUE_TYPE(&val) == GST_TYPE_DATE) { const GDate *date = gst_value_get_date(&val); #endif if (g_date_valid(date)) { int year = g_date_get_year(date); int month = g_date_get_month(date); int day = g_date_get_day(date); map->insert(QByteArray(tag), QDate(year,month,day)); if (!map->contains("year")) map->insert("year", year); } } else if (G_VALUE_TYPE(&val) == GST_TYPE_FRACTION) { int nom = gst_value_get_fraction_numerator(&val); int denom = gst_value_get_fraction_denominator(&val); if (denom > 0) { map->insert(QByteArray(tag), double(nom)/denom); } } break; } g_value_unset(&val); } /*! Convert GstTagList structure to QMap<QByteArray, QVariant>. Mapping to int, bool, char, string, fractions and date are supported. Fraction values are converted to doubles. */ QMap<QByteArray, QVariant> QGstUtils::gstTagListToMap(const GstTagList *tags) { QMap<QByteArray, QVariant> res; gst_tag_list_foreach(tags, addTagToMap, &res); return res; }
void ClearPrivateData::dialogAccepted() { QApplication::setOverrideCursor(Qt::WaitCursor); if (ui->history->isChecked()) { qint64 start = QDateTime::currentMSecsSinceEpoch(); qint64 end = 0; const QDate today = QDate::currentDate(); const QDate week = today.addDays(1 - today.dayOfWeek()); const QDate month = QDate(today.year(), today.month(), 1); switch (ui->historyLength->currentIndex()) { case 0: //Later Today end = QDateTime(today).toMSecsSinceEpoch(); break; case 1: //Week end = QDateTime(week).toMSecsSinceEpoch(); break; case 2: //Month end = QDateTime(month).toMSecsSinceEpoch(); break; case 3: //All break; } if (end == 0) { mApp->history()->clearHistory(); } else { const QList<int> &indexes = mApp->history()->indexesFromTimeRange(start, end); mApp->history()->deleteHistoryEntry(indexes); } } if (ui->cookies->isChecked()) { mApp->cookieJar()->setAllCookies(QList<QNetworkCookie>()); } if (ui->cache->isChecked()) { clearCache(); } if (ui->databases->isChecked()) { clearWebDatabases(); } if (ui->localStorage->isChecked()) { clearLocalStorage(); } if (ui->icons->isChecked()) { clearIcons(); } QApplication::restoreOverrideCursor(); ui->clear->setEnabled(false); ui->clear->setText(tr("Done")); QTimer::singleShot(1000, this, SLOT(close())); }
bool MGenerarCuotas::calcularComprobantes() { _cant = 0; _total = 0.0; // Fecha del mes actual - Inicio del mes QDate inicio_mes = QDate( QDate::currentDate().year(), _mes_busqueda, 1 ); QDate fin_mes = inicio_mes; fin_mes = fin_mes.addMonths( 1 ); // Busco el próximo número de recibo //NumeroComprobante *num = new NumeroComprobante( 0, -1, -1 ); NumeroComprobante num = MPagos::proximoSerieNumeroRecibo(); QSqlQuery cola; if( cola.exec( QString( " SELECT ic.id_item_cuota, ic.id_plan_cuota, ic.num_cuota, pc.cantidad_cuotas, ic.monto, pc.id_factura, pc.tipo_comprobante " " FROM item_cuota AS ic " " INNER JOIN plan_cuota AS pc ON ic.id_plan_cuota = pc.id_plan_cuota " " WHERE ic.fecha_pago IS NULL " " AND ic.id_recibo IS NULL " // Cuando se emite el recibo de la cuota este campo no debe estar vacío " AND ic.fecha_vencimiento <= \"%1\" " " AND ic.fecha_vencimiento >= \"%2\" " " GROUP BY ic.id_plan_cuota " " HAVING MIN( ic.num_cuota ) " " ORDER BY ic.id_plan_cuota, ic.num_cuota " ) .arg( fin_mes.toString( Qt::ISODate ) ) .arg( inicio_mes.toString( Qt::ISODate ) ) ) ) { while( cola.next() ) { beginInsertRows( QModelIndex(), _cant, _cant ); _numeros ->insert( _cant, cola.record().value( "id_item_cuota" ).toInt() ); _planes ->insert( _cant, cola.record().value( "id_plan_cuota" ).toInt() ); _cuotas ->insert( _cant, QString( "%2/%1" ) .arg( cola.record().value( "cantidad_cuotas" ).toInt() ) .arg( cola.record().value( "num_cuota" ).toInt() ) ); if( cola.record().value( "tipo_comprobante" ).toInt() == MPlanCuota::Factura ) { int id_factura = cola.record().value("id_factura").toInt(); int id_cliente = MFactura::obtenerIdCliente( id_factura ); _clientes_id->insert( _cant, id_cliente ); _clientes->insert( _cant, MClientes::getRazonSocial( id_cliente ) ); } else if( cola.record().value( "tipo_comprobante" ).toInt() == MPlanCuota::Remito ) { int id_remito = cola.record().value("id_factura").toInt(); int id_cliente = MRemito::obtenerIdCliente( id_remito ); _clientes_id->insert( _cant, id_cliente ); _clientes->insert( _cant, MClientes::getRazonSocial( id_cliente ) ); } else { qDebug() << "Tipo de comprobante desconocido"; } double monto = cola.record().value( "monto" ).toDouble(); _total += monto; _importes->insert( _cant, monto ); _comprobantes->insert( _cant, new NumeroComprobante( num ) ); endInsertRows(); _cant++; num.siguienteNumero(); } if( _cant > 0 ) { emit cambioTotal( _total ); emit cambioCantidad( _cant ); emit dataChanged( index( 0, 0 ), index( _cant, 5 ) ); return true; } else { emit cambioTotal( 0.0 ); emit cambioCantidad( 0 ); return false; } } else { qDebug() << "Error al ejecutar la cola de averiguamiento de los datos de las cuotas a pagar"; qDebug() << cola.lastError().text(); qDebug() << cola.lastQuery(); } return false; }
void Manager::add(const QDate & date, const bool & forced) { // Init bool ok = true; QString error = ""; QString tableName; QString filePath; // Valid date ? if(ok && !(date <= QDate::currentDate().addDays(1) && date >= QDate(2010, 1, 1))) { ok = false; error = "invalid date"; } // Connected ? if(ok && !connected) { ok = false; error = "not connected to any database"; } // starting message if(ok) { Util::addMessage("Adding : " + date.toString("yyyy-MM-dd")); } // if(ok) { tableName = "day" + date.toString("yyyyMMdd"); filePath = Util::getLineFromConf("pathToRawData") + "/" + tableName + ".csv"; } // Drop table if asked if(ok && forced) { QSqlQuery query; QString statement = "DROP TABLE IF EXISTS " + tableName + ";"; query.prepare(statement); if(!query.exec()) { ok = false; error = "couldn't drop table (" + tableName + ") " + database.lastError().text() + query.lastError().text(); } } // Create table if(ok) { QSqlQuery query; QString statement = ""; QStringList columns; QFile file(Util::getLineFromConf("pathToColumn") + "/columns.txt"); if(!file.open(QIODevice::ReadOnly)) { ok = false; error = Util::getLineFromConf("pathToColumn") + "/columns.txt " + file.errorString(); } if(ok) { QTextStream in(&file); while(!in.atEnd()) { columns.append(in.readLine()); } file.close(); statement = " CREATE TABLE "; statement += tableName + " ( "; for(int i = 0 ; i < columns.size() - 1 ; i++) { statement += " " + columns[i] + " text, "; } statement += " " + columns[columns.size() - 1] + " text );"; query.prepare(statement); if(ok && !query.exec()) { ok = false; error = "couldn't create table '" + tableName + "' : " + database.lastError().text() + query.lastError().text(); } } } // Fill table if(ok) { QSqlQuery query; QString statement = ""; QFile file(filePath); if(!file.open(QIODevice::ReadOnly)) { ok = false; error = filePath +" "+ file.errorString(); } QTextStream in(&file); in.setCodec("UTF-8"); int lineNumber = 0; while(!in.atEnd()) { lineNumber++; QString line = in.readLine(); if(line[line.size()-1] == ';') line.remove(line.size()-1, 1); QStringList values = line.split(";"); if(values.size() == Util::getLineFromConf("columnCount").toInt()) { statement = " INSERT INTO " + tableName + " VALUES ("; for(int i = 0 ; i < values.size() - 1 ; i++) { statement += " '" + values[i] + "' , "; } statement += " '" + values[values.size()-1] + "' );"; query.prepare(statement); if(!query.exec()) { Util::addMessage("ERROR: couldn't insert line " + QString::number(lineNumber) + " into " + tableName + database.lastError().text() + query.lastError().text()); } } else { Util::addMessage("ERROR: Not the right count of value: " + QString::number(values.size()) + " instead of " + Util::getLineFromConf("columnCount") + " at line " + QString::number(lineNumber)); } } file.close(); } // The end if(!ok) Util::addMessage("ERROR : " + error); else if(ok) Util::addMessage("Done adding"); }
TransactionHistory::TransactionHistory(Monero::TransactionHistory *pimpl, QObject *parent) : QObject(parent), m_pimpl(pimpl), m_minutesToUnlock(0), m_locked(false) { m_firstDateTime = QDateTime(QDate(2014, 4, 18)); // the genesis block m_lastDateTime = QDateTime::currentDateTime().addDays(1); // tomorrow (guard against jitter and timezones) }
void WoLineEdit::silentSetId(const int pId) { if (pId != -1) { XSqlQuery wo; wo.prepare(_query + _idClause + (_extraClause.isEmpty() || !_strict ? "" : " AND " + _extraClause) + QString(";")); wo.bindValue(":id", pId); wo.exec(); if (wo.first()) { if (_completer) static_cast<QSqlQueryModel* >(_completer->model())->setQuery(QSqlQuery()); _id = pId; _valid = TRUE; setText(wo.value("number").toString()); _qtyOrdered = wo.value("wo_qtyord").toDouble(); _qtyReceived = wo.value("wo_qtyrcv").toDouble(); _method = wo.value("method").toString(); _currentWarehouseid = (wo.value("warehous_id").isNull()) ? -1 : wo.value("warehous_id").toInt(); emit newId(_id); emit newItemid(wo.value("item_id").toInt()); emit warehouseChanged(wo.value("warehous_code").toString()); emit itemNumberChanged(wo.value("item_number").toString()); emit uomChanged(wo.value("uom_name").toString()); emit itemDescrip1Changed(wo.value("item_descrip1").toString()); emit itemDescrip2Changed(wo.value("item_descrip2").toString()); emit startDateChanged(wo.value("wo_startdate").toDate()); emit dueDateChanged(wo.value("wo_duedate").toDate()); emit qtyOrderedChanged(wo.value("wo_qtyord").toDouble()); emit qtyReceivedChanged(wo.value("wo_qtyrcv").toDouble()); emit qtyBalanceChanged(wo.value("balance").toDouble()); emit statusChanged(wo.value("wo_status").toString()); emit methodChanged(wo.value("wo_method").toString()); emit valid(TRUE); } } else { _id = -1; _valid = FALSE; _currentWarehouseid = -1; XLineEdit::clear(); emit newId(-1); emit newItemid(-1); emit warehouseChanged(""); emit itemNumberChanged(""); emit uomChanged(""); emit itemDescrip1Changed(""); emit itemDescrip2Changed(""); emit startDateChanged(QDate()); emit dueDateChanged(QDate()); emit qtyOrderedChanged(0); emit qtyReceivedChanged(0); emit qtyBalanceChanged(0); emit statusChanged(""); emit methodChanged(""); emit valid(FALSE); _qtyOrdered = 0; _qtyReceived = 0; } _parsed = TRUE; emit parsed(); }
void MainWindow::createCase(QString classification) { qDebug()<<classification; QSqlQuery query; QString tempTable = "tempClass" + classification.simplified().remove(" "); query.exec("DROP TEMPORARY TABLE IF EXISTS " + tempTable); // the temprary table is created as below to ensure that the index is also created query.clear(); query.exec("CREATE TEMPORARY TABLE " + tempTable + " LIKE SensorVector"); query.clear(); query.exec("INSERT INTO " + tempTable + " select * from SensorVector limit 1"); query.clear(); query.exec(" select lastUpdate, sensorId, status from Sensors where sensorId < 61 order by sensorId"); QDateTime start(QDate(2010,1,1),QTime(0,0,1)); QString lastSensorId = "-1"; QDateTime currentUpdate; // qDebug()<<".sensor loop"; while (query.next()) { QDateTime sensorLastUpdate = query.value(0).toDateTime(); QString sensorId = query.value(1).toString(); QString sensorStatus = query.value(2).toString(); if (sensorLastUpdate > start) // this gets the last update { start = sensorLastUpdate; lastSensorId = sensorId; } QSqlQuery updateQuery; QString seq; seq = "update " + tempTable + " set sensor" + sensorId + " = '" + sensorStatus + "'"; // qDebug()<<seq; // qDebug()<<"...update temp loop"; updateQuery.exec(seq); } query.clear(); //// Sensor location QSqlQuery locnQuery; QString qry; qry = "select"; qry+= " CASE WHEN L1.where = 0 and L2.where = 0 and L3.where = 0 THEN L1.name"; qry+= " WHEN L3.where = 0 and L2.where = 0 THEN L2.name"; qry+= " ELSE L3.name END,"; qry+= " CASE WHEN L1.where = 0 and L2.where = 0 and L3.where = 0 THEN L1.locationId"; qry+= " WHEN L3.where = 0 and L2.where = 0 THEN L2.locationId"; qry+= " ELSE L3.locationId END"; qry+= " FROM Locations L1, Locations L2, Locations L3"; qry+= " WHERE L2.locationId = L1.where"; qry+= " AND L3.locationId = L2.where"; qry+= " AND L1.locationId = ("; qry+= "select L.locationId from Sensors S, Locations L where S.sensorId = "; qry+= lastSensorId + " and L.locationId = S.locationId LIMIT 1)"; // qDebug()<<qry; // qDebug()<<"..locn query"; if (!locnQuery.exec(qry)) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("Cannot select from location or sensor tables!"); msgBox.exec(); msgBox.setText(locnQuery.lastError().text()); msgBox.exec(); qDebug()<<locnQuery.lastError(); qDebug()<<locnQuery.executedQuery(); return; } if (!locnQuery.next()) { QMessageBox msgBox; msgBox.setIcon(QMessageBox::Warning); msgBox.setText("Cannot select row from location query!"); msgBox.exec(); msgBox.setText(locnQuery.lastError().text()); msgBox.exec(); qDebug()<<locnQuery.lastError(); qDebug()<<locnQuery.executedQuery(); return; } QString location = locnQuery.value(0).toString(); //// QSqlQuery updateQuery; QString seq; seq = "update " + tempTable + " set lastUpdate = '" + start.toString("yyyy-MM-dd hh:mm:ss") + "', sensorLocation = '" + location + "', lastSensorId = '" + lastSensorId + "', classification = '?'"; // qDebug()<<seq; // qDebug()<<"...update temp final"; updateQuery.exec(seq); // create the class file for C5.0 QString fname; fname = "/home/joe/git/accompany/ShowME/data/" + classification + ".cases"; QFile file(fname); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qDebug()<<"Error opening class file"; return; } QTextStream out(&file); seq = "select * from " + tempTable; updateQuery.clear(); updateQuery.exec(seq); QSqlRecord rec = updateQuery.record(); int cols = rec.count(); while(updateQuery.next()) { for (int i=0;i<cols-1;i++) { out << updateQuery.value(i).toString() <<","; } out << updateQuery.value(cols-1).toString()<<"\n"; } file.close(); }
void HouseNumber::setTimeStamp(const int y, const int m, const int d) { timeStamp_=QDate(y,m,d); }
void tst_QQmlMetaObject::property_data() { QTest::addColumn<QString>("testFile"); QTest::addColumn<QByteArray>("cppTypeName"); QTest::addColumn<int>("cppType"); QTest::addColumn<bool>("isDefault"); QTest::addColumn<QVariant>("expectedValue"); QTest::addColumn<bool>("isWritable"); QTest::addColumn<QVariant>("newValue"); QTest::newRow("int") << "property.int.qml" << QByteArray("int") << int(QMetaType::Int) << false // default << QVariant(19) << true << QVariant(42); QTest::newRow("bool") << "property.bool.qml" << QByteArray("bool") << int(QMetaType::Bool) << true // default << QVariant(true) << true << QVariant(false); QTest::newRow("double") << "property.double.qml" << QByteArray("double") << int(QMetaType::Double) << false // default << QVariant(double(1234567890.)) << true // writable << QVariant(double(1.23456789)); QTest::newRow("real") << "property.real.qml" << QByteArray("double") << int(QMetaType::Double) << false // default << QVariant(double(1234567890.)) << true // writable << QVariant(double(1.23456789)); QTest::newRow("string") << "property.string.qml" << QByteArray("QString") << int(QMetaType::QString) << true // default << QVariant(QString::fromLatin1("dog")) << true // writable << QVariant(QString::fromLatin1("food")); QTest::newRow("url") << "property.url.qml" << QByteArray("QUrl") << int(QMetaType::QUrl) << false // default << QVariant(QUrl("http://foo.bar")) << true //writable << QVariant(QUrl("http://bar.baz")); QTest::newRow("color") << "property.color.qml" << QByteArray("QColor") << int(QMetaType::QColor) << true // default << QVariant(QColor("#ff0000")) << true // writable << QVariant(QColor("#00ff00")); QTest::newRow("date") << "property.date.qml" << QByteArray("QDateTime") << int(QMetaType::QDateTime) << false // default << QVariant(QDateTime(QDate(2012, 2, 7))) << true // writable << QVariant(QDateTime(QDate(2010, 7, 2))); QTest::newRow("variant") << "property.variant.qml" << QByteArray("QVariant") << int(QMetaType::QVariant) << true // default << QVariant(QPointF(12, 34)) << true // writable << QVariant(QSizeF(45, 67)); QTest::newRow("var") << "property.var.qml" << QByteArray("QVariant") << int(QMetaType::QVariant) << false // default << QVariant(QVariantList() << 5 << true << "ciao") << true // writable << QVariant(QVariantList() << 17.0); QTest::newRow("QtObject") << "property.QtObject.qml" << QByteArray("QObject*") << int(QMetaType::QObjectStar) << false // default << QVariant() << true // writable << QVariant::fromValue(static_cast<QObject*>(this)); QTest::newRow("list<QtObject>") << "property.list.QtObject.qml" << QByteArray("QQmlListProperty<QObject>") << qMetaTypeId<QQmlListProperty<QObject> >() << false // default << QVariant() << false // writable << QVariant(); QTest::newRow("MyQmlObject") << "property.MyQmlObject.qml" << QByteArray("MyQmlObject*") << qMetaTypeId<MyQmlObject*>() << false // default << QVariant() << true // writable << QVariant::fromValue(&myQmlObject); QTest::newRow("list<MyQmlObject>") << "property.list.MyQmlObject.qml" << QByteArray("QQmlListProperty<MyQmlObject>") << qMetaTypeId<QQmlListProperty<MyQmlObject> >() << false // default << QVariant() << false // writable << QVariant(); QTest::newRow("alias") << "property.alias.qml" << QByteArray("QString") << int(QMetaType::QString) << false // default << QVariant(QString::fromLatin1("Joe")) << true // writable << QVariant(QString::fromLatin1("Bob")); QTest::newRow("alias-2") << "property.alias.2.qml" << QByteArray("QObject*") << int(QMetaType::QObjectStar) << false // default << QVariant() << false // writable << QVariant(); QTest::newRow("alias-3") << "property.alias.3.qml" << QByteArray("QString") << int(QMetaType::QString) << false // default << QVariant(QString::fromLatin1("Arial")) << true // writable << QVariant(QString::fromLatin1("Helvetica")); }
/** * @brief Clears contents of the movie based on a list * @param infos List of infos which should be cleared */ void Movie::clear(QList<int> infos) { if (infos.contains(MovieScraperInfos::Actors)) m_actors.clear(); if (infos.contains(MovieScraperInfos::Backdrop)) { m_backdrops.clear(); m_images.insert(ImageType::MovieBackdrop, QByteArray()); m_hasImageChanged.insert(ImageType::MovieBackdrop, false); m_imagesToRemove.removeOne(ImageType::MovieBackdrop); } if (infos.contains(MovieScraperInfos::CdArt)) { m_discArts.clear(); m_images.insert(ImageType::MovieCdArt, QByteArray()); m_hasImageChanged.insert(ImageType::MovieCdArt, false); m_imagesToRemove.removeOne(ImageType::MovieCdArt); } if (infos.contains(MovieScraperInfos::Countries)) m_countries.clear(); if (infos.contains(MovieScraperInfos::Genres)) m_genres.clear(); if (infos.contains(MovieScraperInfos::Poster)){ m_posters.clear(); m_images.insert(ImageType::MoviePoster, QByteArray()); m_hasImageChanged.insert(ImageType::MoviePoster, false); m_numPrimaryLangPosters = 0; m_imagesToRemove.removeOne(ImageType::MoviePoster); } if (infos.contains(MovieScraperInfos::Studios)) m_studios.clear(); if (infos.contains(MovieScraperInfos::Title)) m_originalName = ""; if (infos.contains(MovieScraperInfos::Set)) m_set = ""; if (infos.contains(MovieScraperInfos::Overview)) { m_overview = ""; m_outline = ""; } if (infos.contains(MovieScraperInfos::Rating)) { m_rating = 0; m_votes = 0; } if (infos.contains(MovieScraperInfos::Released)) m_released = QDate(2000, 02, 30); // invalid date if (infos.contains(MovieScraperInfos::Tagline)) m_tagline = ""; if (infos.contains(MovieScraperInfos::Runtime)) m_runtime = 0; if (infos.contains(MovieScraperInfos::Trailer)) m_trailer = ""; if (infos.contains(MovieScraperInfos::Certification)) m_certification = ""; if (infos.contains(MovieScraperInfos::Writer)) m_writer = ""; if (infos.contains(MovieScraperInfos::Director)) m_director = ""; if (infos.contains(MovieScraperInfos::Tags)) m_tags.clear(); if (infos.contains(MovieScraperInfos::Logo)) { m_images.insert(ImageType::MovieLogo, QByteArray()); m_hasImageChanged.insert(ImageType::MovieLogo, false); m_imagesToRemove.removeOne(ImageType::MovieLogo); } if (infos.contains(MovieScraperInfos::ClearArt)) { m_images.insert(ImageType::MovieClearArt, QByteArray()); m_hasImageChanged.insert(ImageType::MovieClearArt, false); m_imagesToRemove.removeOne(ImageType::MovieClearArt); } if (infos.contains(MovieScraperInfos::Banner)) { m_images.insert(ImageType::MovieBanner, QByteArray()); m_hasImageChanged.insert(ImageType::MovieBanner, false); m_imagesToRemove.removeOne(ImageType::MovieBanner); } if (infos.contains(MovieScraperInfos::Thumb)) { m_images.insert(ImageType::MovieThumb, QByteArray()); m_hasImageChanged.insert(ImageType::MovieThumb, false); m_imagesToRemove.removeOne(ImageType::MovieThumb); } if (infos.contains(MovieScraperInfos::ExtraFanarts)) { m_extraFanartsToRemove.clear(); m_extraFanartImagesToAdd.clear(); m_extraFanarts.clear(); } }
void CDeviceGarmin::slotTimeout() { Garmin::IDevice * dev = getDevice(); if(dev == 0) return; Garmin::Pvt_t pvt; try { dev->getRealTimePos(pvt); } catch(int) { timer->stop(); log.fix = CLiveLog::eOff; emit sigLiveLog(log); QMessageBox::warning(0,tr("Device Link Error"),dev->getLastError().c_str(),QMessageBox::Ok,QMessageBox::NoButton); return; } log.fix = pvt.fix == 3 || pvt.fix == 5 ? CLiveLog::e3DFix : pvt.fix == 2 || pvt.fix == 4 ? CLiveLog::e2DFix : CLiveLog::eNoFix; if(log.fix != CLiveLog::eNoFix) { log.lon = pvt.lon; log.lat = pvt.lat; log.ele = pvt.alt + pvt.msl_hght; QDateTime t(QDate(1989,12,31), QTime(0,0), Qt::UTC); t = t.addDays(pvt.wn_days).addSecs((int)(pvt.tow + 0.5)).addSecs(-pvt.leap_scnds); log.timestamp = t.toLocalTime().toTime_t(); // multiply by 100 to avoid leaving the float range. float heading = fabsf((100.0 * pvt.east) / (100.0 * pvt.north)); heading = atanf(heading) / (2*M_PI) * 360.0; if( (pvt.north > 0.0) & (pvt.east > 0.0) ) { // 1st quadrant heading = heading; } else if( (pvt.north > 0.0) & (pvt.east < 0.0) ) { // 2nd quadrant heading = 360.0 - heading; } else if( (pvt.north < 0.0) & (pvt.east < 0.0) ) { // 3rd quadrant heading = 180.0 + heading; } else if( (pvt.north < 0.0) & (pvt.east > 0.0) ) { // 4th quadrant heading = 180.0 - heading; } else { heading = std::numeric_limits<float>::quiet_NaN(); } log.heading = heading; log.velocity = sqrtf( pvt.north * pvt.north + pvt.east * pvt.east ); //HS: moved division by 2 from CLiveLogDB.cpp log.error_horz = pvt.eph/2.0; //HS: moved division by 2 from CLiveLogDB.cpp log.error_vert = pvt.epv/2.0; } emit sigLiveLog(log); }
#define DEBUG false /* If there's no conversion rate available for the given currency on the given date, then produce an error message. However, since there are often multiple CurrDisplay and/or CurrCluster widgets in the same window, only complain once. When the window is closed and the CurrDisplay/CurrCluster widgets are destroyed or when the user switches to another currency or to an existing conversion rate, then reset so subsequent errors or repeats of the same error can be reported. */ #include <QPair> #include <QMutex> typedef QMap<QPair<int, QDate>, int> DateToCurrMap; static DateToCurrMap errorMap; static QDate nullDate = QDate(); static QMutex errorListLock; /* Report if there is no conversion rate for the currency passed in (curr_id in curr_symbol and curr_rate tables). curr_id < 0 indicates that we really want to report that no base currency has been defined (sNoConversionRate is overloaded to avoid duplicating its logic in sNoBase(QWidget*) below). */ static void sNoConversionRate(QWidget* parent, const int curr_id, const QDate& effective, const char *caller) { bool displayMsg = false; QPair<int, QDate> currDatePair = qMakePair(curr_id, curr_id < 0 ? nullDate : effective);
void notifications() { QDateTime time1(QDate(2013, 1, 2), QTime(12, 34, 56)); QDateTime time2(QDate(2012, 3, 4), QTime(10, 11, 12)); QDateTime time3(QDate(2014, 1, 2), QTime(12, 34, 56)); const QString id1 = QLatin1String("id1"); const QString id2 = QLatin1String("id2"); const QString id3 = QLatin1String("id3"); const QString from1 = QLatin1String("from1"); const QString from2 = QLatin1String("from2"); const QString from3 = QLatin1String("from3"); const QString to1 = QLatin1String("to1"); const QString to2 = QLatin1String("to2"); const QString to3 = QLatin1String("to3"); const QString title1 = QLatin1String("title1"); const QString title2 = QLatin1String("title2"); const QString title3 = QLatin1String("title3"); const QString link1 = QLatin1String("link1"); const QString link2 = QLatin1String("link2"); const QString link3 = QLatin1String("link3"); const QString app1 = QLatin1String("app1"); const QString app2 = QLatin1String("app2"); const QString app3 = QLatin1String("app3"); const QString object1 = QLatin1String("object1"); const QString object2 = QLatin1String("object2"); const QString object3 = QLatin1String("object3"); const bool unread1 = true; const bool unread2 = false; const bool unread3 = false; int account1 = 1; int account2 = 2; QString clientId = QLatin1String("clientId"); FacebookNotificationsDatabase database; database.addFacebookNotification(id1, from1, to1, time1, time1, title1, link1, app1, object1, unread1, account1, clientId); database.addFacebookNotification(id2, from2, to2, time2, time2, title2, link2, app2, object2, unread2, account1, clientId); database.addFacebookNotification(id3, from3, to3, time3, time3, title3, link3, app3, object3, unread3, account2, clientId); database.sync(); database.wait(); QCOMPARE(database.writeStatus(), AbstractSocialCacheDatabase::Finished); QList<FacebookNotification::ConstPtr> notifications; notifications = database.notifications(); QCOMPARE(notifications.count(), 3); FacebookNotification::ConstPtr notification; do { notification = notifications.takeFirst(); } while (notification->facebookId() != id1 && notifications.count() > 0); QCOMPARE(notification->facebookId(), id1); QCOMPARE(notification->from(), from1); QCOMPARE(notification->to(), to1); QCOMPARE(notification->createdTime(), time1); QCOMPARE(notification->updatedTime(), time1); QCOMPARE(notification->title(), title1); QCOMPARE(notification->link(), link1); QCOMPARE(notification->application(), app1); QCOMPARE(notification->object(), object1); QCOMPARE(notification->unread(), unread1); QCOMPARE(notification->accountId(), account1); QCOMPARE(notification->clientId(), clientId); QStringList toBeDeleted; toBeDeleted.append(id1); toBeDeleted.append(id2); database.removeNotifications(toBeDeleted); database.sync(); database.wait(); QCOMPARE(database.writeStatus(), AbstractSocialCacheDatabase::Finished); notifications = database.notifications(); QCOMPARE(notifications.count(), 1); notification = notifications.takeFirst(); QCOMPARE(notification->facebookId(), id3); QCOMPARE(notification->from(), from3); QCOMPARE(notification->to(), to3); QCOMPARE(notification->createdTime(), time3); QCOMPARE(notification->updatedTime(), time3); QCOMPARE(notification->title(), title3); QCOMPARE(notification->link(), link3); QCOMPARE(notification->application(), app3); QCOMPARE(notification->object(), object3); QCOMPARE(notification->unread(), unread3); QCOMPARE(notification->accountId(), account2); QCOMPARE(notification->clientId(), clientId); database.removeNotification(id3); database.sync(); database.wait(); QCOMPARE(database.writeStatus(), AbstractSocialCacheDatabase::Finished); notifications = database.notifications(); QCOMPARE(notifications.count(), 0); database.addFacebookNotification(id1, from1, to1, time1, time1, title1, link1, app1, object1, unread1, account1, clientId); database.addFacebookNotification(id2, from2, to2, time2, time2, title2, link2, app2, object2, unread2, account1, clientId); database.addFacebookNotification(id3, from3, to3, time3, time3, title3, link3, app3, object3, unread3, account2, clientId); database.sync(); database.wait(); QCOMPARE(database.writeStatus(), AbstractSocialCacheDatabase::Finished); notifications = database.notifications(); QCOMPARE(notifications.count(), 3); database.removeNotifications(account1); database.sync(); database.wait(); QCOMPARE(database.writeStatus(), AbstractSocialCacheDatabase::Finished); notifications = database.notifications(); QCOMPARE(notifications.count(), 1); database.removeNotifications(account2); database.sync(); database.wait(); QCOMPARE(database.writeStatus(), AbstractSocialCacheDatabase::Finished); notifications = database.notifications(); QCOMPARE(notifications.count(), 0); database.addFacebookNotification(id1, from1, to1, time1, time1, title1, link1, app1, object1, unread1, account1, clientId); database.removeNotification(id1); database.sync(); database.wait(); QCOMPARE(database.writeStatus(), AbstractSocialCacheDatabase::Finished); notifications = database.notifications(); QCOMPARE(notifications.count(), 0); }
QDate MonthlyRecurrence::prevOccurrence(const QDate &date, bool include_equals) const { const KCalendarSystem *calSys = KGlobal::locale()->calendar(); if(!include_equals) { if(date > endDate()) return lastOccurrence(); } QDate prevdate = date; if(!include_equals) prevdate = calSys->addDays(prevdate, -1); if(prevdate < startDate()) return QDate(); if(prevdate == startDate()) return startDate(); int prevday = -1; if(i_frequency != 1 && calSys->month(prevdate) != calSys->month(startDate())) { int i = months_between_dates(startDate(), prevdate) % i_frequency; if(i != 0) { if(i > 1) prevday = 1; else prevday = calSys->day(prevdate); prevdate = calSys->addMonths(prevdate, -i); calSys->setYMD(prevdate, calSys->year(prevdate), calSys->month(prevdate), calSys->daysInMonth(prevdate)); } } if(calSys->month(prevdate) == calSys->month(startDate())) return startDate(); int day = i_day; if(i_dayofweek > 0) day = get_day_in_month(prevdate, i_week, i_dayofweek); else if(i_day < 1) day = calSys->daysInMonth(prevdate) + i_day; if(wh_weekendhandling == WEEKEND_HANDLING_BEFORE) { QDate date; calSys->setYMD(date, calSys->year(prevdate), calSys->month(prevdate), day); int wday = calSys->dayOfWeek(date); if(wday == 6) day -= 1; else if(wday == 7) day -= 2; if(day <= 0) { prevdate = calSys->addMonths(prevdate, -1); day = calSys->daysInMonth(prevdate) + day; } } else if(wh_weekendhandling == WEEKEND_HANDLING_AFTER) { QDate date; calSys->setYMD(date, calSys->year(prevdate), calSys->month(prevdate), day); int wday = calSys->dayOfWeek(date); if(wday == 6) day += 2; else if(wday == 7) day += 1; if(day > calSys->daysInMonth(prevdate) && prevday > 0 && prevday >= day - calSys->daysInMonth(prevdate)) { day -= calSys->daysInMonth(prevdate); prevdate = calSys->addMonths(prevdate, 1); calSys->setYMD(prevdate, calSys->year(prevdate), calSys->month(prevdate), day); } } if(day <= 0 || calSys->day(prevdate) < day) { do { if(i_frequency > 1) prevday = 1; else prevday = calSys->day(prevdate); prevdate = calSys->addMonths(prevdate, -i_frequency); if(calSys->month(prevdate) == calSys->month(startDate())) return startDate(); if(calSys->month(prevdate) < calSys->month(startDate())) return QDate(); day = i_day; if(i_dayofweek > 0) day = get_day_in_month(prevdate, i_week, i_dayofweek); else if(i_day < 1) day = calSys->daysInMonth(prevdate) + i_day; if(wh_weekendhandling == WEEKEND_HANDLING_BEFORE) { QDate date; calSys->setYMD(date, calSys->year(prevdate), calSys->month(prevdate), day); int wday = calSys->dayOfWeek(date); if(wday == 6) day -= 1; else if(wday == 7) day -= 2; if(day <= 0) { prevdate = calSys->addMonths(prevdate, -1); day = calSys->daysInMonth(prevdate) + day; } } else if(wh_weekendhandling == WEEKEND_HANDLING_AFTER) { QDate date; calSys->setYMD(date, calSys->year(prevdate), calSys->month(prevdate), day); int wday = calSys->dayOfWeek(date); if(wday == 6) day += 2; else if(wday == 7) day += 1; if(day > calSys->daysInMonth(prevdate) && prevday > 0 && prevday >= day - calSys->daysInMonth(prevdate)) { day -= calSys->daysInMonth(prevdate); prevdate = calSys->addMonths(prevdate, 1); calSys->setYMD(prevdate, calSys->year(prevdate), calSys->month(prevdate), day); } else { calSys->setYMD(prevdate, calSys->year(prevdate), calSys->month(prevdate), calSys->daysInMonth(prevdate)); } } } while(day <= 0 || day > calSys->daysInMonth(prevdate)); } calSys->setYMD(prevdate, calSys->year(prevdate), calSys->month(prevdate), day); if(prevdate < startDate()) return QDate(); if(hasException(prevdate)) return prevOccurrence(prevdate); return prevdate; }
_rrTime::operator QDate () const { tm conv; to_tm(conv); return QDate(conv.tm_year+1900,conv.tm_mon+1,conv.tm_mday); }
void CalendarGraphicsItem::setSelectedDay(const QDate & sDate) { //if(sDate == _selectedDay) // return; _selectedDay = sDate; QDate today = QDate::currentDate(); QDate firstMonthDay = QDate(_selectedDay.year(), _selectedDay.month(), 1); QDate firstCalendarDay = firstMonthDay.addDays(firstMonthDay.dayOfWeek() * -1); if(firstMonthDay.dayOfWeek() < 2) firstCalendarDay = firstCalendarDay.addDays(-7); QGraphicsRectItem * titleBackground = static_cast<QGraphicsRectItem*>(_items["titleBackground"]); QGraphicsSimpleTextItem * title = static_cast<QGraphicsSimpleTextItem*>(_items["title"]); if(title && titleBackground) { title->setText(_selectedDay.toString("MMMM yyyy")); QPointF ct = titleBackground->boundingRect().center(); QRectF rt = title->boundingRect(); title->setPos(ct.x() - (rt.width() / 2), ct.y() - (rt.height() / 2)); } QDate date; QApplication::setOverrideCursor(Qt::WaitCursor); for(int wday = 0; wday < 42; wday++) { date = firstCalendarDay.addDays(wday); QBrush fill; QBrush dayFill = blackFill; if(date == _selectedDay) fill = selectedFill; else if(date.month() != _selectedDay.month()) { fill = nonMonthFill; dayFill = nonMonthDayFill; } else if(date == today) fill = todayFill; else if(date.dayOfWeek() > 5) fill = weekendFill; QString additionalText; if(_controller) additionalText = _controller->contents(date); QGraphicsRectItem * ri = static_cast<QGraphicsRectItem*>(_items[QString("day%1").arg(wday)]); if(ri) ri->setBrush(fill); QGraphicsSimpleTextItem * si = static_cast<QGraphicsSimpleTextItem*>(_items[QString("day%1Number").arg(wday)]); if(si) { si->setText(QString::number(date.day())); si->setBrush(dayFill); } QGraphicsSimpleTextItem * si2 = static_cast<QGraphicsSimpleTextItem*>(_items[QString("day%1Text").arg(wday)]); if(si2) { si2->setText(additionalText); si2->setBrush(dayFill); } } QApplication::restoreOverrideCursor(); if(_controller) _controller->setSelectedDay(_selectedDay); }
"uint8", // 2 "int16", // 3 "uint16", // 4 "int32", // 5 "uint32", // 6 "string", // 7 "float32", // 8 "float64", // 9 "uint8z", // 10 "uint16z", // 11 "uint32z", // 12 "byte" // 13 }; */ static const int base_type_names_size(14); static const QDateTime qbase_time(QDate(1989, 12, 31), QTime(0, 0, 0), Qt::UTC); struct FitField { int num; int type; int size; // in bytes }; struct FitDefinition { int global_msg_num; std::vector<FitField> fields; }; struct FitFileReaderState { static QMap<int,QString> global_msg_names;
//*************************************************************************** bool Kwave::MP3Decoder::parseID3Tags(ID3_Tag &tag) { if (tag.NumFrames() < 1) return true; // no tags, nothing to do QDate creation_date; QTime creation_time; int year = -1; int month = -1; int day = -1; ID3_Tag::Iterator *it = tag.CreateIterator(); ID3_Frame *frame = 0; Kwave::FileInfo info(metaData()); while (it && (frame = it->GetNext())) { const ID3_FrameID id = frame->GetID(); const Kwave::FileProperty property = m_property_map.property(id); const ID3_PropertyMap::Encoding encoding = m_property_map.encoding(id); switch (encoding) { case ID3_PropertyMap::ENC_TEXT_PARTINSET: { QString s = parseId3Frame2String(frame); int cd = 0; int cds = 0; if (s.contains(QLatin1Char('/'))) { int i = s.indexOf(QLatin1Char('/')); cd = s.left(i).toInt(); cds = s.mid(i + 1).toInt(); } else { cd = s.toInt(); } if (cd > 0) info.set(Kwave::INF_CD , QVariant(cd)); if (cds > 0) info.set(Kwave::INF_CDS, QVariant(cds)); break; } case ID3_PropertyMap::ENC_TRACK_NUM: { QString s = parseId3Frame2String(frame); int track = 0; int tracks = 0; if (s.contains(QLatin1Char('/'))) { int i = s.indexOf(QLatin1Char('/')); track = s.left(i).toInt(); tracks = s.mid(i + 1).toInt(); } else { track = s.toInt(); } if (track > 0) info.set(Kwave::INF_TRACK , QVariant(track)); if (tracks > 0) info.set(Kwave::INF_TRACKS, QVariant(tracks)); break; } case ID3_PropertyMap::ENC_TERMS_OF_USE: // the same as ENC_COMMENT, but without "Description" /* FALLTHROUGH */ case ID3_PropertyMap::ENC_COMMENT: { QString s = parseId3Frame2String(frame); // optionally prepend language char *lang = ID3_GetString(frame, ID3FN_LANGUAGE); if (lang) { s = _("[") + _(lang) + _("] ") + s; ID3_FreeString(lang); } // append to already existing tag, separated by a slash if (info.contains(property)) s = info.get(property).toString() + _(" / ") + s; info.set(property, QVariant(s)); break; } case ID3_PropertyMap::ENC_GENRE_TYPE: { QString s = parseId3Frame2String(frame); int genre = Kwave::GenreType::fromID3(s); if (genre >= 0) s = Kwave::GenreType::name(genre, false); info.set(property, QVariant(s)); break; } case ID3_PropertyMap::ENC_LENGTH: { // length in ms -> convert this to samples QString s = parseId3Frame2String(frame); const double rate = info.rate(); bool ok = false; const double ms = s.toDouble(&ok) + 0.5; if (ok && (rate > 0)) { // NOTE: this overwrites the length found in the header! sample_index_t length = static_cast<sample_index_t>( (rate * ms) / 1000.0); info.setLength(length); } break; } case ID3_PropertyMap::ENC_TEXT_TIMESTAMP: { if (!creation_date.isValid()) { QString s = parseId3Frame2String(frame); switch (id) { case ID3FID_RECORDINGDATES: // should be a ISO 8601 timestamp or similar s = Kwave::string2date(s); if (s.length()) creation_date = QDate::fromString(s, Qt::ISODate); break; case ID3FID_DATE: { // DDMM unsigned int ddmm = s.toUInt(); day = ddmm / 100; month = ddmm % 100; break; } case ID3FID_YEAR: /* FALLTHROUGH */ case ID3FID_ORIGYEAR: // YYYY year = s.toUInt(); break; default: break; } } if (creation_time.isValid()) { switch (id) { case ID3FID_TIME: creation_time = QTime::fromString(_("hhmm")); break; default: break; } } break; } case ID3_PropertyMap::ENC_TEXT_SLASH: { // append to already existing tag, separated by a slash QString s = parseId3Frame2String(frame); if (info.contains(property)) s = info.get(property).toString() + _(" / ") + s; info.set(property, QVariant(s)); break; } case ID3_PropertyMap::ENC_TEXT_URL: /* FALLTHROUGH */ case ID3_PropertyMap::ENC_TEXT: info.set(property, QVariant(parseId3Frame2String(frame))); break; case ID3_PropertyMap::ENC_NONE: /* FALLTHROUGH */ default: { QString s = parseId3Frame2String(frame); qWarning("unsupported ID3 tag: %d, descr: '%s', text: '%s'", id, frame->GetDescription(), DBG(s)); break; } } } /* * try to build a valid creation date/time */ if (!creation_date.isValid()) { // no complete creation date - try to reassemble from found y/m/d creation_date = QDate(year, month, day); } if (creation_date.isValid() && creation_time.isValid()) { // full date + time QDateTime dt(creation_date, creation_time); info.set(Kwave::INF_CREATION_DATE, dt.toString( _("yyyy-MM-ddTHH:mm:ss"))); } else if (creation_date.isValid()) { // date without time info.set(Kwave::INF_CREATION_DATE, creation_date.toString( _("yyyy-MM-dd"))); } else if (year > 0) { // only year creation_date = QDate(year, 1, 1); info.set(Kwave::INF_CREATION_DATE, creation_date.toString(_("yyyy"))); } metaData().replace(Kwave::MetaDataList(info)); return true; }
void DiarySidebar::setSummary() { // are we metric? bool useMetricUnits = context->athlete->useMetricUnits; // where we construct the text QString summaryText(""); QDate when; if (_ride && _ride->ride()) when = _ride->dateTime.date(); else when = QDate::currentDate(); // main totals static const QStringList totalColumn = QStringList() << "workout_time" << "time_riding" << "total_distance" << "total_work" << "elevation_gain"; static const QStringList averageColumn = QStringList() << "average_speed" << "average_power" << "average_hr" << "average_cad"; static const QStringList maximumColumn = QStringList() << "max_speed" << "max_power" << "max_heartrate" << "max_cadence"; // user defined QString s = appsettings->value(this, GC_SETTINGS_SUMMARY_METRICS, GC_SETTINGS_SUMMARY_METRICS_DEFAULT).toString(); // in case they were set tand then unset if (s == "") s = GC_SETTINGS_SUMMARY_METRICS_DEFAULT; QStringList metricColumn = s.split(","); // what date range should we use? QDate newFrom, newTo; switch(summarySelect->currentIndex()) { case 0 : // DAILY - just the date of the ride newFrom = newTo = when; break; case 1 : // WEEKLY - from Mon to Sun newFrom = when.addDays((when.dayOfWeek()-1)*-1); newTo = newFrom.addDays(6); break; default: case 2 : // MONTHLY - all days in month newFrom = QDate(when.year(), when.month(), 1); newTo = newFrom.addMonths(1).addDays(-1); break; } if (newFrom != from || newTo != to) { // date range changed lets refresh from = newFrom; to = newTo; // lets get the metrics QList<SummaryMetrics>results = context->athlete->metricDB->getAllMetricsFor(QDateTime(from,QTime(0,0,0)), QDateTime(to, QTime(24,59,59))); // foreach of the metrics get an aggregated value // header of summary summaryText = QString("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 3.2//EN\">" "<html>" "<head>" "<title></title>" "</head>" "<body>" "<center>"); for (int i=0; i<4; i++) { //taken out maximums -- too much info -- looks ugly QString aggname; QStringList list; switch(i) { case 0 : // Totals aggname = tr("Totals"); list = totalColumn; break; case 1 : // Averages aggname = tr("Averages"); list = averageColumn; break; case 3 : // Maximums aggname = tr("Maximums"); list = maximumColumn; break; case 2 : // User defined.. aggname = tr("Metrics"); list = metricColumn; break; } summaryText += QString("<p><table width=\"85%\">" "<tr>" "<td align=\"center\" colspan=\"2\">" "<b>%1</b>" "</td>" "</tr>").arg(aggname); foreach(QString metricname, list) { const RideMetric *metric = RideMetricFactory::instance().rideMetric(metricname); QStringList empty; // usually for filters, but we don't do that QString value = SummaryMetrics::getAggregated(context, metricname, results, empty, false, useMetricUnits); // Maximum Max and Average Average looks nasty, remove from name for display QString s = metric ? metric->name().replace(QRegExp(tr("^(Average|Max) ")), "") : "unknown"; // don't show units for time values if (metric && (metric->units(useMetricUnits) == "seconds" || metric->units(useMetricUnits) == tr("seconds") || metric->units(useMetricUnits) == "")) { summaryText += QString("<tr><td>%1:</td><td align=\"right\"> %2</td>") .arg(s) .arg(value); } else { summaryText += QString("<tr><td>%1(%2):</td><td align=\"right\"> %3</td>") .arg(s) .arg(metric ? metric->units(useMetricUnits) : "unknown") .arg(value); } } summaryText += QString("</tr>" "</table>"); } // finish off the html document summaryText += QString("</center>" "</body>" "</html>"); // set webview contents summary->page()->mainFrame()->setHtml(summaryText); }
namespace QtTools { /// тут ряд функций для преобразования unix time в julian date, /// в форматах std::chrono, boost::chrono, QDateTime / double, QDate. /// unix time в QDate julian day. /// QDate хранит julian day как qint64. /// QDATE_JULIAN_DAY_FOR_UNIX_EPOCH должно быть равно 2440588 const qint64 QDATE_JULIAN_DAY_FOR_UNIX_EPOCH = QDate(1970, 1, 1).toJulianDay(); /// https://en.wikipedia.org/wiki/Julian_day /// 2440587.5 /// разница в .5 вызвана в отчете точки начала дня: /// для julian day это полдень, для unix time это полночь const double JULIAN_DAY_FOR_UNIX_EPOCH = 2440587.5; /************************************************************************/ /* julian / chrono -> QDate */ /************************************************************************/ /// QDate по факту обертка вокруг qint64 - in/out параметры не нужны, достаточно return формы inline QDate ToQDate(std::chrono::system_clock::time_point point) { auto days = std::chrono::duration_cast<std::chrono::hours>(point.time_since_epoch()).count() / 24; return QDate::fromJulianDay(days + QDATE_JULIAN_DAY_FOR_UNIX_EPOCH); } inline QDate ToQDate(boost::chrono::system_clock::time_point point) { auto days = boost::chrono::duration_cast<boost::chrono::hours>(point.time_since_epoch()).count() / 24; return QDate::fromJulianDay(days + QDATE_JULIAN_DAY_FOR_UNIX_EPOCH); } inline QDate ToQDate(double jd) { /// julian date: день начинается в полдень /// но QDate считает только дни(qint64), а unix эпоха считается как 2440588, вместо 2440587.5. /// округляем что бы быть консистентными. Возможно лишнее return QDate::fromJulianDay(std::round(jd)); } /************************************************************************/ /* julian / chrono -> QDateTime */ /************************************************************************/ /// QDateTime - qt shared data class, который создается на куче. /// предоставляем 2 версии сигнатур с in/out параметром и return формой inline void ToQDateTime(std::chrono::system_clock::time_point point, QDateTime & dt) { auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(point.time_since_epoch()); dt.setMSecsSinceEpoch(msec.count()); } inline void ToQDateTime(boost::chrono::system_clock::time_point point, QDateTime & dt) { auto msec = boost::chrono::duration_cast<boost::chrono::milliseconds>(point.time_since_epoch()); dt.setMSecsSinceEpoch(msec.count()); } inline void ToQDateTime(double jd, QDateTime & dt) { /// https://en.wikipedia.org/wiki/Julian_day /// (JD − 2440587.5) × 86400 auto msec = static_cast<qint64>((jd - JULIAN_DAY_FOR_UNIX_EPOCH) * 24 * 60 * 60 * 1000); dt.setMSecsSinceEpoch(msec); } inline QDateTime ToQDateTime(std::chrono::system_clock::time_point point) { auto msec = std::chrono::duration_cast<std::chrono::milliseconds>(point.time_since_epoch()); return QDateTime::fromMSecsSinceEpoch(msec.count()); } inline QDateTime ToQDateTime(boost::chrono::system_clock::time_point point) { auto msec = boost::chrono::duration_cast<boost::chrono::milliseconds>(point.time_since_epoch()); return QDateTime::fromMSecsSinceEpoch(msec.count()); } inline QDateTime ToQDateTime(double jd) { /// https://en.wikipedia.org/wiki/Julian_day /// (JD − 2440587.5) × 86400 auto msec = static_cast<qint64>((jd - JULIAN_DAY_FOR_UNIX_EPOCH) * 24 * 60 * 60 * 1000); return QDateTime::fromMSecsSinceEpoch(msec); } /************************************************************************/ /* chrono / QDate/QDateTime -> julian day */ /************************************************************************/ inline double ToJulianDay(std::chrono::system_clock::time_point point) { auto days = std::chrono::duration_cast<std::chrono::hours>(point.time_since_epoch()).count() / 24; return days + QDATE_JULIAN_DAY_FOR_UNIX_EPOCH; } inline double ToJulianDay(boost::chrono::system_clock::time_point point) { auto days = boost::chrono::duration_cast<boost::chrono::hours>(point.time_since_epoch()).count() / 24; return days + QDATE_JULIAN_DAY_FOR_UNIX_EPOCH; } inline double ToJulianDay(const QDate & date) { return date.toJulianDay(); } inline double ToJulianDay(const QDateTime & date) { return ToJulianDay(date.date()); } /************************************************************************/ /* QDate/QDateTime / julian day -> chrono */ /************************************************************************/ inline std::chrono::system_clock::time_point ToStdChrono(double jd) { /// https://en.wikipedia.org/wiki/Julian_day /// (JD − 2440587.5) × 86400 auto unix_time = static_cast<qint64>((jd - JULIAN_DAY_FOR_UNIX_EPOCH) * 24 * 60 * 60); return std::chrono::system_clock::from_time_t(unix_time); } inline std::chrono::system_clock::time_point ToStdChrono(QDate date) { /// https://en.wikipedia.org/wiki/Julian_day /// (JD − 2440587.5) × 86400 auto unix_time = (date.toJulianDay() - QDATE_JULIAN_DAY_FOR_UNIX_EPOCH) * 24 * 60 * 60; return std::chrono::system_clock::from_time_t(unix_time); } inline std::chrono::system_clock::time_point ToStdChrono(const QDateTime & dt) { return std::chrono::system_clock::from_time_t(dt.toMSecsSinceEpoch() / 1000); } inline boost::chrono::system_clock::time_point ToBoostChrono(double jd) { /// https://en.wikipedia.org/wiki/Julian_day /// (JD − 2440587.5) × 86400 auto unix_time = static_cast<qint64>((jd - JULIAN_DAY_FOR_UNIX_EPOCH) * 24 * 60 * 60); return boost::chrono::system_clock::from_time_t(unix_time); } inline boost::chrono::system_clock::time_point ToBoostChrono(QDate date) { /// https://en.wikipedia.org/wiki/Julian_day /// (JD − 2440587.5) × 86400 auto unix_time = (date.toJulianDay() - QDATE_JULIAN_DAY_FOR_UNIX_EPOCH) * 24 * 60 * 60; return boost::chrono::system_clock::from_time_t(unix_time); } inline boost::chrono::system_clock::time_point ToBoostChrono(const QDateTime & dt) { return boost::chrono::system_clock::from_time_t(dt.toMSecsSinceEpoch() / 1000); } /// регистрирует std::chrono::system_clock::time_point/duration в Qt meta system void QtRegisterStdChronoTypes(); }
void Cashbox::updateTotals() { QString text;// = "<h1>Свод по кассе</h1><br>"; QSqlQuery query; double summOnStart = 0; QDate start_date = QDate(2000,1,1); QTime start_time = QTime(0,0,0); QSettings *settings = data->getSettings(); query.prepare(settings->value("cashbox/queries/first_shiftwork_document").toString()); query.bindValue(":store", data->getVariables()->value("current_base_id")); query.bindValue(":user", data->getVariables()->value("user_id")); if(!query.exec()){ qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues(); }else { if(query.next()){ start_date = query.value(0).toDate(); start_time = query.value(1).toTime(); } } text += "<h2>Товарные операции</h2>"; query.prepare(settings->value("cashbox/queries/goods_operations_sum").toString()); query.bindValue(":time_start",start_time); query.bindValue(":date_start",start_date); query.bindValue(":date_start2",start_date); if(!query.exec()){ qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues(); } while (query.next()) { text += "<li>"+query.value(0).toString() + ": "+ QString::number(query.value(1).toDouble(),'f',2); summOnStart -= query.value(1).toDouble(); } text += "<h2>Денежные операции</h2>"; query.prepare(settings->value("cashbox/queries/money_operations_sum").toString()); query.bindValue(":time_start",start_time); query.bindValue(":date_start",start_date); query.bindValue(":date_start2",start_date); // qDebug()<<query.lastQuery()<<Service::join(query.boundValues()); if(!query.exec()){ qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues(); } while (query.next()) { text += "<li>"+query.value(0).toString() + ": "+ QString::number(query.value(1).toDouble(),'f',2); summOnStart -= query.value(1).toDouble(); } query.prepare(settings->value("cashbox/queries/rests_goods_sum").toString()); if(!query.exec()){ qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues(); } double rests = 0; while (query.next()) rests += query.value(0).toDouble(); query.prepare(settings->value("cashbox/queries/rests_money_sum").toString()); if(!query.exec()){ qDebug()<<posInFile<<query.lastError().text()<<endl<<query.lastQuery()<<endl<<query.boundValues(); } while (query.next()) rests += query.value(0).toDouble(); text += "<h2>Остаток в кассе: "+ QString::number(rests,'f',2)+"</h2>"; summOnStart += rests; text = "Смена с "+start_date.toString("dd.MM.yyyy")+" "+start_time.toString("hh:mm:ss") + "<h2>Остаток на начало: "+ QString::number(summOnStart,'f',2)+"</h2>" + text; totals.setText(text); }
void AddresseeTest::serializeTest() { KContacts::Addressee addressee1, addressee2; KContacts::Picture logo(QStringLiteral("http://scottlandyard.info/pics/logo.png")); KContacts::Picture photo(QStringLiteral("http://scottlandyard.info/~sinclair/photo.png")); KContacts::Sound sound(QStringLiteral("http://scottlandyard.info/~sinclair/sound.wav")); QStringList emails; emails << QStringLiteral("*****@*****.**") << QStringLiteral("*****@*****.**"); KContacts::Key::List keys; keys << KContacts::Key(QStringLiteral("SecretKey")); QStringList categories; categories << QStringLiteral("Helper") << QStringLiteral("Friend"); QStringList customs; customs << QStringLiteral("FirstApp-FirstKey:FirstValue") << QStringLiteral("SecondApp-SecondKey:SecondValue") << QStringLiteral("ThirdApp-ThirdKey:ThirdValue"); addressee1.setUid(QStringLiteral("My uid")); addressee1.setName(QStringLiteral("John Sinclair")); addressee1.setFormattedName(QStringLiteral("Sinclair, John")); addressee1.setFamilyName(QStringLiteral("Sinclair")); addressee1.setGivenName(QStringLiteral("John")); addressee1.setAdditionalName(QStringLiteral("Bob")); addressee1.setPrefix(QStringLiteral("Sir")); addressee1.setSuffix(QStringLiteral("II")); addressee1.setNickName(QStringLiteral("ghosthunter")); addressee1.setBirthday(QDateTime(QDate(1982, 7, 19))); addressee1.setMailer(QStringLiteral("mutt")); addressee1.setTimeZone(KContacts::TimeZone(2)); addressee1.setGeo(KContacts::Geo(42, 23)); addressee1.setTitle(QStringLiteral("Ghost Hunter")); addressee1.setRole(QStringLiteral("Leader")); addressee1.setOrganization(QStringLiteral("Scottland Yard")); addressee1.setNote(QStringLiteral("Don't cross black deads way...")); addressee1.setProductId(QStringLiteral("ProductId45")); addressee1.setRevision(QDateTime(QDate(1982, 9, 15))); addressee1.setSortString(QStringLiteral("Name")); KContacts::ResourceLocatorUrl url; url.setUrl(QUrl(QStringLiteral("www.scottlandyard.info"))); addressee1.setUrl(url); addressee1.setSecrecy(KContacts::Secrecy(KContacts::Secrecy::Public)); addressee1.setLogo(logo); addressee1.setPhoto(photo); addressee1.setSound(sound); addressee1.setEmails(emails); addressee1.setKeys(keys); addressee1.setCategories(categories); addressee1.setCustoms(customs); addressee1.setChanged(false); QByteArray data; QDataStream s(&data, QIODevice::WriteOnly); s << addressee1; QDataStream t(&data, QIODevice::ReadOnly); t >> addressee2; QVERIFY(addressee1 == addressee2); }
void LXQtClockConfiguration::addDateFormat(const QString &format) { if (ui->dateFormatCOB->findData(QVariant(format)) == -1) ui->dateFormatCOB->addItem(QDate(currentYear, 1, 1).toString(format), QVariant(format)); }