コード例 #1
0
ファイル: UT.cpp プロジェクト: bazzinotti/art-core
QString UT::GetCurrentDate()
{
	QDate date = QDate::currentDate();
	QString dateString = date.toString();
	return dateString;
}	
コード例 #2
0
void KMyMoneyBriefSchedule::loadSchedule()
{
    try {
        if (m_index < m_scheduleList.count()) {
            MyMoneySchedule sched = m_scheduleList[m_index];

            m_indexLabel->setText(i18n("%1 of %2", m_index + 1, m_scheduleList.count()));
            m_name->setText(sched.name());
            m_type->setText(KMyMoneyUtils::scheduleTypeToString(sched.type()));
            m_account->setText(sched.account().name());
            QString text;
            MyMoneyMoney amount = sched.transaction().splitByAccount(sched.account().id()).value();
            amount = amount.abs();

            if (sched.willEnd()) {
                int transactions = sched.paymentDates(m_date, sched.endDate()).count() - 1;
                text = i18np("Payment on %2 for %3 with %1 transaction remaining occurring %4.",
                             "Payment on %2 for %3 with %1 transactions remaining occurring %4.",
                             transactions,
                             KGlobal::locale()->formatDate(m_date),
                             amount.formatMoney(sched.account().fraction()),
                             i18n(sched.occurrenceToString().toLatin1()));
            } else {
                text = i18n("Payment on %1 for %2 occurring %3.",
                            KGlobal::locale()->formatDate(m_date),
                            amount.formatMoney(sched.account().fraction()),
                            i18n(sched.occurrenceToString().toLatin1()));
            }

            if (m_date < QDate::currentDate()) {
                if (sched.isOverdue()) {
                    QDate startD = (sched.lastPayment().isValid()) ?
                                   sched.lastPayment() :
                                   sched.startDate();

                    if (m_date.isValid())
                        startD = m_date;

                    int days = startD.daysTo(QDate::currentDate());
                    int transactions = sched.paymentDates(startD, QDate::currentDate()).count();

                    text += "<br><font color=red>";
                    text += i18np("%1 day overdue", "%1 days overdue", days);
                    text += QString(" ");
                    text += i18np("(%1 occurrence.)", "(%1 occurrences.)", transactions);
                    text += "</color>";
                }
            }

            m_details->setText(text);

            m_prevButton->setEnabled(true);
            m_nextButton->setEnabled(true);
            m_skipButton->setEnabled(sched.occurrencePeriod() != MyMoneySchedule::OCCUR_ONCE);

            if (m_index == 0)
                m_prevButton->setEnabled(false);
            if (m_index == (m_scheduleList.count() - 1))
                m_nextButton->setEnabled(false);
        }
    } catch (const MyMoneyException &) {
    }
}
コード例 #3
0
// Apply a simple variant type to a DOM property
static bool applySimpleProperty(const QVariant &v, bool translateString, DomProperty *dom_prop)
{
    switch (v.type()) {
    case QVariant::String: {
        DomString *str = new DomString();
        str->setText(v.toString());
        if (!translateString)
            str->setAttributeNotr(QLatin1String("true"));
        dom_prop->setElementString(str);
    }
        return true;

    case QVariant::ByteArray:
        dom_prop->setElementCstring(QString::fromUtf8(v.toByteArray()));
        return true;

    case QVariant::Int:
        dom_prop->setElementNumber(v.toInt());
        return true;

    case QVariant::UInt:
        dom_prop->setElementUInt(v.toUInt());
        return true;

    case QVariant::LongLong:
        dom_prop->setElementLongLong(v.toLongLong());
        return true;

    case QVariant::ULongLong:
        dom_prop->setElementULongLong(v.toULongLong());
        return true;

    case QVariant::Double:
        dom_prop->setElementDouble(v.toDouble());
        return true;

    case QVariant::Bool:
        dom_prop->setElementBool(v.toBool() ? QFormBuilderStrings::instance().trueValue : QFormBuilderStrings::instance().falseValue);
        return true;

    case QVariant::Char: {
        DomChar *ch = new DomChar();
        const QChar character = v.toChar();
        ch->setElementUnicode(character.unicode());
        dom_prop->setElementChar(ch);
    }
        return true;

    case QVariant::Point: {
        DomPoint *pt = new DomPoint();
        const QPoint point = v.toPoint();
        pt->setElementX(point.x());
        pt->setElementY(point.y());
        dom_prop->setElementPoint(pt);
    }
        return true;

    case QVariant::PointF: {
        DomPointF *ptf = new DomPointF();
        const QPointF pointf = v.toPointF();
        ptf->setElementX(pointf.x());
        ptf->setElementY(pointf.y());
        dom_prop->setElementPointF(ptf);
    }
        return true;

    case QVariant::Color: {
        DomColor *clr = new DomColor();
        const QColor color = qvariant_cast<QColor>(v);
        clr->setElementRed(color.red());
        clr->setElementGreen(color.green());
        clr->setElementBlue(color.blue());
        const int alphaChannel = color.alpha();
        if (alphaChannel != 255)
            clr->setAttributeAlpha(alphaChannel);
        dom_prop->setElementColor(clr);
    }
        return true;

    case QVariant::Size: {
        DomSize *sz = new DomSize();
        const QSize size = v.toSize();
        sz->setElementWidth(size.width());
        sz->setElementHeight(size.height());
        dom_prop->setElementSize(sz);
    }
        return true;

    case QVariant::SizeF: {
        DomSizeF *szf = new DomSizeF();
        const QSizeF sizef = v.toSizeF();
        szf->setElementWidth(sizef.width());
        szf->setElementHeight(sizef.height());
        dom_prop->setElementSizeF(szf);
    }
        return true;

    case QVariant::Rect: {
        DomRect *rc = new DomRect();
        const QRect rect = v.toRect();
        rc->setElementX(rect.x());
        rc->setElementY(rect.y());
        rc->setElementWidth(rect.width());
        rc->setElementHeight(rect.height());
        dom_prop->setElementRect(rc);
    }
        return true;

    case QVariant::RectF: {
        DomRectF *rcf = new DomRectF();
        const QRectF rectf = v.toRectF();
        rcf->setElementX(rectf.x());
        rcf->setElementY(rectf.y());
        rcf->setElementWidth(rectf.width());
        rcf->setElementHeight(rectf.height());
        dom_prop->setElementRectF(rcf);
    }
        return true;

    case QVariant::Font: {
        DomFont *fnt = new DomFont();
        const QFont font = qvariant_cast<QFont>(v);
        const uint mask = font.resolve();
        if (mask & QFont::WeightResolved) {
            fnt->setElementBold(font.bold());
            fnt->setElementWeight(font.weight());
        }
        if (mask & QFont::FamilyResolved)
            fnt->setElementFamily(font.family());
        if (mask & QFont::StyleResolved)
            fnt->setElementItalic(font.italic());
        if (mask & QFont::SizeResolved)
            fnt->setElementPointSize(font.pointSize());
        if (mask & QFont::StrikeOutResolved)
            fnt->setElementStrikeOut(font.strikeOut());
        if (mask & QFont::UnderlineResolved)
            fnt->setElementUnderline(font.underline());
        if (mask & QFont::KerningResolved)
            fnt->setElementKerning(font.kerning());
        if (mask & QFont::StyleStrategyResolved) {
            const QMetaEnum styleStrategy_enum = metaEnum<QAbstractFormBuilderGadget>("styleStrategy");
            fnt->setElementStyleStrategy(QLatin1String(styleStrategy_enum.valueToKey(font.styleStrategy())));
        }
        dom_prop->setElementFont(fnt);
    }
        return true;

#ifndef QT_NO_CURSOR
    case QVariant::Cursor: {
        const QMetaEnum cursorShape_enum = metaEnum<QAbstractFormBuilderGadget>("cursorShape");
        dom_prop->setElementCursorShape(QLatin1String(cursorShape_enum.valueToKey(qvariant_cast<QCursor>(v).shape())));
        }
        return true;
#endif

    case QVariant::KeySequence: {
        DomString *s = new DomString();
        s->setText(qvariant_cast<QKeySequence>(v).toString(QKeySequence::PortableText));
        dom_prop->setElementString(s);
        }
        return true;

    case QVariant::Locale: {
        DomLocale *dom = new DomLocale();
        const QLocale locale = qvariant_cast<QLocale>(v);

        const QMetaEnum language_enum = metaEnum<QAbstractFormBuilderGadget>("language");
        const QMetaEnum country_enum = metaEnum<QAbstractFormBuilderGadget>("country");

        dom->setAttributeLanguage(QLatin1String(language_enum.valueToKey(locale.language())));
        dom->setAttributeCountry(QLatin1String(country_enum.valueToKey(locale.country())));

        dom_prop->setElementLocale(dom);
        }
        return true;

    case QVariant::SizePolicy: {
        DomSizePolicy *dom = new DomSizePolicy();
        const QSizePolicy sizePolicy = qvariant_cast<QSizePolicy>(v);

        dom->setElementHorStretch(sizePolicy.horizontalStretch());
        dom->setElementVerStretch(sizePolicy.verticalStretch());

        const QMetaEnum sizeType_enum = metaEnum<QAbstractFormBuilderGadget>("sizeType");

        dom->setAttributeHSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.horizontalPolicy())));
        dom->setAttributeVSizeType(QLatin1String(sizeType_enum.valueToKey(sizePolicy.verticalPolicy())));

        dom_prop->setElementSizePolicy(dom);
    }
        return true;

    case QVariant::Date: {
        DomDate *dom = new DomDate();
        const QDate date = qvariant_cast<QDate>(v);

        dom->setElementYear(date.year());
        dom->setElementMonth(date.month());
        dom->setElementDay(date.day());

        dom_prop->setElementDate(dom);
        }
        return true;

    case QVariant::Time: {
        DomTime *dom = new DomTime();
        const QTime time = qvariant_cast<QTime>(v);

        dom->setElementHour(time.hour());
        dom->setElementMinute(time.minute());
        dom->setElementSecond(time.second());

        dom_prop->setElementTime(dom);
        }
        return true;

    case QVariant::DateTime: {
        DomDateTime *dom = new DomDateTime();
        const QDateTime dateTime = qvariant_cast<QDateTime>(v);

        dom->setElementHour(dateTime.time().hour());
        dom->setElementMinute(dateTime.time().minute());
        dom->setElementSecond(dateTime.time().second());
        dom->setElementYear(dateTime.date().year());
        dom->setElementMonth(dateTime.date().month());
        dom->setElementDay(dateTime.date().day());

        dom_prop->setElementDateTime(dom);
    }
        return true;

    case QVariant::Url: {
        DomUrl *dom = new DomUrl();
        const QUrl url = v.toUrl();

        DomString *str = new DomString();
        str->setText(url.toString());
        dom->setElementString(str);

        dom_prop->setElementUrl(dom);
    }
        return true;

    case QVariant::StringList: {
        DomStringList *sl = new DomStringList;
        sl->setElementString(qvariant_cast<QStringList>(v));
        dom_prop->setElementStringList(sl);
    }
        return true;

    default:
        break;
    }

    return false;
}
コード例 #4
0
ファイル: Zones.cpp プロジェクト: gregf83/GoldenCheetah
QString Zones::getStartDateString(int rnum) const
{
    assert(rnum >= 0);
    QDate d = ranges[rnum].begin;
    return (d.isNull() ? "BEGIN" : d.toString());
}
コード例 #5
0
void FrmInformacionFarmaco::finishedSlotBuscarMedicamento(QNetworkReply* reply)
{
    //qDebug()<<reply->readAll();
    QString data=(QString)reply->readAll();
    QString cXML = data;

    // Extract values from XML
    QDomDocument document("XmlDoc");
    document.setContent(cXML);

    QDomElement root = document.documentElement();
    if (root .tagName() != "object")
        qDebug("Bad root element.");

    QDomNode drugList = root.firstChild();

    QDomNode n = drugList.firstChild();
    QDomNode n2 = n.firstChild();
    QDomNode n3 = n2.firstChild();
    while (!n.isNull()) {
        if (n.isElement()) {
            QDomNodeList attributes = n.childNodes();

            for (int i = 0; i < attributes.count(); i ++) {
                QDomElement e = attributes.at(i).toElement();

                if (e.tagName() == "name_speciality") {
                    ui->txtNombre->setText(e.text());
                }
                if (e.tagName() == "dosage_form") {
                    ui->txtDosificacion->setText(e.text());
                }
                if (e.tagName() == "national_code") {
                    ui->txtcodigo_nacional->setText(e.text());
                }
                if (e.tagName() == "name_laboratory") {
                    ui->txtLaboratorio->setText(e.text());
                }
                if (e.tagName() == "name_atc") {
                    ui->txtNombreATC->setText(e.text());
                }
                if (e.tagName() == "drug_type") {
                    ui->txtTipoMedicamento->setText(e.text());
                }
                if (e.tagName() == "package") {
                    ui->txtCaja->setText(e.text());
                }
                if (e.tagName() == "price") {
                    ui->txtPVP->setText(e.text());
                }
                if (e.tagName() == "laboratory_price") {
                    ui->txtPVC->setText(e.text());
                }
                if (e.tagName() == "TLD") {
                    ui->txtTLD->setText(e.text());
                }
                if (e.tagName() == "RECETA") {
                    ui->txtReceta->setText(e.text());
                }
                if (e.tagName() == "FINAN") {
                    ui->txtFinanciado->setText(e.text());
                }
                if (e.tagName() == "fecha_alta") {
                    QDate alta;
                    int ano,mes,dia;
                    ano = e.text().left(4).toInt();
                    mes = e.text().mid(5,2).toInt();
                    dia = e.text().mid(8,2).toInt();
                    alta.setDate(ano,mes,dia);
                    ui->txtfecha_alta->setDate(alta);
                }
                if (e.tagName() == "fecha_baja") {
                    if (e.text()!="0" && !e.text().isEmpty()) {
                        QDate baja;
                        int ano,mes,dia;
                        ano = e.text().left(4).toInt();
                        mes = e.text().mid(5,2).toInt();
                        dia = e.text().mid(8,2).toInt();
                        baja.setDate(ano,mes,dia);
                        ui->txtFechaBaja->setVisible(true);
                        ui->lblfechabaja->setVisible(true);
                        ui->txtFechaBaja->setDate(baja);
                    } else {
                        ui->txtFechaBaja->setVisible(false);
                        ui->lblfechabaja->setVisible(false);
                    }
                }
                if (e.tagName() == "baja") {
                    if(e.text()=="1")
                        ui->lblDadodeBaja->setVisible(true);
                    else
                        ui->lblDadodeBaja->setVisible(false);
                }

                if (e.tagName() == "id_laboratory") {
                    QUrl  uUrl;
                    QString cUrl = "http://svadcf.es/documentos/image/fotos/laboratorio/"+e.text().trimmed()+".gif";
                    uUrl.setUrl(cUrl);
                    ui->webLogoLaboratorio->load(uUrl);
                }

                if (e.tagName() == "id_speciality") {
                    connect(ui->webimagen1,SIGNAL(loadFinished(bool)),this, SLOT(cargaFinalizada1(bool)));
                    connect(ui->webimagen2,SIGNAL(loadFinished(bool)),this, SLOT(cargaFinalizada2(bool)));
                    connect(ui->webimagen3,SIGNAL(loadFinished(bool)),this, SLOT(cargaFinalizada3(bool)));
                    connect(ui->webLogoLaboratorio,SIGNAL(loadFinished(bool)),this, SLOT(cargaFinalizadaLogo(bool)));
                    QUrl  uUrl;
                    QString cUrl = "http://svadcf.es/documentos/image/fotos/medicamento/"+e.text().trimmed()+"_1.jpg";
                    uUrl.setUrl(cUrl);
                    ui->webimagen1->load(uUrl);

                    cUrl = "http://svadcf.es/documentos/image/fotos/medicamento/"+e.text().trimmed()+"_2.jpg";
                    uUrl.setUrl(cUrl);
                    ui->webimagen2->load(uUrl);
                    cUrl = "http://svadcf.es/documentos/image/fotos/medicamento/"+e.text().trimmed()+"_3.jpg";
                    uUrl.setUrl(cUrl);
                    ui->webimagen3->load(uUrl);
                }

                //----------------------------
                // Llenar tabla indicaciones
                //----------------------------

                if (e.tagName() == "Indications_set") {
                    ui->listaIndicaciones->setColumnCount(2);
                    ui->listaIndicaciones->setColumnWidth(0,200);
                    ui->listaIndicaciones->setColumnWidth(1,0);

                    //int nrow = 0;
                    int pos = 0;
                    while (!n2.isNull()) {
                        if (n2.isElement()) {
                            QDomNodeList attributes = n2.childNodes();

                            for (int i = 0; i < attributes.count(); i ++) {
                                QDomElement e2 = attributes.at(i).toElement();
                                if (e2.tagName() == "")
                                    while (!n3.isNull()) {
                                        if (n3.isElement()) {
                                            QDomNodeList attributes = n3.childNodes();

                                            for (int i = 0; i < attributes.count(); i ++) {
                                                QDomElement e3 = attributes.at(i).toElement();
                                                if (e3.tagName() == "id_IND") {
                                                    ui->listaIndicaciones->setRowCount(pos+1);
                                                    QTableWidgetItem *newItem = new QTableWidgetItem(e3.text());
                                                    // para que los elementos no sean editables
                                                    newItem->setFlags(newItem->flags() & (~Qt::ItemIsEditable));
                                                    newItem->setTextColor(Qt::blue); // color de los items

                                                    ui->listaIndicaciones->setItem(pos,1,newItem);
                                                }
                                                if (e3.tagName() == "TITINDMIN") {
                                                    ui->listaIndicaciones->setRowCount(pos+1);
                                                    QTableWidgetItem *newItem = new QTableWidgetItem(e3.text());
                                                    // para que los elementos no sean editables
                                                    newItem->setFlags(newItem->flags() & (~Qt::ItemIsEditable));
                                                    newItem->setTextColor(Qt::blue); // color de los items

                                                    ui->listaIndicaciones->setItem(pos,0,newItem);
                                                }

                                            }

                                            pos++;

                                            //data.append(s);
                                        }
                                        n3 = n3.nextSibling();
                                    }

                            }
                            n2 = n2.nextSibling();
                        }
                    }

                }

            }
            n = n.nextSibling();
        }
コード例 #6
0
TaskQueries::TaskResult::Ptr TaskQueries::findWorkdayTopLevel() const
{
    if (!m_findWorkdayTopLevel) {
        {
            TaskQueries *self = const_cast<TaskQueries*>(this);
            self->m_findWorkdayTopLevel = self->createTaskQuery();
        }

        m_findWorkdayTopLevel->setFetchFunction([this] (const TaskQuery::AddFunction &add) {
            CollectionFetchJobInterface *job = m_storage->fetchCollections(Akonadi::Collection::root(),
                                                                           StorageInterface::Recursive,
                                                                           StorageInterface::Tasks);
            Utils::JobHandler::install(job->kjob(), [this, job, add] {
                if (job->kjob()->error() != KJob::NoError)
                    return;

                for (auto collection : job->collections()) {
                    ItemFetchJobInterface *job = m_storage->fetchItems(collection);
                    Utils::JobHandler::install(job->kjob(), [this, job, add] {
                        if (job->kjob()->error() != KJob::NoError)
                            return;

                        for (auto item : job->items()) {
                            add(item);
                        }
                    });
                }
            });
        });

        m_findWorkdayTopLevel->setConvertFunction([this] (const Akonadi::Item &item) {
            return m_serializer->createTaskFromItem(item);
        });
        m_findWorkdayTopLevel->setUpdateFunction([this] (const Akonadi::Item &item, Domain::Task::Ptr &task) {
            m_serializer->updateTaskFromItem(task, item);
        });
        m_findWorkdayTopLevel->setPredicateFunction([this] (const Akonadi::Item &item) {
            if (!m_serializer->isTaskItem(item))
                return false;

            const Domain::Task::Ptr task = m_serializer->createTaskFromItem(item);

            const QDate doneDate = task->doneDate().date();
            const QDate startDate = task->startDate().date();
            const QDate dueDate = task->dueDate().date();
            const QDate today = Utils::DateTime::currentDateTime().date();

            const bool pastStartDate = startDate.isValid() && startDate <= today;
            const bool pastDueDate = dueDate.isValid() && dueDate <= today;
            const bool todayDoneDate = doneDate == today;

            if (task->isDone())
                return todayDoneDate;
            else
                return pastStartDate || pastDueDate;

        });
        m_findWorkdayTopLevel->setRepresentsFunction([this] (const Akonadi::Item &item, const Domain::Task::Ptr &task) {
            return m_serializer->representsItem(task, item);
        });
    }

    return m_findWorkdayTopLevel->result();
}
コード例 #7
0
ファイル: mythdialogbox.cpp プロジェクト: JGunning/OpenAOL-TV
bool MythTimeInputDialog::Create()
{
    if (!CopyWindowFromBase("MythTimeInputDialog", this))
        return false;

    MythUIText *messageText = NULL;
    MythUIButton *okButton = NULL;

    bool err = false;
    UIUtilE::Assign(this, messageText, "message", &err);
    UIUtilE::Assign(this, m_dateList, "dates", &err);
    UIUtilE::Assign(this, m_timeList, "times", &err);
    UIUtilE::Assign(this, okButton, "ok", &err);

    if (err)
    {
        LOG(VB_GENERAL, LOG_ERR, "Cannot load screen 'MythTimeInputDialog'");
        return false;
    }

    m_dateList->SetVisible(false);
    m_timeList->SetVisible(false);

    MythUIButtonListItem *item;
    // Date
    if (kNoDate != (m_resolution & 0xF))
    {
        const QDate startdate(m_startTime.toLocalTime().date());
        QDate date(startdate);

        int limit = 0;
        if (m_resolution & kFutureDates)
        {
            limit += m_rangeLimit;
        }
        if (m_resolution & kPastDates)
        {
            limit += m_rangeLimit;
            date = date.addDays(0-m_rangeLimit);
        }

        QString text;
        int flags;
        bool selected = false;
        for (int x = 0; x <= limit; x++)
        {
            selected = false;
            if (m_resolution & kDay)
            {
                date = date.addDays(1);
                flags = MythDate::kDateFull | MythDate::kSimplify;
                if (m_rangeLimit >= 356)
                    flags |= MythDate::kAddYear;
                text = MythDate::toString(date, flags);

                if (date == startdate)
                    selected = true;
            }
            else if (m_resolution & kMonth)
            {
                date = date.addMonths(1);
                text = date.toString("MMM yyyy");

                if ((date.month() == startdate.month()) &&
                    (date.year() == startdate.year()))
                    selected = true;
            }
            else if (m_resolution & kYear)
            {
                date = date.addYears(1);
                text = date.toString("yyyy");
                if (date.year() == startdate.year())
                    selected = true;
            }

            item = new MythUIButtonListItem(m_dateList, text, NULL, false);
            item->SetData(QVariant(date));

            if (selected)
                m_dateList->SetItemCurrent(item);
        }
        m_dateList->SetVisible(true);
    }

    // Time
    if (kNoTime != (m_resolution & 0xF0))
    {
        QDate startdate(m_startTime.toLocalTime().date());
        QTime starttime(m_startTime.toLocalTime().time());
        QTime time(0,0,0);
        QString text;
        bool selected = false;

        int limit = (m_resolution & kMinutes) ? (60 * 24) : 24;

        for (int x = 0; x < limit; x++)
        {
            selected = false;
            if (m_resolution & kMinutes)
            {
                time = time.addSecs(60);
                QDateTime dt = QDateTime(startdate, time, Qt::LocalTime);
                text = MythDate::toString(dt, MythDate::kTime);

                if (time == starttime)
                    selected = true;
            }
            else if (m_resolution & kHours)
            {
                time = time.addSecs(60*60);
                text = time.toString("hh:00");

                if (time.hour() == starttime.hour())
                    selected = true;
            }

            item = new MythUIButtonListItem(m_timeList, text, NULL, false);
            item->SetData(QVariant(time));

            if (selected)
                m_timeList->SetItemCurrent(item);
        }
        m_timeList->SetVisible(true);
    }

    if (messageText && !m_message.isEmpty())
        messageText->SetText(m_message);

    connect(okButton, SIGNAL(Clicked()), SLOT(okClicked()));

    BuildFocusList();

    return true;
}
コード例 #8
0
QList<int> tradeDateCalendar::computeFrequencyTradeMonthly(int date_, int minimumDate_, int maximumDate_)
{
    QList<int> tradeDates;

    QDate monthDayCounter = QDate::fromJulianDay(minimumDate_);
    int dayOfMonth = QDate::fromJulianDay(date_).day();

    forever
    {
        QDate monthDayComputation = monthDayCounter;
        if (monthDayComputation.day() > dayOfMonth)
            monthDayComputation = monthDayComputation.addMonths(1);

        if (dayOfMonth > monthDayComputation.daysInMonth())
        {
            monthDayComputation = monthDayComputation.addMonths(1);
            monthDayComputation = QDate(monthDayComputation.year(), monthDayComputation.month(), 1);
        }
        else
            monthDayComputation = QDate(monthDayComputation.year(), monthDayComputation.month(), dayOfMonth);

        date_ = checkTradeDate(monthDayComputation.toJulianDay(), direction_ascending);
        if (date_ > maximumDate_)
            break;

        tradeDates.append(date_);
        monthDayCounter = monthDayCounter.addMonths(1);
    }

    return tradeDates;
}
コード例 #9
0
//! [17]
void MainWindow::setYear(QDate date)
{
    selectedDate = QDate(date.year(), selectedDate.month(), selectedDate.day());
    insertCalendar();
}
コード例 #10
0
ファイル: AdditionalMap.cpp プロジェクト: gqueiroz/terrama2
//! Change the map expiration date
void AdditionalMap::setExpirationDate(QDate date)
{
  _data.expirationYear  = date.year();
  _data.expirationMonth = date.month();
  _data.expirationDay   = date.day();
}
コード例 #11
0
ファイル: MakeDeposits.cpp プロジェクト: gottafixthat/tacc
void MakeDeposits::processSelections()
{
    if (selTotal <= 0.00) return;

    GenLedger   *GL = new GenLedger();
    int         srcAcct, dstAcct = 0;
    ADB         DB;
    QDate       selDate = transDate->date();
    char        tDate[1024];

    strcpy(tDate, selDate.toString("yyyy-MM-dd").ascii());

    // Setup the base GL transaction
    GL->BaseDesc = "Deposit";

    // Get the source and destination accounts.
    // The source will be our Undeposited Funds account.
    srcAcct = atol(cfgVal("UndepositedFundsAcct"));
    dstAcct = accountIDX[targetAccountList->currentItem()];

    // Now, setup the transaction.
    // Start by walking through each of the undeposited items and
    // then adding a split item for it.
    Q3ListViewItem   *curItem;
    //int nameCol  = 2;
    //int numCol   = 3;
    int amtCol   = 4;
    int intIDCol = 5;
    char tmpStr[1024];
    selTotal = 0.00;
    curItem = paymentList->firstChild();
    while (curItem != NULL) {
        if (curItem->isSelected()) {
            selTotal += atof(curItem->key(amtCol,0));
        }
        curItem = curItem->itemBelow();
    }
    // Add the first half of our split
    GL->AddSplit();
    GL->CurrentSplit->IntAccountNo.setNum(srcAcct);
    GL->CurrentSplit->Amount.setNum(selTotal * -1.0);
    GL->CurrentSplit->TransType.setNum(TRANSTYPE_DEPOSIT);
    GL->CurrentSplit->TransTypeLink.setNum(0);
    GL->CurrentSplit->TransDate = selDate.toString("yyyy-MM-dd");
    GL->CurrentSplit->BilledDate = selDate.toString("yyyy-MM-dd");
    GL->CurrentSplit->DueDate = selDate.toString("yyyy-MM-dd");
    GL->CurrentSplit->Cleared.setNum(0);
    GL->CurrentSplit->Number.setNum(0);
    GL->CurrentSplit->NumberStr = "";
    GL->CurrentSplit->ItemID.setNum(0);
    GL->CurrentSplit->Quantity.setNum(1);
    GL->CurrentSplit->Price.setNum(selTotal);
    sprintf(tmpStr, "Deposit of $%.2f on %s", selTotal, selDate.toString("yyyy-MM-dd").ascii());
    GL->CurrentSplit->Memo = tmpStr;

    // Now, setup the other "half" of our transaction.
    GL->AddSplit();
    GL->CurrentSplit->IntAccountNo.setNum(dstAcct);
    GL->CurrentSplit->Amount.setNum(selTotal);
    GL->CurrentSplit->TransType.setNum(TRANSTYPE_DEPOSIT);
    GL->CurrentSplit->TransTypeLink.setNum(0);
    GL->CurrentSplit->TransDate = selDate.toString("yyyy-MM-dd").ascii();
    GL->CurrentSplit->BilledDate = selDate.toString("yyyy-MM-dd").ascii();
    GL->CurrentSplit->DueDate = selDate.toString("yyyy-MM-dd").ascii();
    GL->CurrentSplit->Cleared.setNum(0);
    GL->CurrentSplit->Number.setNum(0);
    GL->CurrentSplit->NumberStr = "0";
    GL->CurrentSplit->ItemID.setNum(0);
    GL->CurrentSplit->Quantity.setNum(1);
    GL->CurrentSplit->Price.setNum(selTotal);
    sprintf(tmpStr, "Deposit of $%.2f on %s", selTotal, selDate.toString("yyyy-MM-dd").ascii());
    GL->CurrentSplit->Memo = tmpStr;

    // Finally, save the entire transaction.
    GL->SaveTrans();

    // Now, walk throught the list one more time and update the 
    // undeposited funds with the linked transaction and set them to be
    // cleared.

    curItem = paymentList->firstChild();
    while (curItem != NULL) {
        if (curItem->isSelected()) {
            DB.dbcmd("update GL set LinkedTrans = %ld, Cleared = 1 where InternalID = %ld", GL->TransID, atol(curItem->key(intIDCol, 0)));
        }
        curItem = curItem->itemBelow();
    }

    // All done, close the window.
    close();

}
コード例 #12
0
ファイル: dialoginvoicelist.cpp プロジェクト: cfdev/mcercle
/**
	Affiche les factures
	@param filter, filtre a appliquer
	@param field, champ ou appliquer le filtre
*/
void DialogInvoiceList::listInvoicesToTable(QDate mdate) {
	invoice::InvoicesBook ilist;

	//Clear les items, attention tjs utiliser la fonction clear()
	ui->tableWidget_Invoices->clear();
	for (int i=ui->tableWidget_Invoices->rowCount()-1; i >= 0; --i)
		ui->tableWidget_Invoices->removeRow(i);
	for (int i=ui->tableWidget_Invoices->columnCount()-1; i>=0; --i)
		ui->tableWidget_Invoices->removeColumn(i);

	ui->tableWidget_Invoices->setSortingEnabled(false);
	//Style de la table de facture
	ui->tableWidget_Invoices->setColumnCount( COL_COUNT );
	ui->tableWidget_Invoices->setColumnWidth( COL_DESCRIPTION, 250 );
#ifdef QT_NO_DEBUG
	ui->tableWidget_Invoices->setColumnHidden(COL_ID , true); //cache la colonne ID ou DEBUG
#endif
	ui->tableWidget_Invoices->setSelectionBehavior(QAbstractItemView::SelectRows);
	ui->tableWidget_Invoices->setSelectionMode(QAbstractItemView::SingleSelection);
	ui->tableWidget_Invoices->setEditTriggers(QAbstractItemView::NoEditTriggers);
	QStringList titles;
	titles  << tr("Id") << tr("sélection") << tr("Date") << tr("Code Facture") << tr("Client") << tr("Description")  << tr("Montant") << tr("TTC") << QLatin1String("Règlement");
	ui->tableWidget_Invoices->setHorizontalHeaderLabels( titles );
	if(!m_data->getIsTax()) {
		ui->tableWidget_Invoices->setColumnHidden(COL_PRICE_TAX , true);
	}
	//Recuperation des donnees presentent dans la bdd
	m_invoice->getInvoices(ilist, QString::number(mdate.year()), QString::number(mdate.month()));

	// list all customers
	QString typeP;
	for(int i=0; i<ilist.code.count(); i++){

		ItemOfTable *item_ID           = new ItemOfTable();
		ItemOfTable *item_State        = new ItemOfTable();
		ItemOfTable *item_DATE         = new ItemOfTable();
		ItemOfTable *item_CODE         = new ItemOfTable();
		ItemOfTable *item_CUSTOMER     = new ItemOfTable();
		ItemOfTable *item_DESCRIPTION  = new ItemOfTable();
		ItemOfTable *item_PRICE        = new ItemOfTable();
		ItemOfTable *item_PRICE_TAX    = new ItemOfTable();
		ItemOfTable *item_TYPE_PAYMENT = new ItemOfTable();
		
		item_ID->setData(Qt::DisplayRole, ilist.id.at(i));
		item_State -> setData(Qt::CheckStateRole, Qt::Checked);
		item_DATE->setData(Qt::DisplayRole, ilist.userDate.at(i)/*.toString(tr("dd/MM/yyyy"))*/);
		item_CODE->setData(Qt::DisplayRole, ilist.code.at(i));
		if(ilist.customerFirstName.at(i).isEmpty())
			item_CUSTOMER->setData(Qt::DisplayRole, ilist.customerLastName.at(i));
		else
			item_CUSTOMER->setData(Qt::DisplayRole, ilist.customerFirstName.at(i) +" "+ilist.customerLastName.at(i));

		item_DESCRIPTION->setData(Qt::DisplayRole, ilist.description.at(i));
		item_PRICE->setData(Qt::DisplayRole, ilist.price.at(i) - ilist.part_payment.at(i));
		item_PRICE_TAX->setData(Qt::DisplayRole, ilist.priceTax.at(i) - ilist.part_paymentTax.at(i));

		typeP="";
		if( ilist.typePayment.at(i) == MCERCLE::CASH)         typeP = tr("Espece");
		if( ilist.typePayment.at(i) == MCERCLE::CHECK)        typeP = tr("Cheque");
		if( ilist.typePayment.at(i) == MCERCLE::CREDIT_CARD)  typeP = tr("CB");
		if( ilist.typePayment.at(i) == MCERCLE::INTERBANK)    typeP = tr("TIP");
		if( ilist.typePayment.at(i) == MCERCLE::TRANSFER)     typeP = tr("Virement");
		if( ilist.typePayment.at(i) == MCERCLE::DEBIT)        typeP = tr("Prelevement");
		if( ilist.typePayment.at(i) == MCERCLE::OTHER)        typeP = tr("Autre");

		item_TYPE_PAYMENT->setData(Qt::DisplayRole, typeP);

		//definir le tableau
		ui->tableWidget_Invoices->setRowCount(i+1);

		//remplir les champs
		ui->tableWidget_Invoices->setItem(i, COL_ID, item_ID);
		ui->tableWidget_Invoices->setItem(i, COL_STATE, item_State);
		ui->tableWidget_Invoices->setItem(i, COL_DATE, item_DATE);
		ui->tableWidget_Invoices->setItem(i, COL_CODE, item_CODE);
		ui->tableWidget_Invoices->setItem(i, COL_CUSTOMER, item_CUSTOMER);
		ui->tableWidget_Invoices->setItem(i, COL_DESCRIPTION, item_DESCRIPTION);
		ui->tableWidget_Invoices->setItem(i, COL_PRICE, item_PRICE);
		ui->tableWidget_Invoices->setItem(i, COL_PRICE_TAX, item_PRICE_TAX);
		ui->tableWidget_Invoices->setItem(i, COL_TYPE_PAYMENT, item_TYPE_PAYMENT);
	}
	ui->tableWidget_Invoices->setSortingEnabled(true);
	ui->tableWidget_Invoices->selectRow(0);
}
コード例 #13
0
void unpostedPoReceipts::sPost()
{
  bool changeDate = false;
  QDate newDate = QDate::currentDate();

  if (_privleges->check("ChangePORecvPostDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Receipt Date"));
    if (newdlg.exec() == QDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  XSqlQuery setDate;
  setDate.prepare("UPDATE recv SET recv_gldistdate=:distdate "
		  "WHERE recv_id=:recv_id;");

  QList<QTreeWidgetItem*>selected = _recv->selectedItems();
  QList<QTreeWidgetItem*>triedToClosed;

  for (int i = 0; i < selected.size(); i++)
  {
    int id = ((XTreeWidgetItem*)(selected[i]))->id();

    if (changeDate)
    {
      setDate.bindValue(":distdate",  newDate);
      setDate.bindValue(":recv_id", id);
      setDate.exec();
      if (setDate.lastError().type() != QSqlError::None)
      {
	systemError(this, setDate.lastError().databaseText(), __FILE__, __LINE__);
      }
    }
  }
  
  XSqlQuery postLine;
  postLine.prepare("SELECT postReceipt(:id, NULL) AS result;");
  XSqlQuery rollback;
  rollback.prepare("ROLLBACK;");

  bool tryagain = false;
  do {
    for (int i = 0; i < selected.size(); i++)
    {
      int id = ((XTreeWidgetItem*)(selected[i]))->id();

      q.exec("BEGIN;");
      postLine.bindValue(":id", id);
      postLine.exec();
      if (postLine.first())
      {
	int result = postLine.value("result").toInt();
	if (result < 0)
	{
	  rollback.exec();
	  systemError(this, storedProcErrorLookup("postReceipt", result),
		      __FILE__, __LINE__);
	  continue;
	}
	q.exec("COMMIT;");

	distributeInventory::SeriesAdjust(result, this);
      }
      // contains() string is hard-coded in stored procedure
      else if (postLine.lastError().databaseText().contains("posted to closed period"))
      {
	if (changeDate)
	{
	  triedToClosed = selected;
	  break;
	}
	else
	  triedToClosed.append(selected[i]);
      }
      else if (postLine.lastError().type() != QSqlError::None)
      {
	rollback.exec();
	systemError(this, postLine.lastError().databaseText(), __FILE__, __LINE__);
      }
    } // for each selected line

    if (triedToClosed.size() > 0)
    {
      failedPostList newdlg(this, "", true);
      newdlg.sSetList(triedToClosed, _recv->headerItem(), _recv->header());
      tryagain = (newdlg.exec() == QDialog::Accepted);
      selected = triedToClosed;
      triedToClosed.clear();
    }
  } while (tryagain);

  omfgThis->sPurchaseOrderReceiptsUpdated();
}
コード例 #14
0
int CSVOldFormatConverter::getTroopId(
    QString troopName, QString graduatedFromMilitaryDepartmentDate,
    QString degreeEnrollmentNumber,
    QString graduatedFromMilitaryDepartmentInYear) {
  // TODO: refactor this stuff
  QString enteredAtMilitaryDepartmentDate;
  QString troopNamePrefix;
  QString troopNamePostfix;
  QRegExp shortPostfix = QRegExp("\\d\\d");
  QRegExp longPostfix = QRegExp("\\d\\d/\\d\\d");
  QRegExp degreeSplitter = QRegExp("№ ?\\d{1,4} ?(от)? ?");
  QDate dateEnteredAt;
  QDate dateGraduatedFrom;
  QString queryString;
  QSqlQuery query;
  QString formattedTroopName;
  int separatorPosition;
  int difference;
  troopName = troopName.toUpper().simplified();
  if (troopName == "АШ32") {
    troopName = "АШ-32";
  } else if (troopName.isEmpty()) {
    qDebug() << graduatedFromMilitaryDepartmentDate << degreeEnrollmentNumber <<
                graduatedFromMilitaryDepartmentInYear;
    return 0;
  }
  if (!graduatedFromMilitaryDepartmentDate.simplified().isEmpty()) {
    graduatedFromMilitaryDepartmentDate =
        graduatedFromMilitaryDepartmentDate.split(" ").at(0);
    dateGraduatedFrom = QDate::fromString(graduatedFromMilitaryDepartmentDate,
                                          "dd.MM.yyyy");
  } else if (!graduatedFromMilitaryDepartmentInYear.isEmpty()) {
    if (graduatedFromMilitaryDepartmentInYear != "0") {
      dateGraduatedFrom.setDate(
            graduatedFromMilitaryDepartmentInYear.toInt(), 9, 17);
    }
  }
  if (!degreeEnrollmentNumber.isEmpty()) {
    enteredAtMilitaryDepartmentDate = degreeEnrollmentNumber
        .split(degreeSplitter).last().replace("ю", ".").replace(" ", ".");
    if (enteredAtMilitaryDepartmentDate.endsWith("г.")) {
      enteredAtMilitaryDepartmentDate.chop(2);
    } else if (enteredAtMilitaryDepartmentDate.endsWith("г")) {
      enteredAtMilitaryDepartmentDate.chop(1);
    } else if (enteredAtMilitaryDepartmentDate.endsWith(".")) {
      enteredAtMilitaryDepartmentDate.chop(1);
    }
    if (enteredAtMilitaryDepartmentDate.split(".").last().length() == 2) {
      enteredAtMilitaryDepartmentDate = enteredAtMilitaryDepartmentDate.insert(
            enteredAtMilitaryDepartmentDate.length() - 2, "20");
    }
    dateEnteredAt = QDate::fromString(enteredAtMilitaryDepartmentDate,
                                      "d.MM.yyyy");
  }
  if (!dateGraduatedFrom.isValid() && !dateEnteredAt.isValid()) {
    qDebug() << "invalid dates" << dateEnteredAt << dateGraduatedFrom;
    return 0;
  } else if (dateGraduatedFrom.isValid()) {
    // guessing about entered date
    dateEnteredAt.setDate(dateGraduatedFrom.year() - 3, 6, 29);
  } else { // if (dateEnteredAt.isValid())
    dateGraduatedFrom.setDate(dateEnteredAt.year() + 3, 9, 17);
//    qDebug() << "invalid graduation date";
//    return 0;
  }
  int cyear = QDate::currentDate().year();
  if (cyear > dateGraduatedFrom.year()) {
    cyear = dateGraduatedFrom.year();
  }
  difference = cyear - dateEnteredAt.year() - 1;
  separatorPosition = troopName.indexOf('-');
  troopNamePrefix = troopName.left(separatorPosition);
  troopNamePostfix = troopName.mid(separatorPosition + 1);
  formattedTroopName = troopNamePrefix + "-";
  if (shortPostfix.exactMatch(troopNamePostfix)) {
    // TODO: make that more cleaner and optimized
    formattedTroopName +=
        "<N:" +
        QString::number(QString(troopNamePostfix.at(0)).toInt() - difference) +
        ">" + troopNamePostfix.at(1);
  } else if (longPostfix.exactMatch(troopNamePostfix)) {
    formattedTroopName +=
        "<N:" +
        QString::number(QString(troopNamePostfix.at(0)).toInt() - difference) +
        ">" + troopNamePostfix.at(1) + "/" + "<N:" +
        QString::number(QString(troopNamePostfix.at(3)).toInt() - difference) +
        ">" + troopNamePostfix.at(4);
  } else {
    qDebug() << "asshole" << troopNamePostfix << troopName;
    return 0;
  }
  troopName = formattedTroopName;
  queryString = "SELECT id FROM troop WHERE name = ? AND"
      " entered_at_military_department_date = ?";
  query.prepare(queryString);
  query.addBindValue(troopName);
  query.addBindValue(dateEnteredAt);
  if (!query.exec()) {
    qDebug() << query.lastError().text();
    return 0;
  }
  if (!query.next()) {
    queryString = "INSERT INTO troop (name,"
        " entered_at_military_department_date,"
        " graduated_from_military_department_date, military_profession_id)"
        " VALUES (?, ?, ?, ?)";
    query.prepare(queryString);
    query.addBindValue(troopName);
    query.addBindValue(dateEnteredAt);
    query.addBindValue(dateGraduatedFrom);
    query.addBindValue(1);
    if (!query.exec()) {
      qDebug() << query.lastError().text();
      return 0;
    }
    return query.lastInsertId().toInt();
  } else {
    return query.record().value("id").toInt();
  }
}
コード例 #15
0
void KOWhatsNextView::updateView()
{
    KIconLoader kil("kdepim");
    QString *ipath = new QString();
    kil.loadIcon("kdepim", KIcon::NoGroup, 32, KIcon::DefaultState, ipath);

    mText = "<table width=\"100%\">\n";
    mText += "<tr bgcolor=\"#3679AD\"><td><h1>";
    mText += "<img src=\"";
    mText += *ipath;
    mText += "\">";
    mText += "<font color=\"white\"> ";
    mText += i18n("What's Next?") + "</font></h1>";
    mText += "</td></tr>\n<tr><td>";

    mText += "<h2>";
    if(mStartDate.daysTo(mEndDate) < 1)
    {
        mText += KGlobal::locale()->formatDate(mStartDate);
    }
    else
    {
        mText += i18n("Date from - to", "%1 - %2")
                 .arg(KGlobal::locale()->formatDate(mStartDate))
                 .arg(KGlobal::locale()->formatDate(mEndDate));
    }
    mText += "</h2>\n";

    Event::List events;
    for(QDate date = mStartDate; date <= mEndDate; date = date.addDays(1))
        events += calendar()->events(date, EventSortStartDate, SortDirectionAscending);

    if(events.count() > 0)
    {
        mText += "<p></p>";
        kil.loadIcon("appointment", KIcon::NoGroup, 22, KIcon::DefaultState, ipath);
        mText += "<h2><img src=\"";
        mText += *ipath;
        mText += "\">";
        mText += i18n("Events:") + "</h2>\n";
        mText += "<table>\n";
        Event::List::ConstIterator it;
        for(it = events.begin(); it != events.end(); ++it)
        {
            Event *ev = *it;
            if(!ev->doesRecur())
            {
                appendEvent(ev);
            }
            else
            {
                // FIXME: This should actually be cleaned up. Libkcal should
                // provide a method to return a list of all recurrences in a
                // given time span.
                Recurrence *recur = ev->recurrence();
                int duration = ev->dtStart().secsTo(ev->dtEnd());
                QDateTime start = recur->getPreviousDateTime(
                                      QDateTime(mStartDate, QTime()));
                QDateTime end = start.addSecs(duration);
                if(end.date() >= mStartDate)
                {
                    appendEvent(ev, start, end);
                }
                start = recur->getNextDateTime(start);
                while(start.isValid() && start.date() <= mEndDate)
                {
                    appendEvent(ev, start);
                    start = recur->getNextDateTime(start);
                }
            }
        }
        mText += "</table>\n";
    }

    mTodos.clear();
    Todo::List todos = calendar()->todos(TodoSortDueDate, SortDirectionAscending);
    if(todos.count() > 0)
    {
        kil.loadIcon("todo", KIcon::NoGroup, 22, KIcon::DefaultState, ipath);
        mText += "<h2><img src=\"";
        mText += *ipath;
        mText += "\">";
        mText += i18n("To-do:") + "</h2>\n";
        mText += "<ul>\n";
        Todo::List::ConstIterator it;
        for(it = todos.begin(); it != todos.end(); ++it)
        {
            Todo *todo = *it;
            if(!todo->isCompleted() && todo->hasDueDate() && todo->dtDue().date() <= mEndDate)
                appendTodo(todo);
        }
        bool gotone = false;
        int priority = 1;
        while(!gotone && priority <= 9)
        {
            for(it = todos.begin(); it != todos.end(); ++it)
            {
                Todo *todo = *it;
                if(!todo->isCompleted() && (todo->priority() == priority))
                {
                    appendTodo(todo);
                    gotone = true;
                }
            }
            priority++;
            kdDebug(5850) << "adding the todos..." << endl;
        }
        mText += "</ul>\n";
    }

    QStringList myEmails(KOPrefs::instance()->allEmails());
    int replies = 0;
    events = calendar()->events(QDate::currentDate(), QDate(2975, 12, 6));
    Event::List::ConstIterator it2;
    for(it2 = events.begin(); it2 != events.end(); ++it2)
    {
        Event *ev = *it2;
        Attendee *me = ev->attendeeByMails(myEmails);
        if(me != 0)
        {
            if(me->status() == Attendee::NeedsAction && me->RSVP())
            {
                if(replies == 0)
                {
                    mText += "<p></p>";
                    kil.loadIcon("reply", KIcon::NoGroup, 22, KIcon::DefaultState, ipath);
                    mText += "<h2><img src=\"";
                    mText += *ipath;
                    mText += "\">";
                    mText += i18n("Events and to-dos that need a reply:") + "</h2>\n";
                    mText += "<table>\n";
                }
                replies++;
                appendEvent(ev);
            }
        }
    }
    todos = calendar()->todos();
    Todo::List::ConstIterator it3;
    for(it3 = todos.begin(); it3 != todos.end(); ++it3)
    {
        Todo *to = *it3;
        Attendee *me = to->attendeeByMails(myEmails);
        if(me != 0)
        {
            if(me->status() == Attendee::NeedsAction && me->RSVP())
            {
                if(replies == 0)
                {
                    mText += "<p></p>";
                    kil.loadIcon("reply", KIcon::NoGroup, 22, KIcon::DefaultState, ipath);
                    mText += "<h2><img src=\"";
                    mText += *ipath;
                    mText += "\">";
                    mText += i18n("Events and to-dos that need a reply:") + "</h2>\n";
                    mText += "<table>\n";
                }
                replies++;
                appendEvent(to);
            }
        }
        kdDebug() << "check for todo-replies..." << endl;
    }
    if(replies > 0) mText += "</table>\n";


    mText += "</td></tr>\n</table>\n";

    kdDebug(5850) << "KOWhatsNextView::updateView: text: " << mText << endl;

    delete ipath;

    mView->setText(mText);
}
コード例 #16
0
vCardProperty vCardProperty::createBirthday(const QDate& birthday, const vCardParamList& params)
{
    return vCardProperty(VC_BIRTHDAY, birthday.toString("yyyy-MM-dd"), params);
}
コード例 #17
0
/*!
  Align a date/time value for a step size

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

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

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

    QDateTime dt = dateTime;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            break;
        }
    }

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

    return dt;
}
コード例 #18
0
// Converts a date/time value into msecs
static inline qint64 timeToMSecs(const QDate &date, const QTime &time)
{
    return ((date.toJulianDay() - JULIAN_DAY_FOR_EPOCH) * MSECS_PER_DAY)
           + time.msecsSinceStartOfDay();
}
コード例 #19
0
ファイル: wallclock.cpp プロジェクト: Linux-enCaja/SIE
void WallClock::paintEvent(QPaintEvent *)
{
    static const int hourHand[8] = { -2, 18, 2, 18, 2, -60, -2, -60 };
    static const int minuteHand[8] = { -2, 28, 2, 28, 2, -80, -2, -80 };
    static const int secondHand[12] = {-1, 0, -1, -90, 1,-90, 1, 0, 4, 35, -4, 35};

    // odmalowywuje t³o
    drawBackground();
      // inicjalizacja paintera

    QPainter painter(this);
    initCoordinateSystem(painter);

    // Wyliczanie czasu i daty
    QTime time = m_dateTime.time(); 
    QDate date = m_dateTime.date(); 
    QString Str;
    QSize Size;

    if (timeOffset()!=0.0)
    {
      // Rysowanie tekstów - godziny
      painter.setFont(timeFont());
      painter.setPen(timeColor());
      Str = time.toString("hh:mm");
      Size = painter.fontMetrics().size(Qt::TextSingleLine, Str );
      painter.drawText( QPointF (Size.width() / -2.0, Size.height()+ timeOffset()) ,Str);
    }

    if (dateOffset()!=0.0)
    {
      // Rysowanie daty
      painter.setFont(dateFont());
      painter.setPen(dateColor());
      Str = date.toString("dd.MM.yyyy");
      Size = painter.fontMetrics().size(Qt::TextSingleLine, Str);
      painter.drawText( QPointF(Size.width() / -2.0,static_cast<int>(0 - dateOffset())), Str);
    }
    if (dayOffset()!=0.0)
    {
      // Dzieñ tygodnia
      painter.setFont(dayFont());
      painter.setPen(dayColor());
      Str =  date.toString("dddd");
      Size = painter.fontMetrics().size(Qt::TextSingleLine, Str);
      painter.drawText( QPointF (Size.width() / -2.0,static_cast<int>( 0 - dayOffset())) , Str);
    }

    // rysowanie wskazówki godzin
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::black);
    painter.save();
    painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0)));
    painter.drawConvexPolygon(QPolygon(4, hourHand));
    painter.restore();

    // rysowanie minutnika
    painter.setBrush(Qt::black);
    painter.save();
    painter.rotate(6.0 * (time.minute() + time.second() / 60.0));
    painter.drawConvexPolygon(QPolygon(4, minuteHand));
    painter.restore();

    // Malowanie wskazówki sekundnika
    painter.setPen(Qt::NoPen);
    painter.setBrush(Qt::red);
    painter.save();
    painter.rotate(6.0 * ( time.second())); //  + time.msec() / 1000.0) );
    painter.drawConvexPolygon(QPolygon(6, secondHand));
    painter.restore();
    // Kó³ko sekundnika
    painter.drawEllipse(-5,-5,10,10);
}// paintEvent 
コード例 #20
0
int main( int argc, char ** argv )
{
  KLocale::setMainCatalogue("kdelibs");
  KApplication a( argc, argv, "klocaletest" );

  KGlobal::locale()->setLanguage(QString::fromLatin1("en_US"));
  KGlobal::locale()->setCountry(QString::fromLatin1("C"));
  KGlobal::locale()->setThousandsSeparator(QString::fromLatin1(","));

  QString formatted;
  formatted = KGlobal::locale()->formatNumber( 70 ); check("formatNumber(70)",formatted,"70.00");
  formatted = KGlobal::locale()->formatNumber( 70, 0 ); check("formatNumber(70, 0)",formatted,"70");
  formatted = KGlobal::locale()->formatNumber( 70.2 ); check("formatNumber(70.2)",formatted,"70.20");
  formatted = KGlobal::locale()->formatNumber( 70.24 ); check("formatNumber(70.24)",formatted,"70.24");
  formatted = KGlobal::locale()->formatNumber( 70.245 ); check("formatNumber(70.245)",formatted,"70.25"); /*rounded*/
  formatted = KGlobal::locale()->formatNumber(1234567.89123456789,8); check("formatNumber(1234567.89123456789,8)",formatted,"1,234,567.89123457");

  formatted = KGlobal::locale()->formatNumber("70"); check("formatNumber(\"70\")",formatted,"70.00");
  formatted = KGlobal::locale()->formatNumber("70", true, 2); check("formatNumber(\"70\", true, 2)",formatted,"70.00");
  formatted = KGlobal::locale()->formatNumber("70", true, 0); check("formatNumber(\"70\", true, 0)",formatted,"70");
  formatted = KGlobal::locale()->formatNumber("70.9123", true, 0); check("formatNumber(\"70.9123\", true, 0)",formatted,"71"); /* rounded */
  formatted = KGlobal::locale()->formatNumber("-70.2", true, 2); check("formatNumber(\"-70.2\", true, 2)",formatted,"-70.20");
  formatted = KGlobal::locale()->formatNumber("+70.24", true, 2); check("formatNumber(\"+70.24\", true, 2)",formatted,"70.24");
  formatted = KGlobal::locale()->formatNumber("70.245", true, 2); check("formatNumber(\"70.245\", true, 2)",formatted,"70.25"); /*rounded*/
  formatted = KGlobal::locale()->formatNumber("99.996", true, 2); check("formatNumber(\"99.996\", true, 2)",formatted,"100.00"); /*rounded*/
  formatted = KGlobal::locale()->formatNumber("12345678901234567.89123456789", false, 0); check("formatNumber(\"12345678901234567.89123456789\", false, 0)",formatted,"12,345,678,901,234,567.89123456789");



  double num;
  bool ok;
  num = KGlobal::locale()->readNumber( "12,1", &ok ); check("readNumber(12,1)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,100", &ok ); check("readNumber(12,100)",ok?"yes":"no","yes");
  num = KGlobal::locale()->readNumber( "12,100000,000", &ok ); check("readNumber(12,100000,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,100000000", &ok ); check("readNumber(12,100000000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,100000,000", &ok ); check("readNumber(12,100000,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,,100,000", &ok ); check("readNumber(12,,100,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,1000,000", &ok ); check("readNumber(12,1000,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,0000000,000", &ok ); check("readNumber(12,0000000,000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,0000000", &ok ); check("readNumber(12,0000000)",ok?"yes":"no","no");
  num = KGlobal::locale()->readNumber( "12,146,131.12", &ok ); check("readNumber(12,146,131.12)",ok?"yes":"no","yes");
  num = KGlobal::locale()->readNumber( "1.12345678912", &ok );
        qDebug( "%s", QString::number( num, 'g', 12 ).latin1() ); // warning this is the only way to see all decimals
        check("readNumber(1.12345678912)",ok && num==1.12345678912?"yes":"no","yes");
  // bug 95511
  KLocale locale(*KGlobal::locale());
  locale.setCurrencySymbol("$$");
  num = locale.readMoney("1,234,567.89$$", &ok);
  check("readMoney(1,234,567.89$$)",ok?"yes":"no","yes");
  num = locale.readMoney("-1,234,567.89$$", &ok);
  check("readMoney(-1,234,567.89$$)",ok?"yes":"no","yes");

  QDate date;
  date.setYMD( 2002, 5, 3 );
  checkDate("readDate( 3, 5, 2002 )",date,KGlobal::locale()->readDate( KGlobal::locale()->formatDate( date ) ) );
  date = QDate::currentDate();
  checkDate("readDate( QDate::currentDate() )",date,KGlobal::locale()->readDate( KGlobal::locale()->formatDate( date ) ) );

  QTime time;
  time = KGlobal::locale()->readTime( "11:22:33", &ok );
  check("readTime(\"11:22:33\")", (ok && time == QTime(11, 22, 33)) ?
        "yes" : "no", "yes");
  time = KGlobal::locale()->readTime( "11:22", &ok );
  check("readTime(\"11:22\")", (ok && time == QTime(11, 22, 0)) ?
        "yes" : "no", "yes");
  time = KGlobal::locale()->readTime( "foo", &ok );
  check("readTime(\"foo\")", (!ok && !time.isValid()) ?
        "invalid" : "valid", "invalid");

  time = KGlobal::locale()->readTime( "11:22:33", KLocale::WithoutSeconds, &ok );
  check("readTime(\"11:22:33\", WithoutSeconds)", (!ok && !time.isValid()) ?
        "invalid" : "valid", "invalid");
  time = KGlobal::locale()->readTime( "11:22", KLocale::WithoutSeconds, &ok );
  check("readTime(\"11:22\", WithoutSeconds)", (ok && time == QTime(11, 22, 0)) ?
        "yes" : "no", "yes");

  KGlobal::locale()->setTimeFormat( "%H:%M %p" );
  time = QTime( 0, 22, 33 );
  QString timeStr = KGlobal::locale()->formatTime( time, true /*seconds*/, false /*duration*/ );
  check("formatTime(\"0:22\", as time)", timeStr, "00:22 am" );
  timeStr = KGlobal::locale()->formatTime( time, true /*seconds*/, true /*duration*/ );
  check("formatTime(\"0:22\", as duration)", timeStr, "00:22" );

  kdDebug() << "setLanguage C\n";
  KGlobal::locale()->setLanguage(QString::fromLatin1("C"));
  kdDebug() << "C: " << i18n("yes") << " " << i18n("QAccel", "Space") << endl;

  kdDebug() << "setLanguage de\n";
  KGlobal::locale()->setLanguage(QString::fromLatin1("de"));
  kdDebug() << "de: " << i18n("yes") << " " << i18n("QAccel", "Space") << endl;


  Test m;
  a.setMainWidget( &m );
  m.show();

  return a.exec();
}
コード例 #21
0
void RollingFileAppender::computeRollOverTime()
{
  Q_ASSERT_X(!m_datePatternString.isEmpty(), "DailyRollingFileAppender::computeRollOverTime()", "No active date pattern");

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

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

  m_rollOverSuffix = start.toString(m_datePatternString);
  Q_ASSERT_X(now.toString(m_datePatternString) == m_rollOverSuffix,
      "DailyRollingFileAppender::computeRollOverTime()", "File name changes within interval");
  Q_ASSERT_X(m_rollOverSuffix != m_rollOverTime.toString(m_datePatternString),
      "DailyRollingFileAppender::computeRollOverTime()", "File name does not change with rollover");
}
コード例 #22
0
void openVouchers::sPost()
{
  bool changeDate = false;
  QDate newDate = QDate::currentDate();

  if (_privileges->check("ChangeVOPostDate"))
  {
    getGLDistDate newdlg(this, "", TRUE);
    newdlg.sSetDefaultLit(tr("Distribution Date"));
    if (newdlg.exec() == XDialog::Accepted)
    {
      newDate = newdlg.date();
      changeDate = (newDate.isValid());
    }
    else
      return;
  }

  XSqlQuery setDate;
  setDate.prepare("UPDATE vohead SET vohead_gldistdate=:distdate "
		  "WHERE vohead_id=:vohead_id;");

  QList<QTreeWidgetItem*>selected = _vohead->selectedItems();
  QList<QTreeWidgetItem*>triedToClosed;

  for (int i = 0; i < selected.size(); i++)
  {
    int id = ((XTreeWidgetItem*)(selected[i]))->id();

    if (changeDate)
    {
      setDate.bindValue(":distdate",  newDate);
      setDate.bindValue(":vohead_id", id);
      setDate.exec();
      if (setDate.lastError().type() != QSqlError::None)
      {
	systemError(this, setDate.lastError().databaseText(), __FILE__, __LINE__);
      }
    }
  }
  
  XSqlQuery post;
  post.prepare("SELECT fetchJournalNumber('AP-VO') AS result;");
  post.exec();
  int journalNumber = 0;
  if(post.first())
    journalNumber = post.value("result").toInt();
  else
  {
    systemError(this, post.lastError().databaseText(), __FILE__, __LINE__);
    return;
  }

  post.prepare("SELECT postVoucher(:vohead_id, :journalNumber, FALSE) AS result;");

  bool tryagain = false;
  do {
    for (int i = 0; i < selected.size(); i++)
    {
      int id = ((XTreeWidgetItem*)(selected[i]))->id();

      post.bindValue(":vohead_id", id);
      post.bindValue(":journalNumber", journalNumber);
      post.exec();
      if (post.first())
      {
	int result = post.value("result").toInt();
	if (result < 0)
	  systemError(this, storedProcErrorLookup("postVoucher", result),
		      __FILE__, __LINE__);
      }
      // contains() string is hard-coded in stored procedure
      else if (post.lastError().databaseText().contains("posted to closed period"))
      {
	if (changeDate)
	{
	  triedToClosed = selected;
	  break;
	}
	else
	  triedToClosed.append(selected[i]);
      }
      else if (post.lastError().type() != QSqlError::None)
      {
	systemError(this, post.lastError().databaseText(), __FILE__, __LINE__);
      }
    }

    if (triedToClosed.size() > 0)
    {
      failedPostList newdlg(this, "", true);
      newdlg.sSetList(triedToClosed, _vohead->headerItem(), _vohead->header());
      tryagain = (newdlg.exec() == XDialog::Accepted);
      selected = triedToClosed;
      triedToClosed.clear();
    }
  } while (tryagain);

  if (_printJournal->isChecked())
  {
    ParameterList params;
    params.append("journalNumber", journalNumber);

    orReport report("PayablesJournal", params);
    if (report.isValid())
      report.print();
    else
      report.reportError(this);
  }

  omfgThis->sVouchersUpdated();
}
コード例 #23
0
ファイル: Zones.cpp プロジェクト: gregf83/GoldenCheetah
QString Zones::getEndDateString(int rnum) const
{
    assert(rnum >= 0);
    QDate d = ranges[rnum].end;
    return (d.isNull() ? "END" : d.toString());
}
コード例 #24
0
ファイル: Season.cpp プロジェクト: perrygeo/GoldenCheetah
//
// Manage the seasons array
//
void
Seasons::readSeasons()
{
    QFile seasonFile(home.absolutePath() + "/seasons.xml");
    QXmlInputSource source( &seasonFile );
    QXmlSimpleReader xmlReader;
    SeasonParser handler;
    xmlReader.setContentHandler(&handler);
    xmlReader.setErrorHandler(&handler);
    xmlReader.parse( source );
    seasons = handler.getSeasons();

    Season season;
    QDate today = QDate::currentDate();
    QDate eom = QDate(today.year(), today.month(), today.daysInMonth());

    // add Default Date Ranges
    season.setName(tr("All Dates"));
    season.setType(Season::temporary);
    season.setStart(QDate::currentDate().addYears(-50));
    season.setEnd(QDate::currentDate().addYears(50));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000001}"));
    seasons.append(season);

    season.setName(tr("This Year"));
    season.setType(Season::temporary);
    season.setStart(QDate(today.year(), 1,1));
    season.setEnd(QDate(today.year(), 12, 31));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000002}"));
    seasons.append(season);

    season.setName(tr("This Month"));
    season.setType(Season::temporary);
    season.setStart(QDate(today.year(), today.month(),1));
    season.setEnd(eom);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000003}"));
    seasons.append(season);

    season.setName(tr("This Week"));
    season.setType(Season::temporary);
    // from Mon-Sun
    QDate wstart = QDate::currentDate();
    wstart = wstart.addDays(Qt::Monday - wstart.dayOfWeek());
    QDate wend = wstart.addDays(6); // first day + 6 more
    season.setStart(wstart);
    season.setEnd(wend);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000004}"));
    seasons.append(season);

    season.setName(tr("Last 7 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-6)); // today plus previous 6
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000005}"));
    seasons.append(season);

    season.setName(tr("Last 14 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-13));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000006}"));
    seasons.append(season);

    season.setName(tr("Last 21 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-20));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000011}"));
    seasons.append(season);

    season.setName(tr("Last 28 days"));
    season.setType(Season::temporary);
    season.setStart(today.addDays(-27));
    season.setEnd(today);
    season.setId(QUuid("{00000000-0000-0000-0000-000000000007}"));
    seasons.append(season);

    season.setName(tr("Last 2 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-2));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000008}"));
    seasons.append(season);

    season.setName(tr("Last 3 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-3));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000012}"));
    seasons.append(season);

    season.setName(tr("Last 6 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-6));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000009}"));
    seasons.append(season);

    season.setName(tr("Last 12 months"));
    season.setType(Season::temporary);
    season.setEnd(today);
    season.setStart(today.addMonths(-12));
    season.setId(QUuid("{00000000-0000-0000-0000-000000000010}"));
    seasons.append(season);

    seasonsChanged(); // signal!
}
コード例 #25
0
int main(int argc, char *argv[])
{
#ifdef Q_OS_MAC
	// QTBUG-32789 - GUI widgets use the wrong font on OS X Mavericks
	QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande");
#endif

	SingleApplication theApp( argc, argv );

	if(!theApp.shouldContinue())return 0;

	QStringList args = theApp.arguments();

	QUrl proxy;
	int index = args.indexOf("-proxy");
	if ( index != -1 )
		proxy = QUrl( args.value(index + 1) );
	else
		proxy = QUrl( qgetenv( "http_proxy" ) );
	if ( !proxy.isEmpty() )
		setApplicationProxy( proxy );

	QByteArray encoding;
	index = args.indexOf( "-encoding" );
	if ( index != -1 )
		encoding = args.value( index + 1 ).toLocal8Bit();
	else if ( !qgetenv( "COMMUNI_ENCODING" ).isEmpty())
		encoding = qgetenv( "COMMUNI_ENCODING" );
	if ( !encoding.isEmpty() )
		SingleApplication::setEncoding( encoding );


// To enable this, run qmake with "DEFINES+=_SNAPSHOT_BUILD"
#ifdef _SNAPSHOT_BUILD
	QDate oExpire = QDate::fromString( Version::BUILD_DATE, Qt::ISODate ).addDays( 60 );

	if( QDate::currentDate() > oExpire )
	{
		QMessageBox::information( NULL,
								  QObject::tr( "Cool Software, but..." ),
								  QObject::tr( "This build is expired. If you wish to continue using this "
											   "Cool Software you must download either latest stable releas"
											   "e or latest snapshot build from http://quazaa.sf.net/.\n\n"
											   "The program will now terminate." ) );
		return 0;
	}

	if( !args.contains("--no-alpha-warning") )
	{
		int ret = QMessageBox::warning( NULL,
										QObject::tr("Snapshot/Debug Build Warning"),
										QObject::tr("WARNING: This is a SNAPSHOT BUILD of Quazaa. \n"
													"It is NOT meant for GENERAL USE, and is only for testi"
													"ng specific features in a controlled environment.\n"
													"It will frequently stop running, or will display debug"
													"information to assist testing.\n"
													"This build will expire on %1.\n\n"
													"Do you wish to continue?"
													).arg( oExpire.toString( Qt::SystemLocaleLongDate ) ),
									   QMessageBox::Yes | QMessageBox::No );
		if( ret == QMessageBox::No )
			return 0;
	}
#endif

	qsrand( time( 0 ) );

#ifdef Q_OS_LINUX

	rlimit sLimit;
	memset( &sLimit, 0, sizeof( rlimit ) );
	getrlimit( RLIMIT_NOFILE, &sLimit );

	sLimit.rlim_cur = sLimit.rlim_max;

	if( setrlimit( RLIMIT_NOFILE, &sLimit ) == 0 )
	{
		qDebug() << "Successfully raised resource limits";
	}
	else
	{
		qDebug() << "Cannot set resource limits";
	}

#endif // Q_OS_LINUX

	theApp.setApplicationName(    CQuazaaGlobals::APPLICATION_NAME() );
	theApp.setApplicationVersion( CQuazaaGlobals::APPLICATION_VERSION_STRING() );
	theApp.setOrganizationDomain( CQuazaaGlobals::APPLICATION_ORGANIZATION_DOMAIN() );
	theApp.setOrganizationName(   CQuazaaGlobals::APPLICATION_ORGANIZATION_NAME() );
	theApp.setApplicationSlogan( QObject::tr("World class file sharing.") );

	QIcon icon;
	icon.addFile( ":/Resource/Quazaa16.png" );
	icon.addFile( ":/Resource/Quazaa24.png" );
	icon.addFile( ":/Resource/Quazaa32.png" );
	icon.addFile( ":/Resource/Quazaa48.png" );
	icon.addFile( ":/Resource/Quazaa64.png" );
	icon.addFile( ":/Resource/Quazaa128.png" );
	qApp->setWindowIcon( icon );

	// Initialize system log component translations
	systemLog.start();

	// Setup Qt elements of signal queue necessary for operation
	signalQueue.setup();

	//Initialize multilanguage support
	quazaaSettings.loadLanguageSettings();
	quazaaSettings.translator.load( quazaaSettings.Language.File );
	qApp->installTranslator( &quazaaSettings.translator );

	// If the MainWindow object is not created and shown before any other dialogs,
	// the media player will break input event processing
	MainWindow = new CWinMain();
	MainWindow->show();
	MainWindow->hide();

	//Create splash window
	CDialogSplash* dlgSplash = new CDialogSplash();
	dlgSplash->show();
	qApp->processEvents();

	dlgSplash->updateProgress( 1, QObject::tr( "Loading settings..." ) );
	qApp->processEvents();

	//Initialize Settings
	quazaaSettings.loadSettings();

	//Check if this is Quazaa's first run
	dlgSplash->updateProgress( 8, QObject::tr( "Checking for first run..." ) );
	qApp->processEvents();
	bool bFirstRun = quazaaSettings.isFirstRun();
	if ( bFirstRun )
	{
		CDialogLanguage* dlgLanguage = new CDialogLanguage();
		dlgLanguage->exec();

		dlgSplash->updateProgress( 10, QObject::tr( "Running Quick Start wizard..." ) );
		quazaaSettings.saveFirstRun( false );
		quazaaSettings.saveSettings();
		quazaaSettings.saveProfile();

		CWizardQuickStart* wzrdQuickStart = new CWizardQuickStart();
		wzrdQuickStart->exec();
	}

	// Load Security Manager
	dlgSplash->updateProgress( 15, QObject::tr( "Loading Security Manager..." ) );
	qApp->processEvents();
	if ( !securityManager.start() )
		systemLog.postLog( LogSeverity::Information,
						   QObject::tr( "Security data file was not available." ) );

	// Load Discovery Services Manager
	dlgSplash->updateProgress( 22, QObject::tr( "Loading Discovery Services Manager..." ) );
	qApp->processEvents();
	discoveryManager.start();

	//Load profile
	dlgSplash->updateProgress( 25, QObject::tr( "Loading Profile..." ) );
	qApp->processEvents();
	quazaaSettings.loadProfile();

	//Load Host Cache
	dlgSplash->updateProgress( 30, QObject::tr( "Loading Host Cache..." ) );
	qApp->processEvents();
	hostCache.m_pSection.lock();
	hostCache.load();
	hostCache.m_pSection.unlock();

	//initialize geoip list
	geoIP.loadGeoIP();

	//Load the library
	dlgSplash->updateProgress( 38, QObject::tr( "Loading Library..." ) );
	qApp->processEvents();
	QueryHashMaster.create();
	ShareManager.start();

	// Load Download Manager
	dlgSplash->updateProgress( 60, QObject::tr( "Loading Transfer Manager..." ) );
	qApp->processEvents();
	Transfers.start();

	dlgSplash->updateProgress( 80, QObject::tr( "Loading User Interface..." ) );
	qApp->processEvents();

	if ( quazaaSettings.WinMain.Visible )
	{
		if(bFirstRun)
			MainWindow->showMaximized();
		else
			MainWindow->show();
	}

	dlgSplash->updateProgress( 90, QObject::tr( "Loading Tray Icon..." ) );
	qApp->processEvents();
	MainWindow->loadTrayIcon();

	dlgSplash->updateProgress( 100, QObject::tr( "Welcome to Quazaa!" ) );
	qApp->processEvents();

	dlgSplash->deleteLater();
	dlgSplash = 0;

	// Start networks if needed
	if ( quazaaSettings.System.ConnectOnStartup )
	{
		if ( quazaaSettings.Gnutella2.Enable )
		{
			Network.start();
		}
	}

	return theApp.exec();
}
コード例 #26
0
ファイル: besttimesimpl.cpp プロジェクト: audetto/poolviewer
void BestTimesImpl::on_calculateButton_clicked()
{
    enum period
    {
        ALL = 0,
        THISMONTH,
        THISYEAR,
        LASTMONTH,
        LASTYEAR
    };

    timesTable->clearContents();
    timesTable->setRowCount(0);

    // otherwise the rows move around while they are added
    // and we set the item in the wrong place
    timesTable->setSortingEnabled(false);

    int id = periodBox->currentIndex();

    const QString distStr = distanceBox->currentText();
    bool ok = false;
    const uint distance = distStr.toUInt(&ok);
    if (!ok || distance == 0)
    {
        return;
    }

    double bestSpeed = std::numeric_limits<double>::max();

    const std::vector<Workout>& workouts = ds->Workouts();

    for (size_t i = 0; i < workouts.size(); ++i)
    {
        const Workout & w = workouts[i];

        switch(id)
        {
        case ALL:
            break;

        case THISMONTH:
        {
            QDate now = QDate::currentDate();
            if (w.date.month() != now.month() ||
                    w.date.year() != now.year())
                continue;
            break;
        }

        case THISYEAR:
        {
            QDate now = QDate::currentDate();
            if (w.date.year() != now.year())
                continue;
            break;
        }

        case LASTMONTH:
        {
            QDate then = QDate::currentDate().addMonths(-1);
            if (w.date.month() != then.month() ||
                    w.date.year() != then.year())
                continue;
            break;
        }

        case LASTYEAR:
        {
            QDate then = QDate::currentDate().addYears(-1);
            if (w.date.year() != then.year())
                continue;
            break;
        }
        }

        if (w.type != "Swim" && w.type != "SwimHR")
        {
            continue;
        }

        const int pool = w.pool;

        if (pool <= 0)
        {
            continue;
        }

        // this is the number of lanes to get above or equal the desired distance
        const int numberOfLanes = (distance + pool - 1) / pool; // round up

        for (size_t j = 0; j < w.sets.size(); ++j)
        {
            const Set & set = w.sets[j];
            if (set.lens < numberOfLanes)
            {
                // not enough in this set
                continue;
            }

            addSet(set, w, numberOfLanes, bestSpeed, timesTable);
        }
    }

    // ensure the state of the "record progression" is correct
    on_progressionBox_clicked();
    timesTable->resizeColumnsToContents();
    timesTable->setSortingEnabled(true);
}
コード例 #27
0
ファイル: kendingbalancedlg.cpp プロジェクト: KDE/kmymoney
KEndingBalanceDlg::KEndingBalanceDlg(const MyMoneyAccount& account, QWidget *parent) :
    KEndingBalanceDlgDecl(parent),
    d(new Private(Page_InterestChargeCheckings + 1))
{
  setModal(true);
  QString value;
  MyMoneyMoney endBalance, startBalance;

  d->m_account = account;

  MyMoneySecurity currency = MyMoneyFile::instance()->security(account.currencyId());
  //FIXME: port
  m_statementInfoPageCheckings->m_enterInformationLabel->setText(QString("<qt>") + i18n("Please enter the following fields with the information as you find them on your statement. Make sure to enter all values in <b>%1</b>.", currency.name()) + QString("</qt>"));

  // If the previous reconciliation was postponed,
  // we show a different first page
  value = account.value("lastReconciledBalance");
  if (value.isEmpty()) {
    // if the last statement has been entered long enough ago (more than one month),
    // then take the last statement date and add one month and use that as statement
    // date.
    QDate lastStatementDate = account.lastReconciliationDate();
    if (lastStatementDate.addMonths(1) < QDate::currentDate()) {
      setField("statementDate", lastStatementDate.addMonths(1));
    }

    slotUpdateBalances();

    d->m_pages.clearBit(Page_PreviousPostpone);
  } else {
    d->m_pages.clearBit(Page_CheckingStart);
    d->m_pages.clearBit(Page_InterestChargeCheckings);
    //removePage(m_interestChargeCheckings);
    // make sure, we show the correct start page
    setStartId(Page_PreviousPostpone);

    MyMoneyMoney factor(1, 1);
    if (d->m_account.accountGroup() == MyMoneyAccount::Liability)
      factor = -factor;

    startBalance = MyMoneyMoney(value) * factor;
    value = account.value("statementBalance");
    endBalance = MyMoneyMoney(value) * factor;

    //FIXME: port
    m_statementInfoPageCheckings->m_previousBalance->setValue(startBalance);
    m_statementInfoPageCheckings->m_endingBalance->setValue(endBalance);
  }

  // We don't need to add the default into the list (see ::help() why)
  // m_helpAnchor[m_startPageCheckings] = QString("");
  d->m_helpAnchor[m_interestChargeCheckings] = QString("details.reconcile.wizard.interest");
  d->m_helpAnchor[m_statementInfoPageCheckings] = QString("details.reconcile.wizard.statement");

  value = account.value("statementDate");
  if (!value.isEmpty())
    setField("statementDate", QDate::fromString(value, Qt::ISODate));

  //FIXME: port
  m_statementInfoPageCheckings->m_lastStatementDate->setText(QString());
  if (account.lastReconciliationDate().isValid()) {
    m_statementInfoPageCheckings->m_lastStatementDate->setText(i18n("Last reconciled statement: %1", QLocale().toString(account.lastReconciliationDate())));
  }

  // connect the signals with the slots
  connect(MyMoneyFile::instance(), SIGNAL(dataChanged()), this, SLOT(slotReloadEditWidgets()));
  connect(m_statementInfoPageCheckings->m_statementDate, SIGNAL(dateChanged(QDate)), this, SLOT(slotUpdateBalances()));
  connect(m_interestChargeCheckings->m_interestCategoryEdit, SIGNAL(createItem(QString,QString&)), this, SLOT(slotCreateInterestCategory(QString,QString&)));
  connect(m_interestChargeCheckings->m_chargesCategoryEdit, SIGNAL(createItem(QString,QString&)), this, SLOT(slotCreateChargesCategory(QString,QString&)));
  connect(m_interestChargeCheckings->m_payeeEdit, SIGNAL(createItem(QString,QString&)), this, SIGNAL(createPayee(QString,QString&)));

  KMyMoneyMVCCombo::setSubstringSearchForChildren(m_interestChargeCheckings, !KMyMoneySettings::stringMatchFromStart());

  slotReloadEditWidgets();

  // preset payee if possible
  try {
    // if we find a payee with the same name as the institution,
    // than this is what we use as payee.
    if (!d->m_account.institutionId().isEmpty()) {
      MyMoneyInstitution inst = MyMoneyFile::instance()->institution(d->m_account.institutionId());
      MyMoneyPayee payee = MyMoneyFile::instance()->payeeByName(inst.name());
      setField("payeeEdit", payee.id());
    }
  } catch (const MyMoneyException &) {
  }

  KMyMoneyUtils::updateWizardButtons(this);

  // setup different text and icon on finish button
  setButtonText(QWizard::FinishButton, KStandardGuiItem::cont().text());
  button(QWizard::FinishButton)->setIcon(KStandardGuiItem::cont().icon());
}
コード例 #28
0
ファイル: AssetCache.cpp プロジェクト: 360degrees-fi/tundra
bool AssetCache::SetLastModified(const QString &assetRef, const QDateTime &dateTime)
{
    if (!dateTime.isValid())
    {
        LogError("AssetCache::SetLastModified() DateTime is invalid: " + assetRef);
        return false;
    }

    QString absolutePath = FindInCache(assetRef);
    if (absolutePath.isEmpty())
        return false;

    QDate date = dateTime.date();
    QTime time = dateTime.time();

#ifdef Q_WS_WIN
    HANDLE fileHandle = (HANDLE)OpenFileHandle(absolutePath);
    if (fileHandle == INVALID_HANDLE_VALUE)
    {
        LogError("AssetCache: Failed to open cache file to update last modified time: " + assetRef);
        return false;
    }

    // Notes: For SYSTEMTIME Sunday is 0 and ignore msec.
    SYSTEMTIME sysTime;
    sysTime.wDay = (WORD)date.day();
    sysTime.wDayOfWeek = (WORD)date.dayOfWeek();
    if (sysTime.wDayOfWeek == 7)
        sysTime.wDayOfWeek = 0;
    sysTime.wMonth = (WORD)date.month();
    sysTime.wYear = (WORD)date.year();
    sysTime.wHour = (WORD)time.hour();
    sysTime.wMinute = (WORD)time.minute();
    sysTime.wSecond = (WORD)time.second();
    sysTime.wMilliseconds = 0; 

    // Set last write time
    FILETIME fileTime;
    BOOL success = SystemTimeToFileTime(&sysTime, &fileTime);
    if (success)
        success = SetFileTime(fileHandle, 0, 0, &fileTime);
    CloseHandle(fileHandle);
    if (!success)
    {
        LogError("AssetCache: Failed to update cache file last modified time: " + assetRef);
        return false;
    }
    return true;
#else
    QString nativePath = QDir::toNativeSeparators(absolutePath);
    utimbuf modTime;
    modTime.actime = (time_t)(dateTime.toMSecsSinceEpoch() / 1000);
    modTime.modtime = (time_t)(dateTime.toMSecsSinceEpoch() / 1000);
    if (utime(nativePath.toStdString().c_str(), &modTime) == -1)
    {
        LogError("AssetCache: Failed to read cache file last modified time: " + assetRef);
        return false;
    }
    else
        return true;
#endif
}
コード例 #29
0
void ClinicChargeStatisticForm::updateTable()
{
    initTable();
    QDate startDate = m_startDateEdit->date();
    QDate endDate = m_endDateEdit->date();

    if(startDate > endDate)
        return;

    QString strName = m_nameEdit->text();
    Gender eGender = (Gender)m_genderComboBox->currentIndex();
    if(myDB::connectDB())
    {
        QSqlTableModel *model = new QSqlTableModel;
        model->setTable(strClinicCharge);
        QString strSql = "" , strTemp = "";

        strTemp = "Gender = " + QString::number((int)eGender);
        strSql += strTemp;

        if(!strName.isEmpty())
        {
            strTemp = " and Name = \'" + strName + "\'";
            strSql += strTemp;
        }

        QString strStartTime = startDate.toString("yyyy-MM-dd") + "T00:00:00";
        QString strEndTime = endDate.toString("yyyy-MM-dd") + "T23:59:59";

        strTemp = " and Time between \'" + strStartTime + "\' and \'" + strEndTime + "\'";
        strSql += strTemp;

        model->setFilter(strSql);
        model->select();

        int index = 0;
        for(int i = 0; i < model->rowCount();i++)
        {
            QSqlRecord record = model->record(i);
            QString strID = record.value("ID").toString();
            QSqlTableModel *mymodel = new QSqlTableModel;
            mymodel->setTable(strClinicChargeDetails);
            mymodel->setFilter("ChargeId = \'" + strID + "\'");
            mymodel->select();
            for(int j = 0; j < mymodel->rowCount(); j++)
            {
                m_resultsModel->setItem(index,0,new QStandardItem(strID));

                m_resultsModel->setItem(index,1,new QStandardItem(record.value("Name").toString()));
                m_resultsModel->setItem(index,2,new QStandardItem(record.value("Department").toString()));
                m_resultsModel->setItem(index,3,new QStandardItem(record.value("Doctor").toString()));
                QSqlRecord record1 = mymodel->record(j);
                m_resultsModel->setItem(index,4,new QStandardItem(record1.value("ChargeItemName").toString()));
                m_resultsModel->setItem(index,5,new QStandardItem(record1.value("ChargeItemCount").toString()));
                m_resultsModel->setItem(index,6,new QStandardItem(record1.value("ChargeItemPrice").toString()));
                m_resultsModel->setItem(index,7,new QStandardItem(record.value("Time").toString()));
                index++;
            }
        }
    }
}
コード例 #30
0
ファイル: htmlexport.cpp プロジェクト: KDE/kcalutils
void HtmlExport::createMonthView(QTextStream *ts)
{
    QDate start = fromDate();
    start.setYMD(start.year(), start.month(), 1);    // go back to first day in month

    QDate end(start.year(), start.month(), start.daysInMonth());

    int startmonth = start.month();
    int startyear = start.year();

    while (start < toDate()) {
        // Write header
        QDate hDate(start.year(), start.month(), 1);
        QString hMon = hDate.toString(QStringLiteral("MMMM"));
        QString hYear = hDate.toString(QStringLiteral("yyyy"));
        *ts << "<h2>"
            << i18nc("@title month and year", "%1 %2", hMon, hYear)
            << "</h2>" << endl;
        if (QLocale().firstDayOfWeek() == 1) {
            start = start.addDays(1 - start.dayOfWeek());
        } else {
            if (start.dayOfWeek() != 7) {
                start = start.addDays(-start.dayOfWeek());
            }
        }
        *ts << "<table border=\"1\">" << endl;

        // Write table header
        *ts << "  <tr>";
        for (int i = 0; i < 7; ++i) {
            *ts << "<th>" << QLocale().dayName(start.addDays(i).dayOfWeek()) << "</th>";
        }
        *ts << "</tr>" << endl;

        // Write days
        while (start <= end) {
            *ts << "  <tr>" << endl;
            for (int i = 0; i < 7; ++i) {
                *ts << "    <td valign=\"top\"><table border=\"0\">";

                *ts << "<tr><td ";
                if (d->mHolidayMap.contains(start) || start.dayOfWeek() == 7) {
                    *ts << "class=\"dateholiday\"";
                } else {
                    *ts << "class=\"date\"";
                }
                *ts << ">" << QString::number(start.day());

                if (d->mHolidayMap.contains(start)) {
                    *ts << " <em>" << d->mHolidayMap[start] << "</em>";
                }

                *ts << "</td></tr><tr><td valign=\"top\">";

                // Only print events within the from-to range
                if (start >= fromDate() && start <= toDate()) {
                    Event::List events = d->mCalendar->events(start, d->mCalendar->timeSpec(),
                                         EventSortStartDate,
                                         SortDirectionAscending);
                    if (events.count()) {
                        *ts << "<table>";
                        Event::List::ConstIterator it;
                        for (it = events.constBegin(); it != events.constEnd(); ++it) {
                            if (checkSecrecy(*it)) {
                                createEvent(ts, *it, start, false);
                            }
                        }
                        *ts << "</table>";
                    } else {
                        *ts << "&nbsp;";
                    }
                }

                *ts << "</td></tr></table></td>" << endl;
                start = start.addDays(1);
            }
            *ts << "  </tr>" << endl;
        }
        *ts << "</table>" << endl;
        startmonth += 1;
        if (startmonth > 12) {
            startyear += 1;
            startmonth = 1;
        }
        start.setYMD(startyear, startmonth, 1);
        end.setYMD(start.year(), start.month(), start.daysInMonth());
    }
}