DateBox::DateBox(QWidget * parent, int i, int f, QDate dataToSet):QWidget(parent),annoInizio(i),annoFine(f){ giorno=new QComboBox(parent); mese=new QComboBox(parent); anno=new QComboBox(parent); giorno->setFixedWidth(100); mese->setFixedWidth(100); anno->setFixedWidth(100); generaNumeri(giorno,1,31); generaNumeri(mese,1,12); generaNumeri(anno,annoInizio,annoFine); giorno->setCurrentText(intToQString(dataToSet.day())); mese->setCurrentText(intToQString(dataToSet.month())); anno->setCurrentText(intToQString(dataToSet.year())); QHBoxLayout* lay=new QHBoxLayout; lay->setSizeConstraint(QLayout::SetFixedSize); lay->addWidget(giorno); lay->addWidget(mese); lay->addWidget(anno); setLayout(lay); connect(mese,SIGNAL(activated(int)),this,SLOT(aggiornaGiorni())); connect(anno,SIGNAL(activated(int)),this,SLOT(aggiornaGiorni())); }
void TodoList::on_confirmButton_clicked(){ QString name = ui->nameBox->text(); if(name.size() == 0){ warnAniTime = 30; return; } TodoItem item; item.SetName(name.toStdString()); item.SetPlace(ui->placeBox->text().toStdString()); item.SetContent(ui->contentBox->toPlainText().toStdString()); item.SetLabel(ui->labelBox->text().toStdString()); item.SetKind(ui->comboBox->currentIndex()); QDateTime dateTime = ui->dateTimeEdit->dateTime(); QDate date = dateTime.date(); QTime ti = dateTime.time(); item.SetTime(Date(date.year(),date.month(),date.day(),ti.hour(),ti.minute())); item.SetWarnTime(ui->horizontalSlider->value() * 5); //以分为单位 int level = 0; if (ui->radioButton_1->isChecked()) level = 3; if (ui->radioButton_2->isChecked()) level = 1; if (ui->radioButton_3->isChecked()) level = 2; if (ui->radioButton_4->isChecked()) level = 0; item.SetLevel(level); if(state == WINSTATE::EDIT){ pa.AddTodo(item); }else if(state == WINSTATE::DETAIL){ pa.ChangeTodo(item,selectID,viewDate.year,viewDate.month); } ChangeState(WINSTATE::LIST); }
void qsa_eval_check() { QSettings settings; settings.insertSearchPath(QSettings::Windows, "/Trolltech"); QString key = QString("/QSA/%1/expdt").arg(QSA_VERSION_STRING); bool ok; bool showWarning = FALSE; QString str = settings.readEntry(key, QString::null, &ok); if (ok) { QRegExp exp("(\\w\\w\\w\\w)(\\w\\w)(\\w\\w)"); Q_ASSERT(exp.isValid()); if (exp.search(str) >= 0) { int a = exp.cap(1).toInt(0, 16); int b = exp.cap(2).toInt(0, 16); int c = exp.cap(3).toInt(0, 16); showWarning = (QDate::currentDate() > QDate(a, b, c)); } else { showWarning = TRUE; } } else { QDate date = QDate::currentDate().addMonths(1); QString str = QString().sprintf("%.4x%.2x%.2x", date.year(), date.month(), date.day()); settings.writeEntry(key, str); } if (showWarning) { QMessageBox::warning(0, QObject::tr("End of Evaluation Period"), QObject::tr("The evaluation period of QSA has expired.\n\n" "Please check http://www.trolltech.com/products/qsa" "for updates\n" "or contact [email protected] for further information"), QMessageBox::Ok, QMessageBox::NoButton); } }
QString DateTimePlugin::changeDateTime( const QString & filename, bool bModification, bool bAccess, const QDate & date, const QTime & time ) { // Initialze fields struct tm tmp; tmp.tm_mday = date.day(); tmp.tm_mon = date.month() - 1; tmp.tm_year = date.year() - 1900; tmp.tm_hour = time.hour(); tmp.tm_min = time.minute(); tmp.tm_sec = time.second(); tmp.tm_isdst = -1; // Create time time_t ti; ti = mktime( &tmp ); if( ti == -1 ) return QString( i18n("Can't change date of file %1. (Cannot mktime)") ).arg(filename); // Get current values struct stat st; if( stat( filename.toUtf8().data(), &st ) == -1 ) return QString( i18n("Can't change date of file %1. (Cannot stat the file)") ).arg(filename); // Fill structure; struct utimbuf buf; buf.actime = (bAccess ? ti : st.st_atime); buf.modtime = (bModification ? ti: st.st_mtime); if(utime( filename.toUtf8().data(), &buf ) != 0) return QString( i18n("Can't change date of file %1. (utime failed)") ).arg(filename); return QString::null; }
QVariant QQuickMonthModel::data(const QModelIndex &index, int role) const { Q_D(const QQuickMonthModel); if (index.isValid() && index.row() < daysOnACalendarMonth) { const QDate date = d->dates.at(index.row()); switch (role) { case DateRole: return date; case DayRole: return date.day(); case TodayRole: return date == d->today; case WeekNumberRole: return date.weekNumber(); case MonthRole: return date.month() - 1; case YearRole: return date.year(); default: break; } } return QVariant(); }
void Exif2GPX::addWaypoint(QDomElement& elt, std::pair<double,double> position, QDateTime time, const QString& prefix, const QString& name) { QDomDocument qdd = elt.ownerDocument(); QDomElement wptElt = qdd.createElement("wpt"); wptElt.setAttribute("lat", QString("%1").arg(position.first, 0, 'f')); wptElt.setAttribute("lon", QString("%1").arg(position.second, 0, 'f')); QDomElement timeElt = qdd.createElement("time"); char buffer[22]; std::memset(buffer, 0, 22); QDate d = time.date(); QTime t = time.time(); std::sprintf(buffer, "%04d-%02d-%02dT%02d:%02d:%02dZ", d.year(), d.month(), d.day(), t.hour(), t.minute(), t.second()); timeElt.appendChild(qdd.createTextNode(buffer)); wptElt.appendChild(timeElt); QDomElement urlElt = qdd.createElement("url"); urlElt.appendChild(qdd.createTextNode(prefix + name)); wptElt.appendChild(urlElt); QDomElement nameElt = qdd.createElement("name"); nameElt.appendChild(qdd.createTextNode(name)); wptElt.appendChild(nameElt); elt.appendChild(wptElt); }
void wxCalendarCtrl::SetAttr(size_t day, wxCalendarDateAttr *attr) { wxCHECK_RET( day > 0 && day < 32, wxT("invalid day") ); delete m_attrs[day - 1]; m_attrs[day - 1] = attr; QDate date = m_qtCalendar->selectedDate(); date.setDate(date.year(), date.month(), day); QTextCharFormat format = m_qtCalendar->dateTextFormat(date); if ( attr->HasTextColour() ) format.setForeground(attr->GetTextColour().GetHandle()); if ( attr->HasBackgroundColour() ) format.setBackground(attr->GetBackgroundColour().GetHandle()); wxMISSING_IMPLEMENTATION( "Setting font" ); // wxFont is not implemented yet //if ( attr->HasFont() ) // format.setFont(attr->GetFont().GetQFont()); m_qtCalendar->setDateTextFormat(date, format); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QTranslator t; QDate today = QDate::currentDate(); if ( today.month() == 4 && today.day() == 1 ) { t.load(":/translations/koi7.qm"); } else { t.load(":/translations/ru.qm"); } QApplication::installTranslator(&t); Settings::instance(); Logger::logger(); QPixmap logo(":/resources/logo.png"); QSplashScreen *splash = new QSplashScreen(logo, Qt::FramelessWindowHint | Qt::SplashScreen); splash->setMask( logo.mask() ); splash->show(); Settings::instance()->updateLocalData(); splash->close(); delete splash; LauncherWindow w; w.show(); return a.exec(); }
QVariant CalendarModel::data(const QModelIndex & index, int role) const { if (not index.isValid()) return QVariant(); int week = index.row(); int day = index.column(); QDate date = m_week_days[week][day]; switch (role) { case Qt::DisplayRole: return QVariant(date.day()); case Qt::ForegroundRole: if (date.month() == m_current_month) return QVariant(QColor(Qt::black)); else return QVariant(QColor(Qt::lightGray)); default: break; } return QVariant(); }
bool GenericCashFlowPrivate::SamePeriod(const QDate& a, const QDate& b, GenericCashFlow::CashFlowAggregation Freq) { int YearA=0, YearB=0; bool Result; switch (Freq) { case GenericCashFlow::TotalAggragate: return true; case GenericCashFlow::Annually: return a.year() == b.year(); case GenericCashFlow::SemiAnnually: return a.year() == b.year() && (a.month() - 1) / 6 == (b.month() - 1) / 6; case GenericCashFlow::Quarterly: return a.year() == b.year() && (a.month() - 1) / 3 == (b.month() - 1) / 3; case GenericCashFlow::Monthly: return a.year() == b.year() && a.month() == b.month(); case GenericCashFlow::Weekly: Result = a.weekNumber(&YearA) == b.weekNumber(&YearB); return Result && YearA == YearB; case GenericCashFlow::NoAggregation: default: return a==b; } }
void Tab_Logins::refreshLoginList(long) { ADB DB; QString tmpstr = ""; QString tmpQItemID = ""; QString tmpQActive = ""; QString qds; ADB DB2; bool showIt = true; char isActive[128]; char dateStamp[128]; QDate d; QTime t; list->clear(); DB.query("select Logins.LoginID, LoginTypes.LoginType, Logins.ContactName, Logins.LastModified, Logins.DiskSpace, Logins.DialupChannels, Logins.Active from Logins, LoginTypes where Logins.CustomerID = %ld and Logins.LoginType = LoginTypes.InternalID", myCustID); if (DB.rowCount) while (DB.getrow()) { strcpy(isActive, "No"); if (atoi(DB.curRow["Active"])) strcpy(isActive, "Yes"); // Get the date stamp. strcpy(dateStamp, "Unknown"); if (strncmp("0000", DB.curRow["LastModified"], 4)) { // There is a date in the LastModified field. d = DB.curRow.col("LastModified")->toQDateTime().date(); t = DB.curRow.col("LastModified")->toQDateTime().time(); sprintf(dateStamp, "%04d-%02d-%02d %2d:%02d", d.year(), d.month(), d.day(), t.hour(), t.minute()); } // Count how many custom flags there are. QString flagCount = "0"; DB2.query("select count(LoginFlag) from LoginFlagValues where LoginID = '%s'", DB.curRow["LoginID"]); if (DB2.rowCount) { DB2.getrow(); flagCount = DB2.curRow[0]; } showIt = true; if (hideWiped->isChecked() && !strncmp("W", DB.curRow["LoginID"], 1)) showIt = false; if (showIt) { (void) new Q3ListViewItem(list, DB.curRow["LoginID"], // Login ID DB.curRow["LoginType"], // Login Type DB.curRow["ContactName"], // Contact Name dateStamp, // Last Modified Date DB.curRow["DiskSpace"], // Disk Space flagCount, // Custom flags isActive // Active? ); } } /* // Fill in the subscriptions ListBox if (hideWiped->isChecked()) { sprintf(querystr, "select LoginID, LoginType, ContactName, LastModified, DiskSpace, DialupChannels, Active from Logins where CustomerID = %ld and Wiped < '1970-01-01' order by LoginID", myCustID); } else { sprintf(querystr, "select LoginID, LoginType, ContactName, LastModified, DiskSpace, DialupChannels, Active from Logins where CustomerID = %ld order by LoginID", myCustID); } DB.query("%s", querystr); // subscrIndex = new(int[DB.rowCount + 1]); int idxPtr = 0; while(DB.getrow()) { // subscrIndex[idxPtr] = atoi(DB.curRow[0]); idxPtr++; tmpQItemID = DB.curRow["ContactName"]; tmpQItemID.truncate(11); strcpy(tmpItemID, tmpQItemID); tmpQActive = "No"; if (atoi(DB.curRow["Active"])) { tmpQActive = "Yes"; } strcpy(tmpActive, tmpQActive); DB2.query("select LoginType from LoginTypes where InternalID = %d", atoi(DB.curRow["LoginType"])); if (DB2.getrow()) { strcpy(loginType, DB2.curRow["LoginID"]); } else { strcpy(loginType, "Unknown"); } // Parse out the time stamp. qds = DB.curRow["LastModified"]; sprintf(tmpDateStamp, "%4s-%2s-%2s %2s:%2s.%2s", (const char *) qds.mid(0,4), (const char *) qds.mid(4,2), (const char *) qds.mid(6,2), (const char *) qds.mid(8,2), (const char *) qds.mid(10,2), (const char *) qds.mid(12,2) ); (void) new QListViewItem(list, DB.curRow["LoginID"], // Login ID loginType, // Login Type DB.curRow["ContactName"], // Contact Name tmpDateStamp, // Last Modified Date DB.curRow["DiskSpace"], // Disk Space DB.curRow["DialupChannels"], // Dialup Channels tmpActive // Active? ); // list->insertItem(i); } */ }
void DateSettingsEdit::setDateSettings() { if (active) return; // first lets disable everything active = true; fromDateEdit->setEnabled(false); toDateEdit->setEnabled(false); startDateEdit->setEnabled(false); thisperiod->setEnabled(false); prevperiod->setEnabled(false); lastn->setEnabled(false); lastnx->setEnabled(false); // the date selection types have changed if (radioSelected->isChecked()) { // current selection emit useStandardRange(); } else if (radioCustom->isChecked()) { // between x and y fromDateEdit->setEnabled(true); toDateEdit->setEnabled(true); // set date range using custom values emit useCustomRange(DateRange(fromDateEdit->date(), toDateEdit->date())); } else if (radioToday->isChecked()) { // current selected thru to today emit useThruToday(); } else if (radioLast->isChecked()) { // last n 'weeks etc' lastn->setEnabled(true); lastnx->setEnabled(true); QDate from; QDate today = QDate::currentDate(); // calculate range up to today... switch(lastnx->currentIndex()) { case 0 : // days from = today.addDays(lastn->value() * -1); break; case 1 : // weeks from = today.addDays(lastn->value() * -7); break; case 2 : // months from = today.addMonths(lastn->value() * -1); break; case 3 : // years from = today.addYears(lastn->value() * -1); break; } emit useCustomRange(DateRange(from, today)); } else if (radioFrom->isChecked()) { // from date - today startDateEdit->setEnabled(true); emit useCustomRange(DateRange(startDateEdit->date(), QDate::currentDate())); } else if (radioThis->isChecked()) { thisperiod->setEnabled(true); prevperiod->setEnabled(true); QDate today = QDate::currentDate(); QDate from, to; switch(thisperiod->currentIndex()) { case 0 : // weeks { int dow = today.dayOfWeek(); // 1-7, where 1=monday from = today.addDays(-1 * (dow-1)); to = from.addDays(6); // prevperiods from = from.addDays(prevperiod->value() * -7); to = to.addDays(prevperiod->value() * -7); } break; case 1 : // months from = QDate(today.year(), today.month(), 1); to = from.addMonths(1).addDays(-1); from = from.addMonths(prevperiod->value() * -1); to = to.addMonths(prevperiod->value() * -1); break; case 2 : // years from = QDate(today.year(), 1, 1); to = from.addYears(1).addDays(-1); from = from.addYears(prevperiod->value() * -1); to = to.addYears(prevperiod->value() * -1); break; } emit useCustomRange(DateRange(from, to)); } active = false; }
void MyMoneyForecast::createBudget ( MyMoneyBudget& budget, QDate historyStart, QDate historyEnd, QDate budgetStart, QDate budgetEnd, const bool returnBudget ) { // clear all data except the id and name QString name = budget.name(); budget = MyMoneyBudget(budget.id(), MyMoneyBudget()); budget.setName(name); //check parameters if ( historyStart > historyEnd || budgetStart > budgetEnd || budgetStart <= historyEnd ) { throw new MYMONEYEXCEPTION ( "Illegal parameters when trying to create budget" ); } //get forecast method int fMethod = forecastMethod(); //set start date to 1st of month and end dates to last day of month, since we deal with full months in budget historyStart = QDate ( historyStart.year(), historyStart.month(), 1 ); historyEnd = QDate ( historyEnd.year(), historyEnd.month(), historyEnd.daysInMonth() ); budgetStart = QDate ( budgetStart.year(), budgetStart.month(), 1 ); budgetEnd = QDate ( budgetEnd.year(), budgetEnd.month(), budgetEnd.daysInMonth() ); //set forecast parameters setHistoryStartDate ( historyStart ); setHistoryEndDate ( historyEnd ); setForecastStartDate ( budgetStart ); setForecastEndDate ( budgetEnd ); setForecastDays ( budgetStart.daysTo ( budgetEnd ) + 1 ); if ( budgetStart.daysTo ( budgetEnd ) > historyStart.daysTo ( historyEnd ) ) { //if history period is shorter than budget, use that one as the trend length setAccountsCycle ( historyStart.daysTo ( historyEnd ) ); //we set the accountsCycle to the base timeframe we will use to calculate the average (eg. 180 days, 365, etc) } else { //if one timeframe is larger than the other, but not enough to be 1 time larger, we take the lowest value setAccountsCycle ( budgetStart.daysTo ( budgetEnd ) ); } setForecastCycles ( ( historyStart.daysTo ( historyEnd ) / accountsCycle() ) ); if ( forecastCycles() == 0 ) //the cycles must be at least 1 setForecastCycles ( 1 ); //do not skip opening date setSkipOpeningDate ( false ); //clear and set accounts list we are going to use. Categories, in this case m_nameIdx.clear(); setBudgetAccountList(); //calculate budget according to forecast method switch(fMethod) { case eScheduled: doFutureScheduledForecast(); calculateScheduledMonthlyBalances(); break; case eHistoric: pastTransactions(); //get all transactions for history period calculateAccountTrendList(); calculateHistoricMonthlyBalances(); //add all balances of each month and put at the 1st day of each month break; default: break; } //flag the forecast as done m_forecastDone = true; //only fill the budget if it is going to be used if ( returnBudget ) { //setup the budget itself MyMoneyFile* file = MyMoneyFile::instance(); budget.setBudgetStart ( budgetStart ); //go through all the accounts and add them to budget QMap<QString, QString>::ConstIterator it_nc; for ( it_nc = m_nameIdx.begin(); it_nc != m_nameIdx.end(); ++it_nc ) { MyMoneyAccount acc = file->account ( *it_nc ); MyMoneyBudget::AccountGroup budgetAcc; budgetAcc.setId ( acc.id() ); budgetAcc.setBudgetLevel ( MyMoneyBudget::AccountGroup::eMonthByMonth ); for ( QDate f_date = forecastStartDate(); f_date <= forecastEndDate(); ) { MyMoneyBudget::PeriodGroup period; //add period to budget account period.setStartDate ( f_date ); period.setAmount ( forecastBalance ( acc, f_date ) ); budgetAcc.addPeriod ( f_date, period ); //next month f_date = f_date.addMonths ( 1 ); } //add budget account to budget budget.setAccount ( budgetAcc, acc.id() ); } } }
QString convertTimeDate(const QString &mac_format, const QDateTime &datetime) { QDate date = datetime.date(); QTime time = datetime.time(); QString str; if (mac_format.contains('%')) { const QChar *chars = mac_format.constData(); bool is_percent = false; int length = 0; bool error = false; while ((*chars).unicode() && !error) { if (is_percent) { is_percent = false; switch ((*chars).unicode()) { case L'%': str += *chars; break; case L'a': appendStr(str, QDate::shortDayName(date.dayOfWeek()), length); break; case L'A': appendStr(str, QDate::longDayName(date.dayOfWeek()), length); break; case L'b': appendStr(str, QDate::shortMonthName(date.day()), length); break; case L'B': appendStr(str, QDate::longMonthName(date.day()), length); break; case L'c': appendStr(str, QLocale::system().toString(datetime), length); break; case L'd': appendInt(str, date.day(), length > 0 ? length : 2); break; case L'e': appendInt(str, date.day(), length); break; case L'F': appendInt(str, time.msec(), length > 0 ? length : 3); break; case L'H': appendInt(str, time.hour(), length > 0 ? length : 2); break; case L'I': appendInt(str, time.hour() % 12, length > 0 ? length : 2); break; case L'j': appendInt(str, date.dayOfYear(), length > 0 ? length : 3); break; case L'm': appendInt(str, date.month(), length > 0 ? length : 2); break; case L'M': appendInt(str, time.minute(), length > 0 ? length : 2); break; case L'p': appendStr(str, time.hour() < 12 ? "AM" : "PM", length); break; case L'S': appendInt(str, time.second(), length > 0 ? length : 2); break; case L'w': appendInt(str, date.dayOfWeek(), length); break; case L'x': appendStr(str, QLocale::system().toString(date), length); break; case L'X': appendStr(str, QLocale::system().toString(time), length); break; case L'y': appendInt(str, date.year() % 100, length > 0 ? length : 2); break; case L'Y': appendInt(str, date.year(), length > 0 ? length : 4); break; case L'Z': // It should be localized, isn't it?.. appendStr(str, SystemInfo::instance()->timezone(), length); break; case L'z': { int offset = SystemInfo::instance()->timezoneOffset(); appendInt(str, (offset/60)*100 + offset%60, length > 0 ? length : 4); break; } default: if ((*chars).isDigit()) { is_percent = true; length *= 10; length += (*chars).digitValue(); } else error = true; } } else if (*chars == '%') { length = 0; is_percent = true; } else str += *chars; chars++; } if (!error) return str; str.clear(); } WeekDate week_date(date); QChar last; QChar cur; int length = 0; bool quote = false; const QChar *chars = mac_format.constData(); forever { cur = *chars; if (cur == '\'') { if (*(chars+1) == '\'') { chars++; str += cur; } else { if (!quote) finishStr(str, week_date, date, time, last, length); quote = !quote; } length = 0; } else if (quote) str += cur; else { if (cur == last) length++; else { finishStr(str, week_date, date, time, last, length); length = 1; } } if (!chars->unicode()) break; last = cur; chars++; } return str; }
// Testing get/set functions void tst_QCalendarWidget::getSetCheck() { QWidget topLevel; QCalendarWidget object(&topLevel); //horizontal header formats object.setHorizontalHeaderFormat(QCalendarWidget::NoHorizontalHeader); QCOMPARE(QCalendarWidget::NoHorizontalHeader, object.horizontalHeaderFormat()); object.setHorizontalHeaderFormat(QCalendarWidget::SingleLetterDayNames); QCOMPARE(QCalendarWidget::SingleLetterDayNames, object.horizontalHeaderFormat()); object.setHorizontalHeaderFormat(QCalendarWidget::ShortDayNames); QCOMPARE(QCalendarWidget::ShortDayNames, object.horizontalHeaderFormat()); object.setHorizontalHeaderFormat(QCalendarWidget::LongDayNames); QCOMPARE(QCalendarWidget::LongDayNames, object.horizontalHeaderFormat()); //vertical header formats object.setVerticalHeaderFormat(QCalendarWidget::ISOWeekNumbers); QCOMPARE(QCalendarWidget::ISOWeekNumbers, object.verticalHeaderFormat()); object.setVerticalHeaderFormat(QCalendarWidget::NoVerticalHeader); QCOMPARE(QCalendarWidget::NoVerticalHeader, object.verticalHeaderFormat()); //maximum Date QDate maxDate(2006, 7, 3); object.setMaximumDate(maxDate); QCOMPARE(maxDate, object.maximumDate()); //minimum date QDate minDate(2004, 7, 3); object.setMinimumDate(minDate); QCOMPARE(minDate, object.minimumDate()); //day of week object.setFirstDayOfWeek(Qt::Thursday); QCOMPARE(Qt::Thursday, object.firstDayOfWeek()); //grid visible object.setGridVisible(true); QVERIFY(object.isGridVisible()); object.setGridVisible(false); QVERIFY(!object.isGridVisible()); //header visible object.setNavigationBarVisible(true); QVERIFY(object.isNavigationBarVisible()); object.setNavigationBarVisible(false); QVERIFY(!object.isNavigationBarVisible()); //selection mode QCOMPARE(QCalendarWidget::SingleSelection, object.selectionMode()); object.setSelectionMode(QCalendarWidget::NoSelection); QCOMPARE(QCalendarWidget::NoSelection, object.selectionMode()); object.setSelectionMode(QCalendarWidget::SingleSelection); QCOMPARE(QCalendarWidget::SingleSelection, object.selectionMode()); //selected date QDate selectedDate(2005, 7, 3); QSignalSpy spy(&object, SIGNAL(selectionChanged())); object.setSelectedDate(selectedDate); QCOMPARE(spy.count(), 1); QCOMPARE(selectedDate, object.selectedDate()); //month and year object.setCurrentPage(2004, 1); QCOMPARE(1, object.monthShown()); QCOMPARE(2004, object.yearShown()); object.showNextMonth(); QCOMPARE(2, object.monthShown()); object.showPreviousMonth(); QCOMPARE(1, object.monthShown()); object.showNextYear(); QCOMPARE(2005, object.yearShown()); object.showPreviousYear(); QCOMPARE(2004, object.yearShown()); //date range minDate = QDate(2006,1,1); maxDate = QDate(2010,12,31); object.setDateRange(minDate, maxDate); QCOMPARE(maxDate, object.maximumDate()); QCOMPARE(minDate, object.minimumDate()); //date should not go beyond the minimum. selectedDate = minDate.addDays(-10); object.setSelectedDate(selectedDate); QCOMPARE(minDate, object.selectedDate()); QVERIFY(selectedDate != object.selectedDate()); //date should not go beyond the maximum. selectedDate = maxDate.addDays(10); object.setSelectedDate(selectedDate); QCOMPARE(maxDate, object.selectedDate()); QVERIFY(selectedDate != object.selectedDate()); //show today QDate today = QDate::currentDate(); object.showToday(); QCOMPARE(today.month(), object.monthShown()); QCOMPARE(today.year(), object.yearShown()); //slect a different date and move. object.setSelectedDate(minDate); object.showSelectedDate(); QCOMPARE(minDate.month(), object.monthShown()); QCOMPARE(minDate.year(), object.yearShown()); }
int OCalendarHelper::monthDiff( const QDate& first, const QDate& second ) { return ( second.year() - first.year() ) * 12 + second.month() - first.month(); }
void Tab_Logins::updateDBForWipe(const char * LoginID) { char tmpLogin[64]; char newLogin[64]; char tmpstr[1024]; LoginsDB LDB; ADB DB; NotesDB NDB; int wasActive = 0; QDate tmpDate; char today[64]; strcpy(tmpLogin, LoginID); tmpDate = QDate::currentDate(); sprintf(today, "%04d-%02d-%02d", tmpDate.year(), tmpDate.month(), tmpDate.day()); LDB.get(myCustID, LoginID); DB.dbcmd("update Subscriptions set Active = 0 where LoginID = '%s' and CustomerID = %ld", tmpLogin, myCustID); // Remove any custom flags. DB.dbcmd("delete from LoginFlagValues where LoginID = '%s'", tmpLogin); wasActive = LDB.getInt("Active"); LDB.setValue("Active", (int) 0); LDB.setValue("Wiped", today); LDB.upd(); // Now, just if they were open, update the AR. // If not, don't make an adjusting entry because // the lock routines should have already done that. if (wasActive && isManager()) { QApplication::restoreOverrideCursor(); if (QMessageBox::warning(this, "Prorate Charges", "Do you wish to prorate the charges for this login?", "&Yes", "&No", 0, 1) == 0) { QApplication::setOverrideCursor(WaitCursor); updateARForLock(tmpLogin); QApplication::restoreOverrideCursor(); } QApplication::setOverrideCursor(WaitCursor); } NDB.setValue("LoginID", tmpLogin); NDB.setValue("CustomerID", myCustID); NDB.setValue("NoteType", "Operator"); NDB.setValue("NoteText", "Login Wiped."); NDB.ins(); // Now that they're wiped, rename this login // to show that it has been wiped. // Wiped logins should preface with "Wnn-" where // 'nn' is between 00 and 99. The "W" should be // capitalized, that way it will appear at the // end of the sort list. int StartingNo = 0; int FoundOne = 0; while (!FoundOne) { sprintf(tmpstr, "W%02d-%s", StartingNo, tmpLogin); DB.query("select * from Logins where CustomerID = %ld and LoginID = '%s'", myCustID, tmpstr); if (!DB.rowCount) { FoundOne = 1; strcpy(newLogin, tmpstr); } else { StartingNo++; } } // Now that we've got the newLogin, update // _ALL_ of the tables with it... // Not fun, but necessary. LDB.get(myCustID, tmpLogin); LDB.changeLoginID(newLogin); emit(customerUpdated(myCustID)); refreshLoginList(myCustID); }
void Tab_Logins::updateARForLock(const char * LoginID) { ADB DB; ADB DB2; CustomersDB CDB; LoginsDB LDB; SubscriptionsDB SDB; QDate tmpDate; QDate CycleStart; QDate CycleEnd; QDate yesterday; char sYesterday[64]; int cycleDays; int daysLeft; char today[64]; char sCycleEnd[64]; float Qty; int doEntry; BillingCyclesDB BCDB; tmpDate = QDate::currentDate(); sprintf(today, "%04d-%02d-%02d", tmpDate.year(), tmpDate.month(), tmpDate.day()); CDB.get(myCustID); LDB.get(myCustID, LoginID); BCDB.get(CDB.getInt("BillingCycle")); BCDB.getCycleDates(&CycleStart, &CycleEnd, &cycleDays, &daysLeft,NULL,myCustID); sprintf(sCycleEnd, "%04d-%02d-%02d", CycleEnd.year(), CycleEnd.month(), CycleEnd.day()); // Okay, the first thing we want/need to do is load up the entries // in the AcctsRecv table that have an EndDate > Today. DB.query("select ItemID, Price, Amount, Memo, InternalID from AcctsRecv where CustomerID = %ld and LoginID = '%s' and EndDate > '%s'", myCustID, LoginID, today ); if (DB.rowCount) { // If the customer is active, and we have more than one row, we don't // want to make any adjustments. If they are not active, we're here // to make adjusting entries. while (DB.getrow()) { doEntry = 1; // If they are active now, and our amount > 0, that means // that this is an account that was not previously prorated. // So we don't want to do the adjusting entry. if (LDB.getInt("Active") && (atof(DB.curRow["Amount"]) > 0.0)) doEntry = 0; // If they are not active now, and our amount < 0 that means // they have already been prorated, and we don't need to do // anything more with it. if (!LDB.getInt("Active") && (atof(DB.curRow["Amount"]) < 0.0)) doEntry = 0; if (doEntry) { // It looks as if we need to add to the balance of the user. AcctsRecv AR; AR.ARDB->setValue("CustomerID", myCustID); AR.ARDB->setValue("LoginID", LoginID); AR.ARDB->setValue("ItemID", atoi(DB.curRow["ItemID"])); AR.ARDB->setValue("TransDate", today); AR.ARDB->setValue("StartDate", today); AR.ARDB->setValue("EndDate", sCycleEnd); Qty = (float) daysLeft / cycleDays; if (atof(DB.curRow["Amount"]) > 0) { Qty = Qty * -1.0; } AR.ARDB->setValue("Quantity", Qty); AR.ARDB->setValue("Price", DB.curRow["Price"]); AR.ARDB->setValue("Amount", (float) (atof(DB.curRow["Price"]) * Qty)); AR.ARDB->setValue("Memo", DB.curRow["Memo"]); QString tmpQS; tmpQS = AR.ARDB->getStr("Memo"); if (tmpQS.find('(')) { tmpQS.truncate(tmpQS.find('(') -1); } if (Qty < 0.0) { tmpQS.append(" (Adjustment for account closure)"); } else { tmpQS.append(" (Adjustment for account reactiviation)"); } AR.ARDB->setValue("Memo", (const char *) tmpQS); AR.SaveTrans(); DB2.dbcmd("update AcctsRecv set EndDate = '%s' where InternalID = %ld", today, atol(DB.curRow["InternalID"])); } } } else { // There were no register entries. So make sure there are // Subscriptions for the user. If there aren't, add one. If there // are, update all of the subscriptions for this user so the ends on // date are yesterday, and then do a subscription run for the // customer. DB.query("select InternalID from Subscriptions where CustomerID = %ld and LoginID = '%s'", myCustID, LoginID); if (DB.rowCount) { QDate tmpEndsOn; tmpDate = QDate::currentDate(); yesterday = tmpDate.addDays(-1); sprintf(sYesterday, "%04d-%02d-%02d", yesterday.year(), yesterday.month(), yesterday.day()); while (DB.getrow()) { SDB.get(atol(DB.curRow["InternalID"])); myDatetoQDate((const char *) SDB.getStr("EndsOn"), &tmpEndsOn); // printf("sYesterday = %s, EndsOn = %s\n", sYesterday, (const char *) SDB.getStr("EndsOn")); if (tmpEndsOn < tmpDate) { SDB.setValue("EndsOn", sYesterday); SDB.upd(); } } } else { // No subscriptions. Add them. LDB.get(myCustID, LoginID); LDB.addSubscriptions(); } } }
void Tab_Logins::wipeLogin() { Q3ListViewItem *curItem; curItem = list->currentItem(); if (!curItem) return; // No point in initializing the objects if we don't have any logins. ADB DB; LoginsDB LDB; BrassClient *BC; char today[16]; QDate tmpDate; char tmpLogin[16]; char msg[1024]; tmpDate = QDate::currentDate(); sprintf(today, "%04d-%02d-%02d", tmpDate.year(), tmpDate.month(), tmpDate.day()); LDB.get(myCustID, (const char *) curItem->text(0)); if (LDB.getInt("Active")) { QMessageBox::information(this, "Wipe Login", "Only inactive accounts may be wiped.\nIf you really want to wipe this account, close it first."); return; } else if (strcmp((const char *)LDB.getStr("Wiped"), "0000-00-00")) { QMessageBox::information(this, "Wipe Login", "This login has already been wiped."); return; } else { sprintf(msg, "Are you sure you wish to wipe the login '%s'?", (const char *) curItem->text(0)); if (QMessageBox::warning(this, "Wipe Login", msg, "&Yes", "&No", 0, 1) != 0) return; strcpy(tmpLogin, LDB.getStr("LoginID")); // Remove their CCC Filters and other stuff first. QApplication::setOverrideCursor(WaitCursor); emit setStatus("Removing CCC preferences/filters..."); ADB CCCDB(cfgVal("CCCMySQLDB"), cfgVal("CCCMySQLUser"), cfgVal("CCCMySQLPass"), cfgVal("CCCMySQLHost")); QApplication::restoreOverrideCursor(); if (CCCDB.Connected()) { QApplication::setOverrideCursor(WaitCursor); CCCDB.dbcmd("delete from AddressBook where LoginID = '%s'", tmpLogin); CCCDB.dbcmd("delete from MailFilters where LoginID = '%s'", tmpLogin); CCCDB.dbcmd("delete from Preferences where LoginID = '%s'", tmpLogin); CCCDB.dbcmd("delete from JunkFilter where LoginID = '%s'", tmpLogin); CCCDB.dbcmd("delete from Identities where UserName = '******'", tmpLogin); emit setStatus(""); QApplication::restoreOverrideCursor(); } else { emit setStatus(""); QMessageBox::critical(this, "MySQL Error", "Error connecting to the CCC database.\nUnable to wipe the CCC user information.\nAborting."); return; } // Remove their CCC Filters and other stuff first. QApplication::setOverrideCursor(WaitCursor); emit setStatus("Removing email aliases..."); ADB mailDB(cfgVal("MailSQLDB"), cfgVal("MailSQLUser"), cfgVal("MailSQLPass"), cfgVal("MailSQLHost")); QApplication::restoreOverrideCursor(); if (mailDB.Connected()) { QApplication::setOverrideCursor(WaitCursor); mailDB.dbcmd("delete from Virtual where Mailbox = '%s'", tmpLogin); emit setStatus(""); QApplication::restoreOverrideCursor(); } else { emit setStatus(""); QMessageBox::critical(this, "MySQL Error", "Error connecting to the Postfix database.\nUnable to wipe the Postfix user information.\nAborting."); return; } emit setStatus("Connecting to BRASS server..."); // Okay, they want to. Wipe it. BC = new BrassClient(); if (!BC->Connect()) { QMessageBox::critical(this, "BRASS Error", "Error connecting to the BRASS server."); } else { if (!BC->Authenticate()) { QMessageBox::critical(this, "BRASS Error", "Error authenticating with the BRASS server."); } else { // Well, we finally made it into brass. Wipe the login. QApplication::setOverrideCursor(WaitCursor); emit setStatus("Wiping account..."); if (BC->WipeUser(tmpLogin)) { // Went okay, update the database. // Update any subscriptions, JIC. updateDBForWipe(tmpLogin); } else { QMessageBox::warning(this, "BRASS Error", "Unable to wipe the account."); } emit setStatus(""); QApplication::restoreOverrideCursor(); } } emit setStatus(""); delete BC; } }
void Calendar::updateData() { if (m_days == 0 || m_weeks == 0) { return; } m_dayList.clear(); m_weekList = QJsonArray(); int totalDays = m_days * m_weeks; int daysBeforeCurrentMonth = 0; int daysAfterCurrentMonth = 0; QDate firstDay(m_displayedDate.year(), m_displayedDate.month(), 1); // If the first day is the same as the starting day then we add a complete row before it. if (m_firstDayOfWeek < firstDay.dayOfWeek()) { daysBeforeCurrentMonth = firstDay.dayOfWeek() - m_firstDayOfWeek; } else { daysBeforeCurrentMonth = days() - (m_firstDayOfWeek - firstDay.dayOfWeek()); } int daysThusFar = daysBeforeCurrentMonth + m_displayedDate.daysInMonth(); if (daysThusFar < totalDays) { daysAfterCurrentMonth = totalDays - daysThusFar; } if (daysBeforeCurrentMonth > 0) { QDate previousMonth = m_displayedDate.addMonths(-1); //QDate previousMonth(m_displayedDate.year(), m_displayedDate.month() - 1, 1); for (int i = 0; i < daysBeforeCurrentMonth; i++) { DayData day; day.isCurrent = false; day.dayNumber = previousMonth.daysInMonth() - (daysBeforeCurrentMonth - (i + 1)); day.monthNumber = previousMonth.month(); day.yearNumber = previousMonth.year(); // day.containsEventItems = false; m_dayList << day; } } for (int i = 0; i < m_displayedDate.daysInMonth(); i++) { DayData day; day.isCurrent = true; day.dayNumber = i + 1; // +1 to go form 0 based index to 1 based calendar dates // day.containsEventItems = m_dayHelper->containsEventItems(i + 1); day.monthNumber = m_displayedDate.month(); day.yearNumber = m_displayedDate.year(); m_dayList << day; } if (daysAfterCurrentMonth > 0) { for (int i = 0; i < daysAfterCurrentMonth; i++) { DayData day; day.isCurrent = false; day.dayNumber = i + 1; // +1 to go form 0 based index to 1 based calendar dates // day.containsEventItems = false; day.monthNumber = m_displayedDate.addMonths(1).month(); day.yearNumber = m_displayedDate.addMonths(1).year(); m_dayList << day; } } const int numOfDaysInCalendar = m_dayList.count(); // Week numbers are always counted from Mondays // so find which index is Monday int mondayOffset = 0; if (!m_dayList.isEmpty()) { const DayData &data = m_dayList.at(0); QDate firstDay(data.yearNumber, data.monthNumber, data.dayNumber); // If the first day is not already Monday, get offset for Monday if (firstDay.dayOfWeek() != 1) { mondayOffset = 8 - firstDay.dayOfWeek(); } } // Fill weeksModel with the week numbers for (int i = mondayOffset; i < numOfDaysInCalendar; i += 7) { const DayData &data = m_dayList.at(i); m_weekList.append(QDate(data.yearNumber, data.monthNumber, data.dayNumber).weekNumber()); } emit weeksModelChanged(); m_daysModel->update(); // qDebug() << "---------------------------------------------------------------"; // qDebug() << "Date obj: " << m_displayedDate; // qDebug() << "Month: " << m_displayedDate.month(); // qDebug() << "m_days: " << m_days; // qDebug() << "m_weeks: " << m_weeks; // qDebug() << "Days before this month: " << daysBeforeCurrentMonth; // qDebug() << "Days after this month: " << daysAfterCurrentMonth; // qDebug() << "Days in current month: " << m_displayedDate.daysInMonth(); // qDebug() << "m_dayList size: " << m_dayList.count(); // qDebug() << "---------------------------------------------------------------"; }
QString Jalali::gregorianToJalali(QDate gregorian) { QString jalali; int gy, gm, gd; int jy, jm, jd; long g_day_no, j_day_no; int j_np; int i; int gYear = gregorian.year(); int gMonth = gregorian.month(); int gDay = gregorian.day(); gy = gYear - 1600; gm = gMonth - 1; gd = gDay - 1; g_day_no = 365*gy + (gy+3)/4 - (gy+99)/100 + (gy+399)/400; for ( i=0 ; i<gm ; ++i ) { g_day_no += g_days_in_month_list.at(i); } if (gm>1 && ((gy%4==0 && gy%100!=0) || (gy%400==0))) /* leap and after Feb */ ++g_day_no; g_day_no += gd; j_day_no = g_day_no-79; j_np = j_day_no / 12053; j_day_no %= 12053; jy = 979+33*j_np+4*(j_day_no/1461); j_day_no %= 1461; if (j_day_no >= 366) { jy += (j_day_no-1)/365; j_day_no = (j_day_no-1)%365; } for (i = 0; i < 11 && j_day_no >= j_days_in_month_list.at(i); ++i) { j_day_no -= j_days_in_month_list.at(i); } jm = i+1; jd = j_day_no+1; QVariant jyS=jy,jmS=jm,jdS=jd; if (jmS.toString ().length ()<2) jmS = jmS.toString ().prepend ("0"); if (jdS.toString ().length ()<2) jdS = jdS.toString ().prepend ("0"); jalali = jyS.toString () + "/" + jmS.toString () + "/" + jdS.toString (); return jalali; }
QString FightSheet::generateData() { Style *s = new Style( object->get("style").toInt(), keeper ); setReportFile(s->get("name").toLower() + ".html"); setReportPath("/../share/reports/fightsheet"); Wrestler *red = new Wrestler(object->get("red").toInt(), keeper); Geo *geo_r = new Geo(red->get("geo").toInt(), keeper); Wrestler *blue = new Wrestler(object->get("blue").toInt(), keeper); Geo *geo_b = new Geo(blue->get("geo").toInt(), keeper); Weight *wh = new Weight( object->get("weight").toInt(), keeper ); Competition *c = new Competition(object->get("competition").toInt(), keeper); Mat *mat = new Mat(object->get("mat").toInt(), keeper); CRound *cround = new CRound(object->get("cround").toInt(), keeper); CTour *ctour = new CTour(object->get("ctour").toInt(), keeper); QDate start = QDate::fromString(c->get("start"), QString("yyyy-MM-dd")); QDate stop = QDate::fromString(c->get("stop"), QString("yyyy-MM-dd")); QString date; if ( start.month() == stop.month() ) { date = QString("%1-%2/%3/%4").arg(start.day()).arg(stop.day()).arg(start.month()).arg(start.year()); } else { date = start.toString("dd/MM/yyyy") + " - " + stop.toString("dd/MM/yyyy"); } vars.insert("{red.title}", red->get("title")); vars.insert("{red.geo}", geo_r->get("title")); vars.insert("{blue.title}", blue->get("title")); vars.insert("{blue.geo}", geo_b->get("title")); vars.insert("{style}", s->get("name")); vars.insert("{weight}", wh->get("title")); vars.insert("{competition}", c->get("title")); vars.insert("{mat}", mat->get("title")); vars.insert("{round}", cround->get("title")); vars.insert("{place}", ctour->get("title")); vars.insert("{num}", object->get("num")); vars.insert("{date}", date); TQueryMap opt; opt.insert("competition", keeper->prepareParam(Equal, c->get("id"))); QList<QVariant> id_list; if ( red->get("id").toInt() > 0 ) id_list << red->get("id"); if ( blue->get("id").toInt() > 0 ) id_list << blue->get("id"); opt.insert("wrestler", keeper->prepareParam(And | InSet, id_list )); opt.insert("style", keeper->prepareParam(And | Equal, s->get("id"))); opt.insert("weight", keeper->prepareParam(And | Equal, wh->get("id"))); QList<QVariant> list = keeper->getListOfFields(OCompetitionWrestler, QStringList() << "wrestler" << "sorder", opt); for( int i = 0; i < list.size(); i++) { QStringList row = list.at(i).toStringList(); if ( red->get("id").toInt() == row.at(0).toInt() ) vars.insert("{red.num}", row.at(1)); if ( blue->get("id").toInt() == row.at(0).toInt() ) vars.insert("{blue.num}", row.at(1)); } delete red; delete geo_r; delete geo_b; delete blue; delete s; delete wh; delete mat; delete cround; delete ctour; delete c; return applyTemplateVars(loadTemplate(reportFile), vars); }
int main(int argc, char *argv[]) { cout<<1; srand(time(0)); #ifdef Q_WS_MAEMO_6 //Meego graphics system conflicts with xvideo during fullscreen transition QApplication::setGraphicsSystem("raster"); #endif QApplication app(argc, argv); qDebug()<<1; // QString s = myTr("水电费似懂非懂发"); // while(true) { // qDebug()<<s.toUtf8().toPercentEncoding(); // qDebug()<<s; // cout<<s.toUtf8().data()<<endl; // } QApplication::setStyle(QStyleFactory::create("Fusion")); qDebug()<<QStyleFactory::keys(); // HttpFileDownloader hfd; //hfd.getFileFromURL(QUrl("http://yinyueshiting.baidu.com/data2/music/121523379/14385500158400128.mp3?xcode=c6e50f79d04aaac4b89e9d84f827b20882c86357ec80af0a&song_id=14385500"),"t.mp3"); //hfd.getFileFromURL(QUrl("http://www.acfun.tv/a/ac1515425"),"t.txt"); UserBank::load(); { QDir d; d.mkdir("hint"); } MessageCenter mc; CHotKeyEventFilter hk(mc.winId()); app.installNativeEventFilter(&hk); QTimer t1; if (mc.registerTitle("mayu player")) { QObject::connect(&t1, &QTimer::timeout, [&]() { if (mc.addPartner("mayu danmu") ) { } else { qDebug()<<"Danmu assistant is not running!" ; } t1.start(40000); }); t1.start(1000); } else { QMessageBox::critical(0, "error", "The media player was running!" ); return 0; } // mc.registerHotkey(MOD_CONTROL, VK_OEM_PLUS); Player player; //player.getMp3UrlFrom163(myTr("小鸡哔哔")); QIcon ico(QString(":/ico/scorpio3.ico")); player.setWindowIcon(ico); // QObject::connect(& (mc), &MessageCenter::globalHotkey, [&](UINT, UINT){ player.playNextSong(); qDebug()<<"hotkey play next song"; }); QObject::connect(&hk, &CHotKeyEventFilter::HotKeyTrigger,[&]( ){ player.playNextSong(); qDebug()<<"hotkey play next song"; } ); player.danmuConnectionTimer.start(20000); QObject::connect(& (player.danmuConnectionTimer), &QTimer::timeout, [&](){ mc.addOutput("mayu danmu"); //qDebug()<<"reconnect danmu"; player.danmuConnectionTimer.start(20000); }); player.loadMusicListFileNames(); QObject::connect(&mc, &MessageCenter::sendMessage, &player, &Player::getDanmu); QObject::connect(&player, &Player::informUser, &mc, &MessageCenter::broadcast ); #if defined(Q_WS_SIMULATOR) player.setAttribute(Qt::WA_LockLandscapeOrientation); player.showMaximized(); #else player.show(); #endif QTimer t; { t.start(10000); QObject::connect(&t, &QTimer::timeout, [&]() { static bool init = false; if (!init) { init = true; mc.broadcast(myTr("麻由的点歌助手上线")); } //qDebug()<<"test"; QDate d = QDate::currentDate(); if (d.month()!=3) { t.stop();; return; } if (d.day()!=18 && d.day()!=19) { t.stop();; return; } if (d.day()==18) { t.start(60000); return; } //qDebug()<<"test"; QString s = myTr("{\"chatid\":\"8526706110\",\"cmdid\":\"chatmessage\",\"content\":\"点歌生日快乐\",\"fromid\":1709988274,\"fromname\":\"天蝎1000\",\"fromuid\":359887,\"intotallist\":0,\"inweeklist\":0,\"ip\":\"101.254.181.34\",\"level\":0,\"permission\":30,\"rank\":\"primary\",\"showmedal\":1,\"speakinroom\":1,\"style\":null,\"time\":\"20:49\",\"toid\":0,\"usexuanzi\":0}"); player.danmuHistory.push_back(s); player.playNextSong(); t.stop(); }); } int re = app.exec(); UserBank::save(); player.saveMusicListFileNames(); mc.unregisterHotkey(); return re; QApplication aaa(argc, argv); /* MessageCenter a; bool b = a.registerTitle("aaaa"); a.show(); a.hide(); qDebug()<<b; if (b) { while(true) { a.broadcast("asdfadsf"); aaa.processEvents(); } } else { b = a.registerTitle("bbbb"); a.show(); a.hide(); a.addOutput("aaaa"); } */ return aaa.exec(); }
void PickBirthDate::setDate(const QDate &date) { day->setValue(date.day()); month->setValue(date.month()); year->setValue(date.year()); }
/* This writes a TNEF property to the file. * * A TNEF property has a 1 byte type (LVL_MESSAGE or LVL_ATTACHMENT), * a 4 byte type/tag, a 4 byte length, the data and finally the checksum. * * The checksum is a 16 byte int with all bytes in the data added. */ bool KTNEFWriter::writeProperty(QDataStream &stream, int &bytes, int tag) { QMap<int, KTNEFProperty *> &properties = mData->properties.properties(); QMap<int, KTNEFProperty *>::Iterator it = properties.find(tag); if(it == properties.end()) return false; KTNEFProperty *property = *it; Q_UINT32 i; Q_UINT16 checksum = 0; QValueList<QVariant> list; QString s; QCString cs, cs2; QDateTime dt; QDate date; QTime time; switch(tag) { case attMSGSTATUS: // Q_UINT8 i = property->value().toUInt() & 0xff; checksum = i; stream << (Q_UINT8)LVL_MESSAGE; stream << mergeTagAndType(tag, property->type()); stream << (Q_UINT32)1; stream << (Q_UINT8)i; bytes += 10; break; case attMSGPRIORITY: case attREQUESTRES: // Q_UINT16 i = property->value().toUInt() & 0xffff; addToChecksum(i, checksum); stream << (Q_UINT8)LVL_MESSAGE; stream << mergeTagAndType(tag, property->type()); stream << (Q_UINT32)2; stream << (Q_UINT16)i; bytes += 11; break; case attTNEFVERSION: // Q_UINT32 i = property->value().toUInt(); addToChecksum(i, checksum); stream << (Q_UINT8)LVL_MESSAGE; stream << mergeTagAndType(tag, property->type()); stream << (Q_UINT32)4; stream << (Q_UINT32)i; bytes += 13; break; case attOEMCODEPAGE: // 2 Q_UINT32 list = property->value().toList(); assert(list.count() == 2); stream << (Q_UINT8)LVL_MESSAGE; stream << mergeTagAndType(tag, property->type()); stream << (Q_UINT32)8; i = list[0].toInt(); addToChecksum(i, checksum); stream << (Q_UINT32)i; i = list[1].toInt(); addToChecksum(i, checksum); stream << (Q_UINT32)i; bytes += 17; break; case attMSGCLASS: case attSUBJECT: case attBODY: case attMSGID: // QCString cs = property->value().toString().local8Bit(); addToChecksum(cs, checksum); stream << (Q_UINT8)LVL_MESSAGE; stream << mergeTagAndType(tag, property->type()); stream << (Q_UINT32)cs.length() + 1; writeCString(stream, cs); bytes += 9 + cs.length() + 1; break; case attFROM: // 2 QString encoded to a TRP structure list = property->value().toList(); assert(list.count() == 2); cs = list[0].toString().local8Bit(); // Name cs2 = (QString("smtp:") + list[1].toString()).local8Bit(); // Email address i = 18 + cs.length() + cs2.length(); // 2 * sizof(TRP) + strings + 2x'\0' stream << (Q_UINT8)LVL_MESSAGE; stream << mergeTagAndType(tag, property->type()); stream << (Q_UINT32)i; // The stream has to be aligned to 4 bytes for the strings // TODO: Or does it? Looks like Outlook doesn't do this // bytes += 17; // Write the first TRP structure stream << (Q_UINT16)4; // trpidOneOff stream << (Q_UINT16)i; // totalsize stream << (Q_UINT16)(cs.length() + 1); // sizeof name stream << (Q_UINT16)(cs2.length() + 1); // sizeof address // if ( bytes % 4 != 0 ) // Align the buffer // Write the strings writeCString(stream, cs); writeCString(stream, cs2); // Write the empty padding TRP structure (just zeroes) stream << (Q_UINT32)0 << (Q_UINT32)0; addToChecksum(4, checksum); addToChecksum(i, checksum); addToChecksum(cs.length() + 1, checksum); addToChecksum(cs2.length() + 1, checksum); addToChecksum(cs, checksum); addToChecksum(cs2, checksum); bytes += 10; break; case attDATESENT: case attDATERECD: case attDATEMODIFIED: // QDateTime dt = property->value().toDateTime(); time = dt.time(); date = dt.date(); stream << (Q_UINT8)LVL_MESSAGE; stream << mergeTagAndType(tag, property->type()); stream << (Q_UINT32)14; i = (Q_UINT16)date.year(); addToChecksum(i, checksum); stream << (Q_UINT16)i; i = (Q_UINT16)date.month(); addToChecksum(i, checksum); stream << (Q_UINT16)i; i = (Q_UINT16)date.day(); addToChecksum(i, checksum); stream << (Q_UINT16)i; i = (Q_UINT16)time.hour(); addToChecksum(i, checksum); stream << (Q_UINT16)i; i = (Q_UINT16)time.minute(); addToChecksum(i, checksum); stream << (Q_UINT16)i; i = (Q_UINT16)time.second(); addToChecksum(i, checksum); stream << (Q_UINT16)i; i = (Q_UINT16)date.dayOfWeek(); addToChecksum(i, checksum); stream << (Q_UINT16)i; break; /* case attMSGSTATUS: { Q_UINT8 c; Q_UINT32 flag = 0; if ( c & fmsRead ) flag |= MSGFLAG_READ; if ( !( c & fmsModified ) ) flag |= MSGFLAG_UNMODIFIED; if ( c & fmsSubmitted ) flag |= MSGFLAG_SUBMIT; if ( c & fmsHasAttach ) flag |= MSGFLAG_HASATTACH; if ( c & fmsLocal ) flag |= MSGFLAG_UNSENT; d->stream_ >> c; i = property->value().toUInt(); stream << (Q_UINT8)LVL_MESSAGE; stream << (Q_UINT32)type; stream << (Q_UINT32)2; stream << (Q_UINT8)i; addToChecksum( i, checksum ); // from reader: d->message_->addProperty( 0x0E07, MAPI_TYPE_ULONG, flag ); } kdDebug() << "Message Status" << " (length=" << i2 << ")" << endl; break; */ default: kdDebug() << "Unknown TNEF tag: " << tag << endl; return false; } stream << (Q_UINT16)checksum; return true; }
void ReportView::chooseDate(int idx) { if(!transactionProxyModel) return; QDate current = QDate::currentDate(); dateRangeWidget->setVisible(false); switch(dateWidget->itemData(idx).toInt()) { case All: transactionProxyModel->setDateRange( TransactionFilterProxy::MIN_DATE, TransactionFilterProxy::MAX_DATE); break; case Today: transactionProxyModel->setDateRange( QDateTime(current), TransactionFilterProxy::MAX_DATE); break; case Yesterday:{ QDate startOfDay = current.addDays(-1); transactionProxyModel->setDateRange( QDateTime(startOfDay), QDateTime(current)); } break; case ThisWeek: { // Find last Monday QDate startOfWeek = current.addDays(-(current.dayOfWeek()-1)); transactionProxyModel->setDateRange( QDateTime(startOfWeek), TransactionFilterProxy::MAX_DATE); } break; case LastWeek: { //from Monday to Sunday QDate startOfWeek = current.addDays(-(current.dayOfWeek()+6)); QDate endOfWeek = current.addDays(-(current.dayOfWeek()-1)); transactionProxyModel->setDateRange( QDateTime(startOfWeek), QDateTime(endOfWeek)); } break; case ThisMonth: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), current.month(), 1)), TransactionFilterProxy::MAX_DATE); break; case LastMonth: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), current.month()-1, 1)), QDateTime(QDate(current.year(), current.month(), 1))); break; case ThisYear: transactionProxyModel->setDateRange( QDateTime(QDate(current.year(), 1, 1)), TransactionFilterProxy::MAX_DATE); break; case Range: dateRangeWidget->setVisible(true); dateRangeChanged(); break; } showTotal(); }
// http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns static void finishStr(QString &str, const WeekDate &week_date, const QDate &date, const QTime &time, QChar c, int length) { if (length <= 0) return; switch (c.unicode()) { case L'G': { bool ad = date.year() > 0; if (length < 4) str += ad ? "AD" : "BC"; else if (length == 4) str += ad ? "Anno Domini" : "Before Christ"; else str += ad ? "A" : "B"; break; } case L'y': if (length == 2) appendInt(str, date.year() % 100, 2); else appendInt(str, date.year(), length); break; case L'Y': appendInt(str, week_date.year(), length); break; case L'u': { int year = date.year(); if (year < 0) year++; appendInt(str, date.year(), length); break; } case L'q': case L'Q': { int q = (date.month() + 2) / 3; if (length < 3) appendInt(str, q, length); else if (length == 3) { str += 'Q'; str += QString::number(q); } else { switch (q) { case 1: str += qApp->translate("AdiumTimeFormatter", "1st quarter"); break; case 2: str += qApp->translate("AdiumTimeFormatter", "2nd quarter"); break; case 3: str += qApp->translate("AdiumTimeFormatter", "3rd quarter"); break; case 4: str += qApp->translate("AdiumTimeFormatter", "4th quarter"); break; default: break; } } break; } case L'M': case L'L': if (length < 3) appendInt(str, date.month(), length); else if (length == 3) str += QDate::shortMonthName(date.month()); else if (length == 4) str += QDate::longMonthName(date.month()); else str += QDate::shortMonthName(date.month()).at(0); break; case L'w': TRIM_LENGTH(2); appendInt(str, length, week_date.week()); break; case L'W': while (length-- > 0) str += QString::number((date.day() + 6) / 7); break; case L'd': TRIM_LENGTH(2); appendInt(str, date.day(), length); break; case L'D': TRIM_LENGTH(3); appendInt(str, date.dayOfYear(), length); break; case L'F': while (length-- > 0) str += QString::number(1); break; case L'g': appendInt(str, date.toJulianDay(), length); break; case L'c': case L'e': if (length < 3) { appendInt(str, date.dayOfWeek(), length); break; } case L'E': if (length < 4) str += QDate::shortDayName(date.dayOfWeek()); else if (length == 4) str += QDate::longDayName(date.dayOfWeek()); else str += QDate::shortDayName(date.dayOfWeek()).at(0); break; case L'a': str += time.hour() < 12 ? "AM" : "PM"; break; case L'H': TRIM_LENGTH(2); appendInt(str, time.hour(), length); break; case L'h': TRIM_LENGTH(2); appendInt(str, time.hour() % 12, length); break; case L'K': TRIM_LENGTH(2); appendInt(str, time.hour() - 1, length); break; case L'k': TRIM_LENGTH(2); appendInt(str, time.hour() % 12 - 1, length); break; case L'm': TRIM_LENGTH(2); appendInt(str, time.minute(), length); break; case L's': TRIM_LENGTH(2); appendInt(str, time.second(), length); break; case L'S': str += QString::number(time.msec() / 1000.0, 'f', length).section('.', 1); break; case L'A': appendInt(str, QTime(0,0).msecsTo(time), length); break; case L'v': // I don't understand the difference case L'z': if (length < 4) str += SystemInfo::instance()->timezone(); else // There should be localized name, but I don't know how get it str += SystemInfo::instance()->timezone(); break; case L'Z': { if (length == 4) str += "GMT"; int offset = SystemInfo::instance()->timezoneOffset(); if (offset < 0) str += '+'; else str += '-'; appendInt(str, qAbs((offset/60)*100 + offset%60), 4); break; } default: while (length-- > 0) str += c; break; } }
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 == _nullString || dateString.isEmpty()) setNull(); else if (dateString == "0") // today setDate(today, TRUE); else if (dateString.contains(QRegExp("^[+-][0-9]+"))) // offset from today { int offset = dateString.toInt(&isNumeric); if (isNumeric) setDate(today.addDays(offset), true); } else if (dateString[0] == '#') // julian day { int offset = dateString.right(dateString.length() - 1).toInt(&isNumeric); if (isNumeric) setDate(QDate(today.year(), 1, 1).addDays(offset - 1), TRUE); } 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(); setDate(QDate(today.year(), today.month(), 1).addDays(offset - 1), TRUE); } } 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); } } } setDate(QDate(tmp.year(), tmp.month(), tmp.day()), true ); } if (!_valid) setText(""); _parsed = true; }
/*! 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; }
void MainWindow::printToPage(QPainter *p, QRectF sp) { QRectF pos = sp; QRectF pos2; pos.setLeft(pos.left() + adjust->value("x", 0).toInt() - 40 ); pos.setTop( pos.top() + adjust->value("y", 0).toInt() + 300 ); if(ui->beg->text().length() > 27) { p->drawText(pos, ui->beg->text()); }else{ pos2 = pos; for(int i = 0; i < ui->beg->text().length(); i++) { pos2.setLeft(pos.left() + i * 118); p->drawText(pos2, ui->beg->text().at(i)); } } pos.setTop( pos.top() + 210 ); pos2 = pos; for(int i = 0; i < ui->begIBAN->text().remove(" ").length(); i++) { pos2.setLeft(pos.left() + i * 93); p->drawText(pos2, ui->begIBAN->text().remove(" ").at(i)); } pos.setTop( pos.top() + 210 ); pos2 = pos; for(int i = 0; i < ui->begBIC->text().length(); i++) { pos2.setLeft(pos.left() + i * 118); p->drawText(pos2, ui->begBIC->text().at(i)); } pos.setTop( pos.top() + 185); pos2 = pos; pos2.setLeft( pos2.left() + 1770 ); for(int i = 0; i < ui->betrag->text().length(); i++) { p->drawText(pos2, ui->betrag->text().at(i)); pos2.setLeft(pos2.left() + 118); } pos.setTop( pos.top() + 210); pos2 = pos; for(int i = 0; i < ui->verwendungszweck->text().length(); i++) { pos2.setLeft(pos.left() + i * 118); p->drawText(pos2, ui->verwendungszweck->text().at(i)); } pos.setTop( pos.top() + 200); pos2 = pos; if(ui->nochVerwendungszweck->text().length() > 27) { p->drawText(pos, ui->nochVerwendungszweck->text()); }else{ for(int i = 0; i < ui->nochVerwendungszweck->text().length(); i++) { pos2.setLeft(pos.left() + i * 118); p->drawText(pos2, ui->nochVerwendungszweck->text().at(i)); } } pos.setTop( pos.top() + 200); pos2 = pos; for(int i = 0; i < ui->inhaber->text().length(); i++) { pos2.setLeft(pos.left() + i * 118); p->drawText(pos2, ui->inhaber->text().at(i)); } pos.setTop( pos.top() + 200); pos2 = pos; for(int i = 0; i < ui->inhaberIBAN->text().remove(" ").length(); i++) { pos2.setLeft(pos.left() + i * 118); if(i > 1) p->drawText(pos2, ui->inhaberIBAN->text().remove(" ").at(i)); } pos.setTop( pos.top() + 350); QDate currDate = QDateTime::currentDateTime().date(); p->drawText(pos, QString( currDate.day() < 10 ? "0" : "" ) + QString::number(currDate.day()) + QString(".") + QString(currDate.month() < 10 ? "0" : "" ) + QString::number(currDate.month()) + QString(".") + QString::number(currDate.year())); }