Exemplo n.º 1
0
void tst_QHash::keys_values_uniqueKeys()
{
    QHash<QString, int> hash;
    QVERIFY(hash.uniqueKeys().isEmpty());
    QVERIFY(hash.keys().isEmpty());
    QVERIFY(hash.values().isEmpty());

    hash.insertMulti("alpha", 1);
    QVERIFY(sorted(hash.keys()) == (QList<QString>() << "alpha"));
    QVERIFY(hash.keys() == hash.uniqueKeys());
    QVERIFY(hash.values() == (QList<int>() << 1));

    hash.insertMulti("beta", -2);
    QVERIFY(sorted(hash.keys()) == (QList<QString>() << "alpha" << "beta"));
    QVERIFY(hash.keys() == hash.uniqueKeys());
    QVERIFY(sorted(hash.values()) == sorted(QList<int>() << 1 << -2));

    hash.insertMulti("alpha", 2);
    QVERIFY(sorted(hash.uniqueKeys()) == (QList<QString>() << "alpha" << "beta"));
    QVERIFY(sorted(hash.keys()) == (QList<QString>() << "alpha" << "alpha" << "beta"));
    QVERIFY(sorted(hash.values()) == sorted(QList<int>() << 2 << 1 << -2));

    hash.insertMulti("beta", 4);
    QVERIFY(sorted(hash.uniqueKeys()) == (QList<QString>() << "alpha" << "beta"));
    QVERIFY(sorted(hash.keys()) == (QList<QString>() << "alpha" << "alpha" << "beta" << "beta"));
    QVERIFY(sorted(hash.values()) == sorted(QList<int>() << 2 << 1 << 4 << -2));
}
Exemplo n.º 2
0
QHash<V3DLONG, V3DLONG> ChildParent(QList<NeuronSWC> &neurons, const QList<V3DLONG> & idlist, const QHash<V3DLONG,V3DLONG> & LUT)
{
    QHash<V3DLONG, V3DLONG> cp;
    for (V3DLONG i=0;i<neurons.size(); i++)
    {
        if (neurons.at(i).pn==-1)
            cp.insertMulti(idlist.indexOf(LUT.value(neurons.at(i).n)), -1);
        else if(idlist.indexOf(LUT.value(neurons.at(i).pn)) == 0 && neurons.at(i).pn != neurons.at(0).n)
            cp.insertMulti(idlist.indexOf(LUT.value(neurons.at(i).n)), -1);
        else
            cp.insertMulti(idlist.indexOf(LUT.value(neurons.at(i).n)), idlist.indexOf(LUT.value(neurons.at(i).pn)));
    }
        return cp;
};
static void fill(Counter &counter, const typename Counter::Container &container, bool fragmented)
{
    qint64 allocated = 0;
    QHash<void *, int> allocations;
    for (int i = 0; i < 100; ++i) {
        for (int j = 0; j < 100; ++j) {
            int amount = fragmented ? j : i;
            allocated += amount;
            counter.request(amount);
            void *alloc = malloc(amount);
            allocations.insertMulti(alloc, amount);
            counter.obtain(reinterpret_cast<quintptr>(alloc));
            QCOMPARE(counter.currentTotal(), allocated);
        }
    }

    QCOMPARE(allocated, 99 * 50 * 100);
    QCOMPARE(counter.currentTotal(), allocated);
    QCOMPARE(sum(container), allocated);

    for (auto it = allocations.begin(), end = allocations.end(); it != end; ++it) {
        free(it.key());
        counter.release(reinterpret_cast<quintptr>(it.key()));
        allocated -= it.value();
        QCOMPARE(counter.currentTotal(), allocated);
    }

    allocations.clear();

    QCOMPARE(allocated, 0);
    QCOMPARE(counter.currentTotal(), 0);
    QCOMPARE(sum(container), 0);
}
void QGeoSatelliteInfoSourcePrivate::loadStaticPlugins(QHash<QString, QGeoPositionInfoSourceFactory *> &plugins)
{
#if !defined QT_NO_DEBUG
    const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
#endif

    QObjectList staticPlugins = QPluginLoader::staticInstances();
    for (int i = 0; i < staticPlugins.count(); ++i) {
        QGeoPositionInfoSourceFactory *f =
                qobject_cast<QGeoPositionInfoSourceFactory*>(staticPlugins.at(i));

        if (f) {
            QString name = f->sourceName();

#if !defined QT_NO_DEBUG
            if (showDebug)
                qDebug("Static: found a service provider plugin with name %s", qPrintable(name));
#endif
            if (!name.isEmpty()) {
                plugins.insertMulti(name, f);
            }
        }

    }
}
Exemplo n.º 5
0
void testEraseNoError()
{
    QHash<int, int> a;

    a.insert(100, 100);
    a.insert(101, 200);
    a.insert(5, 50);
    a.insertMulti(5, 60);
    a.insertMulti(5, 70);
    a.insertMulti(5, 80);

    QHash<int, int>::iterator i = a.begin();
    while (i.key() != 5)
        ++i;
    ++i;
    a.erase(i);

    qDebug() << "Erase - got no errors on iterator check";
}
Exemplo n.º 6
0
/*!
 *  Parses URL-encoded form data
 *
 *  Extracts the key/value pairs from \bold application/x-www-form-urlencoded
 *  \a data, such as the query string from the URL or the form data from a
 *  POST request.
 */
QHash<QString, QString> QxtWebContent::parseUrlEncodedQuery(const QString& data)
{
    QUrl post("/?" + data);
    QHash<QString, QString> rv;
    foreach(const QxtQueryItem& item, QUrlQuery( post ).queryItems())
    {
        rv.insertMulti(item.first, item.second);
    }
    return rv;
}
Exemplo n.º 7
0
void tst_QHash::rehash_isnt_quadratic()
{
    // this test should be incredibly slow if rehash() is quadratic
    for (int j = 0; j < 5; ++j) {
        QHash<int, int> testHash;
#if defined(Q_OS_WINCE) || defined(Q_OS_SYMBIAN) // mobiles do not have infinite mem...
        for (int i = 0; i < 50000; ++i)
#else
        for (int i = 0; i < 500000; ++i)
#endif
            testHash.insertMulti(1, 1);
    }
}
Exemplo n.º 8
0
/*!
 *  Parses URL-encoded form data
 *
 *  Extracts the key/value pairs from \bold application/x-www-form-urlencoded
 *  \a data, such as the query string from the URL or the form data from a
 *  POST request.
 */
QHash<QString, QString> QxtWebContent::parseUrlEncodedQuery(const QString& data)
{
    QHash<QString, QString> rv;
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
    QUrl post("/?" + data);
#else
    QUrlQuery post("/?" + data);
#endif
    foreach(const QxtQueryItem& item, post.queryItems())
    {
        rv.insertMulti(item.first, item.second);
    }
    return rv;
}
Exemplo n.º 9
0
QHash<QString,QVariant> ReceiptsManager::getDistanceRules()
{
    QHash<QString,QVariant> hash;
    DistanceRulesModel model(this);
    for (int row = 0; row < model.rowCount(); ++row) {
        QString str = model.data(model.index(row,DISTRULES_TYPE),Qt::DisplayRole).toString();
        QVariant uid = model.data(model.index(row,DISTRULES_VALUES),Qt::DisplayRole);
        hash.insertMulti(str,uid);
    }
    if(hash.size()< 1){
        hash.insert("DistPrice",0.50);
    }
    return hash;
}
Exemplo n.º 10
0
QHash<V3DLONG, V3DLONG> getUniqueLUT(QList<NeuronSWC> &neurons)
{
    QHash<V3DLONG,V3DLONG> LUT;

    for (V3DLONG i=0;i<neurons.size();i++)
    {
        V3DLONG j;
        for (j=0;j<i;j++)
        {
            if (neurons.at(i).x==neurons.at(j).x && neurons.at(i).y==neurons.at(j).y && neurons.at(i).z==neurons.at(j).z)	break;
        }
        LUT.insertMulti(neurons.at(i).n,j);
    }
    return (LUT);
};
Exemplo n.º 11
0
QHash<QString,QString> ServerMgr::serverList(QString network)
{
    int count = ini.CountItems(network);
    QHash<QString,QString> r;

    for (int i = 1; i <= count; i++) {
        QString servername = ini.ReadIniItem(network, i);
        QString serverdetails = ini.ReadIni(network, i);

        // Insert multi in case someone adds a server with same name in the list (f.ex. via editing servers.ini)
        r.insertMulti(servername, serverdetails);
    }

    return r;
}
Exemplo n.º 12
0
QHash<QString,QVariant> ReceiptsManager::getHashOfInsurance()
{
    QHash<QString,QVariant> hash;
    InsuranceModel model(this);
    for (int row = 0; row < model.rowCount(); row += 1) {
        QString str = model.data(model.index(row,INSURANCE_NAME),Qt::DisplayRole).toString();
        if (WarnDebugMessage)
            qDebug() << __FILE__ << QString::number(__LINE__) << " str =" << str ;
        QVariant uid = model.data(model.index(row,INSURANCE_UID),Qt::DisplayRole);
        hash.insertMulti(str,uid);
    }
    if(hash.size()< 1) {
        hash.insert("patient","uid");
    }
    return hash;
}
Exemplo n.º 13
0
QHash<QString,QVariant> ReceiptsManager::getHashOfThesaurus()
{
    QHash<QString,QVariant> hash;
    ThesaurusModel model(this);
    for (int row = 0; row < model.rowCount(); ++row)
    {
        QString str = model.data(model.index(row,THESAURUS_VALUES),Qt::DisplayRole).toString();
        QVariant uid = model.data(model.index(row,THESAURUS_USERUID),Qt::DisplayRole);
        if (WarnDebugMessage)
            qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager list = " << str;
        if (WarnDebugMessage)
            qDebug() << __FILE__ << QString::number(__LINE__) << " uid =" << uid.toString() ;
        hash.insertMulti(str,uid);
    }
    if (hash.size()< 1) {
        hash.insert("thesaurus","userUuid");
    }
    return hash;
}
Exemplo n.º 14
0
QHash<QString,QVariant> ReceiptsManager::getHashOfSites(){
    QHash<QString,QVariant> hash;
    WorkingPlacesModel model(this);
    for (int row = 0; row < model.rowCount(); row += 1)
    {
        QString str = model.data(model.index(row,SITES_NAME),Qt::DisplayRole).toString();
        QVariant uid = model.data(model.index(row,SITES_UID),Qt::DisplayRole);
        //if (WarnDebugMessage)
        qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager list = " << str;
        //if (WarnDebugMessage)
        qDebug() << __FILE__ << QString::number(__LINE__) << " uid =" << uid.toString() ;
        hash.insertMulti(str,uid);


    }
    if(hash.size()< 1){
        hash.insert("cabinet","uid");
    }
    return hash;
}
Exemplo n.º 15
0
double AssetsIO::getRate(const QDate &date, double duration) {
    Q_UNUSED(date);
    double rate = 0.00;
    QHash<QString,QDate> hashRatesDates;
    QStringList listChosenOfRanges;
    AssetsRatesModel model(this);
    if (WarnDebugMessage)
        qDebug() << __FILE__ << QString::number(__LINE__) << " model.rowCount() =" << QString::number(model.rowCount()) ;
    for (int i = 0; i < model.rowCount(); i += 1) {
        QDate dateRequest = model.data(model.index(i,ASSETSRATES_DATE),Qt::DisplayRole).toDate();
        QString rangeReq = model.data(model.index(i,ASSETSRATES_YEARS),Qt::DisplayRole).toString();
        QString rate = model.data(model.index(i,ASSETSRATES_RATES),Qt::DisplayRole).toString();
        if (WarnDebugMessage)
            qDebug() << __FILE__ << QString::number(__LINE__) << " rangeReq and rate =" << rangeReq+" "+rate ;
        QStringList listOfRanges = rangeReq.split("_");
        if (int(duration) >= listOfRanges[0].toInt() && int(duration) <= listOfRanges[1].toInt()) {
            hashRatesDates.insertMulti(rate,dateRequest) ;
        }
    }
    QList<QDate> valuesOfDates = hashRatesDates.values();
    if (WarnDebugMessage)
        qDebug() << __FILE__ << QString::number(__LINE__) << " valuesOfDates size =" << QString::number(valuesOfDates.size()) ;
    if (hashRatesDates.size() < 1) {
        Utils::warningMessageBox(tkTr(Trans::Constants::ERROR),
                                 tr("You have to fill defaults for assets rates.\nGo "
                                    "in Configuration>Preferences to do so.\n"
                                    "Otherwise result will be wrong !"));
        return 1.00;
    }
    qSort(valuesOfDates.begin(),valuesOfDates.end());

    QDate nearestDate = valuesOfDates.last();
    QString nearestDateStr = nearestDate.toString("yyyy-MM-dd");
    QString rateStr = hashRatesDates.key(nearestDate);
    rate = rateStr.toDouble();
    qWarning() << __FILE__ << QString::number(__LINE__) << "rate = " << QString::number(rate) ;
    return rate;
}
void QGeoSatelliteInfoSourcePrivate::loadDynamicPlugins(QHash<QString, QGeoPositionInfoSourceFactory *> &plugins)
{
    QStringList paths;
    paths << mobilityPlugins(QLatin1String("position"));

    QPluginLoader qpl;
    QString blockName;

    QSettings settings(QSettings::SystemScope, QLatin1String("Nokia"), QLatin1String("QtLocationPosAndSat"));
    QVariant value = settings.value("position.plugin.operator.whitelist");
    if (value.isValid()) {
        QStringList parts = value.toString().split(",");
        if (parts.size() == 4) {
            QFile file(parts.at(1));
            file.open(QIODevice::ReadOnly);

            QCryptographicHash hash(QCryptographicHash::Sha1);
            while (!file.atEnd()) {
                QByteArray data = file.read(4096);
                hash.addData(data);
            }
            file.close();

            QByteArray hexHash = hash.result().toHex();

            bool loadIt = true;
            if (QString::number(file.size()) != parts.at(3)) {
                qCritical("Position info plugin: bad plugin size for %s",
                          qPrintable(parts.at(1)));
                qWarning("Will fall back to platform default");
                loadIt = false;
            }

            if (hexHash != parts.at(2).toLatin1()) {
                qCritical("Position info plugin: bad plugin hash for %s",
                          qPrintable(parts.at(1)));
                qWarning("Will fall back to platform default");
                loadIt = false;
            }

            if (loadIt) {
                qpl.setFileName(parts.at(1));
                QGeoPositionInfoSourceFactory *f =
                        qobject_cast<QGeoPositionInfoSourceFactory*>(qpl.instance());

                if (f) {
                    QString name = f->sourceName();
                    if (name == parts.at(0)) {
                        plugins.insert(name, f);
                    } else {
                        qCritical("Position info plugin: bad plugin name for %s",
                                  qPrintable(parts.at(1)));
                        qWarning("Will fall back to platform default");
                    }
                }
            }

            // still set blockName to ensure the plugin doesn't load
            blockName = parts.at(1);
        } else {
            qWarning("Position plugin whitelist: invalid format -- should be key,filename,hash,size");
        }
    }

    for (int i = 0; i < paths.count(); ++i) {
        if (paths.at(i) != blockName) {
            qpl.setFileName(paths.at(i));

            QGeoPositionInfoSourceFactory *f =
                    qobject_cast<QGeoPositionInfoSourceFactory*>(qpl.instance());
            if (f) {
                QString name = f->sourceName();

    #if !defined QT_NO_DEBUG
                const bool showDebug = qgetenv("QT_DEBUG_PLUGINS").toInt() > 0;
                if (showDebug)
                    qDebug("Dynamic: found a service provider plugin with name %s", qPrintable(name));
    #endif
                plugins.insertMulti(name, f);
            }
        }
    }
}
Exemplo n.º 17
0
void tst_QHash::compare2()
{
    QHash<int, int> a;
    QHash<int, int> b;

    a.insertMulti(17, 1);
    a.insertMulti(17 * 2, 1);
    b.insertMulti(17 * 2, 1);
    b.insertMulti(17, 1);
    QVERIFY(a == b);
    QVERIFY(b == a);

    a.insertMulti(17, 2);
    a.insertMulti(17 * 2, 3);
    b.insertMulti(17 * 2, 3);
    b.insertMulti(17, 2);
    QVERIFY(a == b);
    QVERIFY(b == a);

    a.insertMulti(17, 4);
    a.insertMulti(17 * 2, 5);
    b.insertMulti(17 * 2, 4);
    b.insertMulti(17, 5);
    QVERIFY(!(a == b));
    QVERIFY(!(b == a));

    a.clear();
    b.clear();
    a.insertMulti(1, 1);
    a.insertMulti(1, 2);
    a.insertMulti(1, 3);
    b.insertMulti(1, 1);
    b.insertMulti(1, 2);
    b.insertMulti(1, 3);
    b.insertMulti(1, 4);
    QVERIFY(!(a == b));
    QVERIFY(!(b == a));
}
Exemplo n.º 18
0
QVariant Cell::parseMember(const QString &formula, SpreadSheet *widget) const
{
    int fOp = firstOperatorPosition(formula);
    if (fOp == -1)
        fOp = formula.length();
    QChar first = formula.at(0);
    
    QRegExp importedData("([\\w\\s]+:[A-Z][1-9][0-9]*)");
    QRegExp cellId("([A-Z][1-9][0-9]*)");
    
    //paranteza
    if (first=='(')
    {
        int end = 0;
        int open_p_count = 0;
        int closed_p_count = 0;
        for (int c=0; c<formula.length(); c++)
        {
            if (formula.at(c) == '(')
                open_p_count++;
            else if (formula.at(c) == ')')
                closed_p_count++;
            if (open_p_count == closed_p_count)
            {
                end = c;
                break;
            }
        }
        return computeFormula(formula.mid(1,end-1), widget);
    }
    //numar 0 sau 0.0
    else if (first.isDigit())
    {
        QString s = formula.left(fOp);
        if (s.count('.') <= 1)
        {
            bool ok;
            double x = s.toDouble(&ok);
            if (ok)
                return x;
        }
        emit invalidFormula(QString("Invalid number or number format in %1").arg(s));
        return "#####";
    }
    //tabela:identificator
    else if (formula.indexOf(importedData) == 0)
    {
        int idx = 0;
        QHash<QString,QString> matches = QHash<QString,QString>();
        while ((idx = formula.indexOf(importedData, idx)) != -1)
        {
            QString match = formula.mid(idx, importedData.matchedLength());
            int delim = match.indexOf(':');
            QString table = match.left(delim);
            QString id = match.mid(delim+1);
            matches.insertMulti(table, id);
            idx += importedData.matchedLength();
        }
        QString result = widget->getLinkData(formula, matches);
        if (isValidFormula(result))
            return display(result);
        else
            return result;
    }
    //celula A2
    else if (cellId.exactMatch(formula))
    {
        QVariant cellVal = getCellValue(formula,widget);
        if (cellVal == "#####")
            emit invalidFormula(QString("Invalid cell data in %1").arg(formula));
        return cellVal;
    }
    //functie nume_functie(A1;A2;A3)
    else if (first.isLower())
    {
        QStringList simple_function_names;
        QStringList cond_function_names;
        QStringList parameters;
        simple_function_names << "sum" << "avg" << "count";
        cond_function_names << "if" << "countif";
        QString s = formula.left(fOp);

        QString params = s.mid(s.lastIndexOf('(')+1,
                               s.indexOf(')')-s.lastIndexOf('(')-1);
        if (s.count('(') == s.count(')'))
            parameters = params.split(';');
        else
        {
            emit invalidFormula(QString("Invalid paranthesis number ").append(s));
            return "#####";
        }
        s = formula.left(formula.indexOf('('));
        if (simple_function_names.contains(s))
        {
            QVariantList values;
            QListIterator<QString> it(parameters);
            while (it.hasNext())
            {
                QString str = it.next();
                QVariant val = parseMember(str, widget);
                if (val != "#####")
                    values.append(val);
            }

            if (s == "sum")
            {
                double tmp = 0;
                bool ok = true;
                QListIterator<QVariant> valIt(values);
                while (valIt.hasNext())
                {
                    QVariant aux = valIt.next();
                    tmp += aux.toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Not a number: ").append(aux.toString()));
                        return "#####";
                    }
                }
                return tmp;
            }
            else if (s == "avg")
            {
                double tmp = 0;
                bool ok = true;
                QListIterator<QVariant> valIt(values);
                while (valIt.hasNext())
                {
                    QVariant aux = valIt.next();
                    tmp += aux.toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Not a number: ").append(aux.toString()));
                        return "#####";
                    }
                }
                tmp /= parameters.length();
                return tmp;
            }
            else if (s == "count")
            {
                return values.length();
            }
        }
        else if (cond_function_names.contains(s))
        {
            int param_no = parameters.length();
            if (param_no < 2)
            {
                emit invalidFormula(QString("Invalid parameter number: %1").arg(param_no));
                return "#####";
            }
            
            if (s == "if")
            {
                //if(A1<5;"Picat";n)
                //if(A1<5;4)
                QRegExp pattern("^(([\\w\\s]+:)?[A-Z][1-9][0-9]*"
                                "(<|<=|>|>=|<>|=)"
                                "((([\\w\\s]+:)?[A-Z][1-9][0-9]*)|(\\d+(\\.\\d+)?)))$");
                QString condition = parameters.at(0);
                if (pattern.exactMatch(condition) && param_no <= 3)
                {
                    int length = 1;
                    int opPos = condition.indexOf(QRegExp("(<|>|=)"));
                    if (condition.indexOf(QRegExp("(<=|>=|<>)")) > -1)
                        length = 2;
                    QString op = condition.mid(opPos,length);
                    bool ok1, ok2;
                    double firstOperand = parseMember(condition.left(opPos), widget).toDouble(&ok1);
                    double secondOperand = parseMember(condition.mid(opPos+length), widget).toDouble(&ok2);
                    if (!ok1 || !ok2)
                    {
                        emit invalidFormula(QString("Invalid condition parameters: %1").arg(condition));
                        return "#####";
                    }
                    if (param_no == 2)
                        return compareMembers(param_no, op,
                                              firstOperand, secondOperand,
                                              parameters.at(1), "#####");
                    else if (param_no == 3)
                        return compareMembers(param_no, op,
                                              firstOperand, secondOperand,
                                              parameters.at(1), parameters.at(2));
                }
                else
                {
                    emit invalidFormula(QString("Invalid formula syntax: ").append(condition));
                    return "#####";
                }
            }
            else if (s == "countif")
            {
                //countif(A1;A2...An;>5)
                if (param_no > 2)
                {
                    int count = 0;
                    int length = 1;
                    QString condition = parameters.last();
                    int opPos = condition.indexOf(QRegExp("(<|>|=)"));
                    if (condition.indexOf(QRegExp("(<=|>=|<>)")) > -1)
                        length = 2;
                    if (opPos == -1)
                    {
                        emit invalidFormula(QString("Invalid condition syntax: ").append(condition));
                        return "#####";
                    } 
                    QString op = condition.mid(opPos,length);
                    bool ok;
                    double firstOperand;
                    double secondOperand = parseMember(condition.mid(opPos+length), widget).toDouble(&ok);
                    if (!ok)
                    {
                        emit invalidFormula(QString("Invalid second operand: %1").
                                            arg(condition.mid(opPos+length)));
                        return "#####";
                    }
                    for (int i=0; i<param_no-1; i++)
                    {
                        firstOperand = parseMember(parameters.at(i), widget).toDouble(&ok);
                        if (!ok)
                        {
                            emit invalidFormula(QString("Invalid operand: %1").
                                                arg(parameters.at(i)));
                            return "#####";
                        }
                        if (compareMembers(op, firstOperand, secondOperand))
                            count++;
                    }
                    return count;
                }
            }
        }
        else
        {
            emit invalidFormula("Invalid formula");
            return "#####";
        }
    }
    return formula;
}
Exemplo n.º 19
0
void tiBackupEdit::on_btnEditBackupJob_clicked()
{
    qDebug() << "tiBackupEdit::on_btnEditBackupJob_clicked() -> BackupDeviceValue::" << getBackupDeviceValue();
    qDebug() << "tiBackupEdit::on_btnEditBackupJob_clicked() -> BackupPartitionValue::" << getBackupPartitionValue();

    //QString devname = ui->comboBackupDevice->itemData(ui->comboBackupDevice->currentIndex()).toString();
    QStandardItemModel *model = dynamic_cast<QStandardItemModel *>(ui->tvBackupFolders->model());
    tiConfBackupJobs jobs;

    if(ui->leBackupJobName->text().isEmpty())
    {
        QMessageBox::information(this, QString::fromUtf8("Edit backupjob"), QString::fromUtf8("You must set a name for the backupjob."));
        return;
    }

    tiBackupJob job = *currentJob;

    if(currentJob->name != ui->leBackupJobName->text())
    {
        // We must rename the job
        if(!jobs.renameJob(currentJob->name, ui->leBackupJobName->text()))
        {
            QMessageBox::information(this, QString::fromUtf8("Edit backupjob"), QString::fromUtf8("The backupjob name could not be changed."));
            return;
        }
        job.name = ui->leBackupJobName->text();
    }

    job.device = getBackupDeviceValue();
    job.partition_uuid = getBackupPartitionValue();
    job.delete_add_file_on_dest = ui->cbDeleteAddFilesOnDest->isChecked();
    job.start_backup_on_hotplug = ui->cbBackupOnHotplug->isChecked();
    job.save_log = ui->cbSaveLog->isChecked();
    job.compare_via_checksum = ui->cbCompareViaChecksum->isChecked();
    job.notify = false;
    if(ui->gbNotify->isChecked() == true)
    {
        job.notify = true;
        job.notifyRecipients = ui->leNotifyRecipients->text();
    }
    job.scriptBeforeBackup = ui->leScriptPathBeforeBackup->text();
    job.scriptAfterBackup = ui->leScriptPathAfterBackup->text();

    /*
    DeviceDisk selDisk;
    selDisk.devname = devname;

    DeviceDiskPartition part = selDisk.getPartitionByUUID(job.partition_uuid);
    TiBackupLib lib;
    */

    QHash<QString, QString> h;
    QString dest;
    TiBackupLib lib;
    bool diskMounted = false;
    DeviceDiskPartition part = TiBackupLib::getPartitionByUUID(getBackupPartitionValue());
    if(lib.isMounted(part.name))
        diskMounted = true;

    for(int i=0; i < model->rowCount(); i++)
    {
        dest = model->item(i, 1)->text();
        if(diskMounted == true)
            dest = TiBackupLib::convertPath2Generic(dest, lib.getMountDir(part.name));

        //h.insertMulti(model->item(i, 0)->text(), TiBackupLib::convertPath2Generic(model->item(i, 1)->text(), lib.getMountDir(part.name)));
        h.insertMulti(model->item(i, 0)->text(), dest);
    }
    job.backupdirs = h;

    // Set task values
    job.intervalType = static_cast<tiBackupJobInterval>(ui->cbInterval->currentIndex());
    job.intervalTime = "0";
    job.intervalDay = 0;
    switch(job.intervalType)
    {
    case tiBackupJobIntervalNONE:
        break;
    case tiBackupJobIntervalDAILY:
        job.intervalTime = ui->teDailyTime->text();
        break;
    case tiBackupJobIntervalWEEKLY:
        job.intervalTime = ui->teWeeklyTime->text();
        job.intervalDay = ui->cbWeeklyDay->currentIndex();
        break;
    case tiBackupJobIntervalMONTHLY:
        job.intervalTime = ui->teMonthlyTime->text();
        job.intervalDay = ui->sbMonthlyDay->value();
        break;
    }

    jobs.saveBackupJob(job);

    parentWidget()->close();

    emit jobEdited(job);
}
Exemplo n.º 20
0
Arquivo: main.cpp Projeto: dtbinh/vmt
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    //-----------------------------------------------------------------------------------------------------------------
    // SET MAJOR VARIABLES HERE
    //-----------------------------------------------------------------------------------------------------------------
    KlaserFunction operation = Feature_From_Vmt;
    bool isGsuData = false;

    QDir dataDir("...");
    QDir trackFileDir("...");
    QDir targetDir("/home/emredog/LIRIS-data/test_features/20141102-rot-int_args16");
    QDir vmtDir("/home/emredog/LIRIS-data/test_VMTs_20140916-ROTATED-INTERPOLATED");
    //------------------------------------------------------------------------------------------------------------------

    if (!targetDir.exists())
        QDir().mkdir(targetDir.absolutePath());
    QDir initialDir = QDir::current();
    QDir::setCurrent("/home/emredog/qt_builds/build-Klaser-Schmid_Hog3D_VMT-Desktop-Release");
    const int threadCount = 2;

    QStringList algoArgs;

    switch(operation)
    {
    case Generate_Vmt:
    {
        // SET KLASER&SCHMID VARIABLES HERE
        algoArgs << "--vmt-only";
        if (isGsuData)
            algoArgs << "--gsu-data";

        cout << "Data directory: " << dataDir.absolutePath().toStdString() << endl;
        QStringList nameFilters;

        //get all image sequences:
        QStringList videos = dataDir.entryList(nameFilters, QDir::AllDirs | QDir::NoDotAndDotDot);
        cout << "Videos fetched: " << videos.count() << endl;

        //get all track files
        nameFilters << "*.track";
        QStringList trackFiles = trackFileDir.entryList(nameFilters, QDir::Files | QDir::NoDotAndDotDot);
        cout << "Track files fetched: " << trackFiles.count() << endl;

        //match track files and videos:
        cout << "Matching track files and videos";

        QHash<QString, QString> videosToTrackFiles;
        foreach (QString video, videos)
        {
            QStringList searchResults = trackFiles.filter(video);
            foreach (QString result, searchResults)
                videosToTrackFiles.insertMulti(video, result);

            cout << ".";
        }

        cout << endl << "Matching completed." << endl;


        QHash<QString, QString>::const_iterator it = videosToTrackFiles.constBegin();


        QList<VideoTrackPair> pairs;

        while (it != videosToTrackFiles.constEnd())
        {
            VideoTrackPair pair;
            pair.first = it.key();
            pair.second = it.value();
            pairs.append(pair);
            ++it;
        }

        int length = pairs.length()/threadCount;

        struct timespec ts = { 5000 / 1000, (5000 % 1000) * 1000 * 1000 };
        nanosleep(&ts, NULL);

        for (int i=0; i<threadCount; i++)
        {
            int startPos = i * length;

            if (i == threadCount - 1) //if it's the last thread
                length = -1; //just take all of the remaining files

            KlaserSchmidThread* proc = new KlaserSchmidThread(pairs.mid(startPos, length), algoArgs, dataDir, trackFileDir, targetDir, i+1);
            proc->start();
        }
        break;

    }
    case Feature_From_Vmt: //we have VMT files already
    {
        // SET KLASER&SCHMID VARIABLES HERE
        algoArgs << "-P" << "icosahedron" //"dodecahedron" icosahedron
                    //<< "--loose-track"
                 << "--xy-stride" <<  "16"  //"16" "32"
                 << "--t-stride" << "16"    //"16" "32"
                 << "--xy-ncells" << "2"
                 << "--t-ncells" << "2"
                 << "--npix" << "2";

        if (isGsuData)
            algoArgs << "--gsu-data";

        cout << "VMT directory: " << vmtDir.absolutePath().toStdString() << endl;
        QStringList nameFilters;
        //get all VMT files
        nameFilters << "*.pcd";
        QStringList vmtFiles = vmtDir.entryList(nameFilters, QDir::Files | QDir::NoDotAndDotDot);
        cout << "VMT files fetched: " << vmtFiles.count() << endl;

        int length = vmtFiles.length()/threadCount;

        struct timespec ts = { 5000 / 1000, (5000 % 1000) * 1000 * 1000 };
        nanosleep(&ts, NULL);

        for (int i=0; i<threadCount; i++)
        {
            int startPos = i * length;

            if (i == threadCount - 1) //if it's the last thread
                length = -1; //just take all of the remaining files

            KlaserSchmidThreadFromVMT* proc = new KlaserSchmidThreadFromVMT(vmtFiles.mid(startPos, length), vmtDir, algoArgs, targetDir, i+1);
            proc->start();
        }
        break;
    }
    case Rotation_Angle_Only:
    {
        // SET KLASER&SCHMID VARIABLES HERE
        algoArgs << "--calculate-rotation";
        if (isGsuData)
            algoArgs << "--gsu-data";

        QString program = "./Klaser-Schmid_Hog3D_VMT";

        cout << "Data directory: " << dataDir.absolutePath().toStdString() << endl;
        QStringList nameFilters;

        //get all image sequences:
        QStringList videos = dataDir.entryList(nameFilters, QDir::AllDirs | QDir::NoDotAndDotDot);
        cout << "Videos fetched: " << videos.count() << endl;

        //get all track files
        nameFilters << "*.track";
        QStringList trackFiles = trackFileDir.entryList(nameFilters, QDir::Files | QDir::NoDotAndDotDot);
        cout << "Track files fetched: " << trackFiles.count() << endl;

        //match track files and videos:
        cout << "Matching track files and videos";

        QHash<QString, QString> videosToTrackFiles;
        foreach (QString video, videos)
        {
            QStringList searchResults = trackFiles.filter(video);
            foreach (QString result, searchResults)
                videosToTrackFiles.insertMulti(video, result);

            cout << ".";
        }

        cout << endl << "Matching completed." << endl;


        QHash<QString, QString>::const_iterator it = videosToTrackFiles.constBegin();

        QStringList inputArgs;
        QFileInfo* trackFileInfo;
        int counter = 1;

        QList<VideoTrackPair> pairs;

        while (it != videosToTrackFiles.constEnd())
        {
            VideoTrackPair pair;
            pair.first = it.key();
            pair.second = it.value();
            pairs.append(pair);
            ++it;
        }

        //we don't need multithread functionality for this operation

        QProcess* process;
        QString outputFilePath = initialDir.absoluteFilePath("rotationAngles.txt");

        foreach (VideoTrackPair pair, pairs)
        {
            inputArgs << "--video-file" << dataDir.absoluteFilePath(pair.first)
                      << "-t" << trackFileDir.absoluteFilePath(pair.second);

            //create a new process
            process = new QProcess();
            //set output file name
            trackFileInfo = new QFileInfo(pair.second);
            process->setStandardOutputFile(outputFilePath, QIODevice::Append);

            //run the program
            process->start(program, inputArgs + algoArgs);
            cout << "All parameters:" << endl << "\t"
                 << inputArgs.join(" ").toStdString() << " " << algoArgs.join(" ").toStdString() << endl << endl;

            //check if it started normally
            if (!process->waitForStarted(3000))
            {
                cerr << "Could not start process with following parameters:" << endl
                     << "input: " << inputArgs.join(" ").toStdString() << endl
                     << "parameters: " << algoArgs.join(" ").toStdString() << endl;

                continue;
            }

            //wait 10 minutes for it to finish
            if (!process->waitForFinished(600000)) //wait for 10 minutes
            {
                cerr << "Could not complete process within 10 minutes, with following parameters:" << endl
                     << "input: " << inputArgs.join(" ").toStdString() << endl
                     << "parameters: " << algoArgs.join(" ").toStdString() << endl;

                continue;
            }

            counter++;

            //clean-up
            delete process;
            delete trackFileInfo;
            inputArgs.clear();
        }
Exemplo n.º 21
0
void TabManagerWidget::processActions()
{
    if (!sender()) {
        return;
    }

    m_refreshBlocked = true;

    QHash<BrowserWindow*, WebTab*> selectedTabs;

    const QString &command = sender()->objectName();

    for (int i = 0; i < ui->treeWidget->topLevelItemCount(); ++i) {
        QTreeWidgetItem* winItem = ui->treeWidget->topLevelItem(i);
        if (winItem->checkState(0) == Qt::Unchecked) {
            continue;
        }

        for (int j = 0; j < winItem->childCount(); ++j) {
            QTreeWidgetItem* tabItem = winItem->child(j);
            if (tabItem->checkState(0) == Qt::Unchecked) {
                continue;
            }

            BrowserWindow* mainWindow = qobject_cast<BrowserWindow*>(qvariant_cast<QWidget*>(tabItem->data(0, QupZillaPointerRole)));
            WebTab* webTab = qobject_cast<WebTab*>(qvariant_cast<QWidget*>(tabItem->data(0, WebTabPointerRole)));

            // current supported actions are not applied to pinned tabs
            if (webTab->isPinned()) {
                tabItem->setCheckState(0, Qt::Unchecked);
                continue;
            }

            if (command == "closeSelection") {
                if (webTab->url().toString() == "qupzilla:restore") {
                    continue;
                }
                selectedTabs.insertMulti(mainWindow, webTab);
            }
            else if (command == "detachSelection" || command == "bookmarkSelection") {
                selectedTabs.insertMulti(mainWindow, webTab);
            }
        }
        winItem->setCheckState(0, Qt::Unchecked);
    }

    if (!selectedTabs.isEmpty()) {
        if (command == "closeSelection") {
            closeSelectedTabs(selectedTabs);
        }
        else if (command == "detachSelection") {
            detachSelectedTabs(selectedTabs);
        }
        else if (command == "bookmarkSelection") {
            bookmarkSelectedTabs(selectedTabs);
        }
    }

    m_refreshBlocked = false;
    delayedRefreshTree();
}
Exemplo n.º 22
0
QHash<QString,QVariant> ReceiptsManager::getParametersData(QString & userUid , int table)
{
   QHash<QString,QVariant> hashForReturn;
   if (WarnDebugMessage)
       qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager: in getComboBoxesData";
   if (table == DEBTOR_ITEM) {
       InsuranceModel  model(this);
       for (int row = 0; row < model.rowCount(); row += 1) {
           QString str = model.data(model.index(row,INSURANCE_NAME),Qt::DisplayRole).toString();
           QVariant uid = model.data(model.index(row,INSURANCE_UID),Qt::DisplayRole);
           if (WarnDebugMessage)
               qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager list = " << str;
           hashForReturn.insert(str,uid);
       }
       if (hashForReturn.size()< 1){
           hashForReturn.insert("patient","uid");
       }
   }
   if (table == SITES_ITEM) {
       WorkingPlacesModel model(this);
       for (int row = 0; row < model.rowCount(); row += 1) {
           QString str = model.data(model.index(row,SITES_NAME),Qt::DisplayRole).toString();
           QVariant uid = model.data(model.index(row,SITES_UID),Qt::DisplayRole);
           if (WarnDebugMessage)
               qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager list = " << str;
           if (WarnDebugMessage)
               qDebug() << __FILE__ << QString::number(__LINE__) << " uid =" << uid.toString() ;
           hashForReturn.insert(str,uid);


       }
       if(hashForReturn.size()< 1){
           hashForReturn.insert("cabinet","uid");
       }

   }
   if (table == BANK_ITEM) {
       BankAccountModel model(this);
       for (int row = 0; row < model.rowCount(); row += 1) {
           QString str = model.data(model.index(row,BANKDETAILS_LABEL),Qt::DisplayRole).toString();
           QVariant uid = model.data(model.index(row,BANKDETAILS_ID),Qt::DisplayRole);
           if (WarnDebugMessage)
               qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager list = " << str;
           hashForReturn.insert(str,uid);
       }
       if(hashForReturn.size()< 1){
           hashForReturn.insert("bank","uid");
       }

   }
   if (table == RULES_ITEM)
   {
       RulesModel model(this);
       for (int row = 0; row < model.rowCount(); row += 1)
       {
           QString str = model.data(model.index(row,RULES_TYPE),Qt::DisplayRole).toString();
           QVariant uid = model.data(model.index(row,RULES_UID),Qt::DisplayRole);
           if (WarnDebugMessage)
               qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager list = " << str;
           hashForReturn.insert(str,uid);
       }
       if(hashForReturn.size()< 1){
           hashForReturn.insert("rule","uid");
       }

   }
   if (table == DISTANCE_RULES_ITEM)
   {
       DistanceRulesModel model(this);
       if (WarnDebugMessage)
           qDebug() << __FILE__ << QString::number(__LINE__) << " distrules =" << QString::number(model.rowCount()) ;
       for (int row = 0; row < model.rowCount(); row += 1)
       {
           QString str = model.data(model.index(row,DISTRULES_TYPE),Qt::DisplayRole).toString();
           QVariant uid = model.data(model.index(row,DISTRULES_UID),Qt::DisplayRole);
           if (WarnDebugMessage)
               qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager list = " << str;
           hashForReturn.insertMulti(str,uid);
       }
       if(hashForReturn.size()< 1){
           hashForReturn.insert("distance_rules","uid");
       }

   }
   if (table == THESAURUS_ITEM)
   {
       ThesaurusModel model(this);
       QString userFilter = QString("%1 = '%2'").arg("THESAURUS_USERUID",userUid);
       model.setFilter(userFilter);
       for (int row = 0; row < model.rowCount(); row += 1)
       {
           QString str = model.data(model.index(row,THESAURUS_VALUES),Qt::DisplayRole).toString();
           QVariant uid = model.data(model.index(row,THESAURUS_UID),Qt::DisplayRole);
           if (WarnDebugMessage)
               qDebug() << __FILE__ << QString::number(__LINE__) << " ReceiptsManager list = " << str;
           hashForReturn.insert(str,uid);
           }
       if(hashForReturn.size()< 1){
           hashForReturn.insert("Act for example","uid");
           hashForReturn.insert("Please create your own series.","uid");
           }

   }

   return hashForReturn;;
}
Exemplo n.º 23
0
void ControlBalance::analyse(){
    qDebug() << __FILE__ << QString::number(__LINE__) << " in analyse " ;
    double sumOfNotValidatedHono = 0.00;
    double sumOfCash = 0.00;
    double sumOfChecks = 0.00;
    double sumOfVisa = 0.00;
    double sumOfVir = 0.00;//vir
    QHash<int,QString> hashOfIdHonoNotValidated;
    QSqlQuery qHonoNotValidated(m_db);
    const QString reqHono = QString("SELECT %1 FROM %2 WHERE %3 NOT LIKE '%4' AND %5 BETWEEN '%6' AND '%7'")
                                                                               .arg("esp,chq,cb,vir,id_hono",
                                                                                    "honoraires",
                                                                                    "valide",
                                                                                    "1",
                                                                                    "date",
                                                                                    m_dateBegin.toString("yyyy-MM-dd"),
                                                                                    m_dateEnd.toString("yyyy-MM-dd"));
    if (!qHonoNotValidated.exec(reqHono))
    {
    	  qWarning() << __FILE__ << QString::number(__LINE__) << qHonoNotValidated.lastError().text() ;
        }
    qDebug() << __FILE__ << QString::number(__LINE__) << " qHonoNotValidated =" << qHonoNotValidated.lastQuery() ;
    while (qHonoNotValidated.next())
    {
    	int type = 0;
    	double cash = qHonoNotValidated.value(CASH).toDouble();
    	if (cash > 0)
    	{
    		type = CASH;  
    	    }
    	qDebug() << __FILE__ << QString::number(__LINE__) << " cash =" << QString::number(cash) ;
    	double checks = qHonoNotValidated.value(CHECKS).toDouble();
    	if (checks > 0)
    	{
    		type = CHECKS;  
    	    }
    	double visa = qHonoNotValidated.value(VISA).toDouble();
    	if (visa > 0)
    	{
    		type = VISA;  
    	    }
    	double vir = qHonoNotValidated.value(VIR).toDouble();
    	if (vir > 0)
    	{
    		type = VIR;
    	    }
    	QString idHono = qHonoNotValidated.value(IDHONO).toString();
    	
    	qDebug() << __FILE__ << QString::number(__LINE__) << " idHono =" << idHono ;
    	sumOfCash += cash;
    	sumOfChecks += checks;
    	sumOfVisa += visa;
    	sumOfVir += vir;
    	sumOfNotValidatedHono += cash+checks+visa+vir;
    	hashOfIdHonoNotValidated.insertMulti(type,idHono) ;
        }
    double newBalanceOfAccount = m_lastBalance + sumOfNotValidatedHono;
    //tests
    qDebug() << __FILE__ << QString::number(__LINE__) << " newBalanceOfAccount =" << QString::number(newBalanceOfAccount) ;
    qDebug() << __FILE__ << QString::number(__LINE__) << " m_balance =" << QString::number(m_balance) ;
    double differenceTotal = newBalanceOfAccount - m_balance;
    double diffCash = m_cashDeposits - sumOfCash;
    double diffChecks = m_checksDeposits - sumOfChecks;
    double diffVisa = m_visaDeposits - sumOfVisa;
    double diffOthers = m_othersDeposits - sumOfVir;
    
    //affichage
    const QString textOfAnalyse = "<html><body><font color = blue size = 3>"
          ""+trUtf8("Entre votre comptabilité et vos dépôts en banque, la différence totale est : ")+"<br/>"
          ""+trUtf8("Différence totale = ")+"</font><font color = red size = 3>"+QString::number(differenceTotal)+"</font><br/>"
          "<font color = blue size = 3>"+trUtf8("Différence espèces = ")+"</font>"+QString::number(diffCash)+"<br/>"
          "<font color = blue size = 3>"+trUtf8("Différence chèques = ")+"</font>"+QString::number(diffChecks)+"<br/>"
          "<font color = blue size = 3>"+trUtf8("Différence visa = ")+"</font>"+QString::number(diffVisa)+"<br/>"
          "<font color = blue size = 3>"+trUtf8("Différence virements = ")+"</font>"+QString::number(diffOthers)+"<br/>"
          "</body></html>";
    textEdit->setHtml(textOfAnalyse);    
    //insert into honoraire validation
    qDebug() << __FILE__ << QString::number(__LINE__) << " hashOfIdHonoNotValidated.size() =" << QString::number(hashOfIdHonoNotValidated.keys().size()) ;
    if (hashOfIdHonoNotValidated.keys().size()>1)
    {
    	QSqlQuery qHonoValidated(m_db);
        ValidDialog mess(this,m_dateBegin,m_dateEnd);
        if (mess.exec() == QDialog::Accepted)
        {
     	    QList<int> listOfReturns = mess.checksBoxesReturn();
     	    for (int i = 0; i < listOfReturns.size(); i += 1)
     	    {
     	    	QStringList listOfNotValPerType = hashOfIdHonoNotValidated.values(i);
     	    	for (int j = 0; j < listOfNotValPerType.size(); j += 1)
     	    	{
     	    		QString idHono = listOfNotValPerType[j];
     	    		const QString reqHonoValidated = QString("UPDATE %1 SET %2 = '%3' WHERE %4 = '%5'")
                                                    .arg("honoraires",
                                                         "valide",
                                                         "1",
                                                         "id_hono",
                                                         idHono);
                    if (!qHonoValidated.exec(reqHonoValidated))
                    {
         	        qWarning() << __FILE__ << QString::number(__LINE__) << qHonoValidated.lastError().text() ;
                        }
     	    	    }
     	        }
            }
         }
}