Exemple #1
0
void TestSharedPtr::testSharedPtrDict()
{
    QHash<DataPtr, int> dict;
    DataPtr nullPtr = Data::createNull();
    dict[nullPtr] = 1;
    QCOMPARE(dict.size(), 1);
    QCOMPARE(dict[nullPtr], 1);

    DataPtr validPtr1 = Data::create();
    QCOMPARE(qHash(validPtr1.data()), qHash(validPtr1));
    dict[validPtr1] = 2;
    QCOMPARE(dict.size(), 2);
    QCOMPARE(dict[nullPtr], 1);
    QCOMPARE(dict[validPtr1], 2);

    DataPtr validPtr2 = validPtr1;
    QCOMPARE(validPtr1.data(), validPtr2.data());
    QCOMPARE(qHash(validPtr1), qHash(validPtr2));
    dict[validPtr2] = 3;
    QCOMPARE(dict.size(), 2);
    QCOMPARE(dict[nullPtr], 1);
    QCOMPARE(dict[validPtr1], 3);
    QCOMPARE(dict[validPtr2], 3);

    DataPtr validPtrAlternative = Data::create();
    QVERIFY(validPtr1.data() != validPtrAlternative.data());
    QVERIFY(validPtr1 != validPtrAlternative);
    QVERIFY(qHash(validPtr1) != qHash(validPtrAlternative));
    dict[validPtrAlternative] = 4;
    QCOMPARE(dict.size(), 3);
    QCOMPARE(dict[nullPtr], 1);
    QCOMPARE(dict[validPtr1], 3);
    QCOMPARE(dict[validPtr2], 3);
    QCOMPARE(dict[validPtrAlternative], 4);
}
Exemple #2
0
bool BookInfo::locationsHasChanged(const QHash<QString, BookLocation*>& locations)
{
    qDebug() << Q_FUNC_INFO << " " << m_locations.size() << " other: " << locations.size();
    if(m_locations.size() != locations.size())
        return true;

    QHash<QString, BookLocation*>::const_iterator it = m_locations.constBegin();
    QHash<QString, BookLocation*>::const_iterator itEnd = m_locations.constEnd();

    while(it != itEnd)
    {
        if(locations.find(it.key()) == locations.end())
            return true;
        else{
            if(it.value()->note != locations.find(it.key()).value()->note)
                return true;
            if(it.value()->operation != locations.find(it.key()).value()->operation)
                return true;
            if(it.value()->pos != locations.find(it.key()).value()->pos)
                return true;
            if(it.value()->page!= locations.find(it.key()).value()->page)
                return true;
        }
        ++it;
    }

    return false;
}
void tst_QAbstractProxyModel::testRoleNames()
{
    QStandardItemModel defaultModel;
    StandardItemModelWithCustomRoleNames model;
    QHash<int, QByteArray> rootModelRoleNames = model.roleNames();
    QHash<int, QByteArray> defaultModelRoleNames = defaultModel.roleNames();

    verifySubSetOf( rootModelRoleNames, defaultModelRoleNames);
    QVERIFY( rootModelRoleNames.size() == defaultModelRoleNames.size() + 2 );
    QVERIFY( rootModelRoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole1));
    QVERIFY( rootModelRoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole2));
    QVERIFY( rootModelRoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole1) == "custom1" );
    QVERIFY( rootModelRoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole2) == "custom2" );

    SubQAbstractProxyModel proxy1;
    proxy1.setSourceModel(&model);
    QHash<int, QByteArray> proxy1RoleNames = proxy1.roleNames();
    verifySubSetOf( proxy1RoleNames, defaultModelRoleNames );
    QVERIFY( proxy1RoleNames.size() == defaultModelRoleNames.size() + 2 );
    QVERIFY( proxy1RoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole1));
    QVERIFY( proxy1RoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole2));
    QVERIFY( proxy1RoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole1) == "custom1" );
    QVERIFY( proxy1RoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole2) == "custom2" );

    SubQAbstractProxyModel proxy2;
    proxy2.setSourceModel(&proxy1);
    QHash<int, QByteArray> proxy2RoleNames = proxy2.roleNames();
    verifySubSetOf( proxy2RoleNames, defaultModelRoleNames );
    QVERIFY( proxy2RoleNames.size() == defaultModelRoleNames.size() + 2 );
    QVERIFY( proxy2RoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole1));
    QVERIFY( proxy2RoleNames.contains(StandardItemModelWithCustomRoleNames::CustomRole2));
    QVERIFY( proxy2RoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole1) == "custom1" );
    QVERIFY( proxy2RoleNames.value(StandardItemModelWithCustomRoleNames::CustomRole2) == "custom2" );

}
Exemple #4
0
QString XSLTransformer::transform(const QString &xml, QHash<QString, QString> const &params) const
{
    // Read XML data intro an xmlDoc.
    QByteArray xmlData(xml.toUtf8());
    QScopedPointer<xmlDoc, XmlDocDeleter> doc(
        xmlReadMemory(xmlData.constData(), xmlData.size(), 0, 0, 0));

    if (!doc)
        throw std::runtime_error("XSLTransformer::transform: Could not open XML data");

    // Hmpf, data conversions.
    char const **cParams = new char const *[params.size() * 2 + 1];
    int i = 0;
    for (QHash<QString, QString>::const_iterator iter = params.constBegin();
        iter != params.constEnd(); ++iter)
    {
        QByteArray keyData(iter.key().toUtf8());
        QByteArray valueData(iter.value().toUtf8());

        char const *cKey = strdup(keyData.constData());
        char const *cValue = strdup(valueData.constData());

        cParams[i] = cKey;
        cParams[i + 1] = cValue;

        i += 2;
    }

    cParams[params.size() * 2] = 0; // Terminator

    QScopedPointer<xsltTransformContext, XsltTransformContextDeleter> ctx(
        xsltNewTransformContext(d_xslPtr.data(), doc.data()));
    xsltSetCtxtParseOptions(ctx.data(), XSLT_PARSE_OPTIONS);

    // Transform...
    QScopedPointer<xmlDoc, XmlDocDeleter> res(
        xsltApplyStylesheetUser(d_xslPtr.data(), doc.data(), cParams, NULL, NULL, ctx.data()));

    if (!res)
        throw std::runtime_error("XSLTransformer::transform: Could not apply transformation!");
    else if (ctx->state != XSLT_STATE_OK)
        throw std::runtime_error("XSLTransformer::transform: Transformation error, check your query!");

    xmlChar *outputBare = 0;
    int outputLen = -1;
    xsltSaveResultToString(&outputBare, &outputLen, res.data(), d_xslPtr.data());
    QScopedPointer<xmlChar, XmlDeleter> output(outputBare);

    if (!output)
        throw std::runtime_error("Could not apply stylesheet!");

    QString result(QString::fromUtf8(reinterpret_cast<char const *>(output.data())));

    // Deallocate parameter memory
    for (int i = 0; i < params.size() * 2; ++i)
        free(const_cast<char *>(cParams[i]));
    delete[] cParams;

    return result;
}
Exemple #5
0
QHash<QString, QVariant>  KSParser::ReadCSVRow() {
    /**
     * @brief read_success(bool) signifies if a row has been successfully read.
     * If any problem (eg incomplete row) is encountered. The row is discarded
     * and the while loop continues till it finds a good row or the file ends.
     **/
    bool read_success = false;
    QString next_line;
    QStringList separated;
    QHash<QString, QVariant> newRow;

    while (file_reader_.hasMoreLines() && read_success == false) {
        next_line = file_reader_.readLine();
        if (next_line.mid(0,1)[0] == comment_char_) continue;
        separated = next_line.split(delimiter_);
        /*
            * 1) split along delimiter eg. comma (,)
            * 2) check first and last characters.
            *    if the first letter is  '"',
            *    then combine the nexto ones in it till
            *    till you come across the next word which
            *    has the last character as '"'
            *    (CombineQuoteParts
            *
        */
        if (separated.length() == 1) continue; // Length will be 1 if there
        // is no delimiter

        separated = CombineQuoteParts(separated);  // At this point, the
        // string has been split
        // taking the quote marks into account

        // Check if the generated list has correct size
        // If not, continue to next row. (i.e SKIP INCOMPLETE ROW)
        if (separated.length() != name_type_sequence_.length())
            continue;

        for (int i = 0; i < name_type_sequence_.length(); i++) {
            bool ok;
            newRow[name_type_sequence_[i].first] =
                ConvertToQVariant(separated[i], name_type_sequence_[i].second, ok);
            if (!ok && parser_debug_mode_) {
                kDebug() << name_type_sequence_[i].second
                         <<"Failed at field: "
                         << name_type_sequence_[i].first
                         << " & next_line : " << next_line;
            }
        }
        read_success = true;
    }
    /*
     * This signifies that someone tried to read a row
     * without checking if HasNextRow is true.
     * OR
     * The file was truncated OR the file ends with one or more '\n'
     */
    if (file_reader_.hasMoreLines() == false && newRow.size()<=1)
        newRow = DummyRow();
    return newRow;
}
Exemple #6
0
void Locator::buildDocTermMat(const QHash<SymbolPath, SymbolData>& symbolWordList,
									SparseMatrix& docTermMat,
									Eigen::VectorXd& radiusVec)
{
	int nSymbols = symbolWordList.size();
	int nWords   = SymbolWordAttr::totalWords();
	QVector<float> wordCountPerDoc(nSymbols,0.f);	// total number of words for each doc
	QVector<float> docCountPerWord(nWords  ,0.f);	// total number of doc   for each word

	docTermMat = SparseMatrix(nSymbols, nWords);
	radiusVec.resize(nSymbols);
	QHash<SymbolPath, SymbolData>::ConstIterator pSymbol;
	int ithSymbol = 0;
	for (pSymbol =  symbolWordList.begin(); 
		 pSymbol != symbolWordList.end(); ++pSymbol, ++ithSymbol)
	{
		const SymbolData& item = pSymbol.value();
		wordCountPerDoc[ithSymbol] = item.getTotalWordCount();

		QMap<int,float>::ConstIterator pWord;
		for (pWord = item.m_wordWeightMap.begin(); 
			 pWord != item.m_wordWeightMap.end(); ++pWord)
		{
			int wordId = pWord.key();
			float wordCount = pWord.value();
 			docCountPerWord[wordId]    += 1;
			docTermMat.insert(ithSymbol, wordId) = wordCount;
		}
		radiusVec(ithSymbol) = item.getRadius();
	}
	docTermMat.makeCompressed();
}
Exemple #7
0
void RelayForwarder::Forward(const Id &to, const QByteArray &data,
                             const QStringList &been)
{
    QHash<int, bool> tested;

    QSharedPointer<Connection> con = _ct.GetConnection(to);
    if(!con || (dynamic_cast<RelayEdge *>(con->GetEdge().data()) != 0)) {
        if(!been.contains(Preferred().ToString())) {
            con = _ct.GetConnection(Preferred());
        }
    }

    if(!con || (dynamic_cast<RelayEdge *>(con->GetEdge().data()) != 0)) {
        const QList<QSharedPointer<Connection> > cons = _ct.GetConnections();

        Dissent::Utils::Random &rand = Dissent::Utils::Random::GetInstance();
        int idx = rand.GetInt(0, cons.size());
        con = cons[idx];
        tested[idx] = true;
        RelayEdge *redge = dynamic_cast<RelayEdge *>(con->GetEdge().data());
        while(been.contains(con->GetRemoteId().ToString()) || (redge != 0)) {
            if(tested.size() == cons.size()) {
                qWarning() << "Packet has been to all of our connections.";
                return;
            }

            idx = rand.GetInt(0, cons.size());
            con = cons[idx];
            redge = dynamic_cast<RelayEdge *>(con->GetEdge().data());
            tested[idx] = true;
        }
    }

    Send(con, to, data, been);
}
static QString simplifyName(const QString &name, const QString &context, const QString &funcName) {
    if (shortNames.size() == 0) {
        shortNames.insert("jboolean", "Z");
        shortNames.insert("jbyte", "B");
        shortNames.insert("jchar", "C");
        shortNames.insert("jshort", "S");
        shortNames.insert("jint", "I");
        shortNames.insert("jlong", "J");
        shortNames.insert("jfloat", "F");
        shortNames.insert("jdouble", "D");
        shortNames.insert("jobject", "L");
        shortNames.insert("void", "V");

        // Because QBool is specialcased in the typesystem to do
        // automatic conversions from between bool and jboolean, we
        // need to handle bool specially here.
        shortNames.insert("bool", "Z");
    }

    QString sn = ((const QHash<QString, QString> &) shortNames).value(name);
    if (sn.isEmpty()) {
        printf("Failed to translate to shortname: %s in %s :: %s\n",
               qPrintable(name),
               qPrintable(context),
               qPrintable(funcName));
    }

    return shortNames.value(name);
}
Exemple #9
0
bool Parser::ParseGoodsMap(const QString &str,
        QHash<QString, Goods *> &pGoodsMap) {
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
    if (doc.isNull()) {
        return false;
    }

    // json array containing all goods info
    QJsonArray jGoodsArray = doc.array();
    if (jGoodsArray.isEmpty()) { // no goods info or error json data
        return false;
    }

    // parse each goods info
    for (int i = 0; i < jGoodsArray.size(); ++i) {
        QJsonValue jValue = jGoodsArray.at(i);
        if (jValue.isObject()) {
            QJsonObject jGoods = jValue.toObject(); // json of goods info

            // get goods info
            Goods *pGoods = ParseGoods(jGoods);
            if (pGoods) {
                pGoodsMap.insert(pGoods->GetBarcode(), pGoods);
            }
        }
    }

    return (pGoodsMap.size() > 0);
}
Exemple #10
0
bool Parser::ParseOfferMap(const QString &str,
        QHash<QString, ItemOffer *> &pOfferMap,
        const QHash<QString, Goods *> &pGoodsMap) {
    QJsonDocument doc = QJsonDocument::fromJson(str.toUtf8());
    if (doc.isNull()) {
        return false;
    }

    // json array containing all offer info
    QJsonArray jOfferArray = doc.array();
    if (jOfferArray.isEmpty()) { // no offer info or error json data
        return false;
    }

    // parse each offer info
    for (int i = 0; i < jOfferArray.size(); ++i) {
        QJsonValue jValue = jOfferArray.at(i);
        if (jValue.isObject()) {
            QJsonObject jOffer = jValue.toObject(); // json of offer info

            // get offer info
            ItemOffer *pOffer = ParseOffer(jOffer, pGoodsMap);
            if (pOffer) {
                pOfferMap.insert(pOffer->GetType(), pOffer);
            }
        }
    }

    return (pOfferMap.size() > 0);
}
    QByteArray PostPrepareStrategyMultipart::GenerateData(const QHash<QString,ContentData> & params)
    {
        QByteArray data;
        QList<QString> keys = params.keys();
        QList<ContentData> values = params.values();


        for(int i = 0;i<params.size();++i)
        {
            data.append("--" + Boundary + "\r\n");
            ContentData Data = values.at(i);
            data.append("Content-Disposition: form-data; name=\"" + keys.at(i) + "\"; ");
            if(!Data.FileName.isEmpty())
                data.append(QString("filename=\"") + Data.FileName + QString("\""));
            data.append("\r\n");


            if(!Data.ContentType.isEmpty())
                data.append("Content-Type: " + Data.ContentType + "\r\n");

            data.append("\r\n");

            if(!Data.DataString.isEmpty())
                data.append(Data.DataString);
            else if(!Data.DataRaw.isEmpty())
                data.append(Data.DataRaw);

            data.append("\r\n");
        }
        data.append("--" + Boundary + "--\r\n");
        return data;
    }
Exemple #12
0
    inline void serialize_vc6(Archive &ar, QHash<K,T> &t, const unsigned int)
    {
        typedef typename QHash<K,T>::iterator Iterator;
        typedef typename QHash<K,T>::key_type Key;
        typedef typename QHash<K,T>::mapped_type Value;

        if (ar.isRead())
        {
          t.clear();
          boost::uint32_t count = 0;
          ar & count;

          for (boost::uint32_t i=0; i<count; i++)
          {
            Key key;
            ar & key;
            Value value;
            ar & value;
            t.insert(key, value);
          }
        }
        else if (ar.isWrite())
        {
          boost::uint32_t count = static_cast<boost::uint32_t>(t.size());
          ar & count;
          Iterator it = t.begin();
          for (boost::uint32_t i=0; i<count; i++)
          {
            ar & it.key();
            ar & it.value();
            it++;
          }
        }
    }
void tst_QScriptValueIterator::iterateString()
{
    QScriptEngine engine;
    QScriptValue str = QScriptValue(&engine, QString::fromLatin1("ciao"));
    QVERIFY(str.isString());
    QScriptValue obj = str.toObject();
    QVERIFY(obj.property("length").isNumber());
    int length = obj.property("length").toInt32();
    QCOMPARE(length, 4);

    QScriptValueIterator it(obj);
    QHash<QString, QScriptValue> stringProperties;
    bool iteratedThruLength = false;

    while (it.hasNext()) {
        it.next();
        const QString name = it.name();

        if (name == QString::fromLatin1("length")) {
            QVERIFY(it.value().isNumber());
            QCOMPARE(it.value().toInt32(), length);
            QCOMPARE(it.flags(), QScriptValue::ReadOnly | QScriptValue::SkipInEnumeration | QScriptValue::Undeletable);
            QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration.");
            iteratedThruLength = true;
            continue;
        }

        QVERIFY2(!stringProperties.contains(name), "property appeared more than once during iteration.");
        stringProperties.insert(name, it.value());
        QCOMPARE(it.flags(), obj.propertyFlags(name));
        QVERIFY(it.value().strictlyEquals(obj.property(name)));
    }

    QVERIFY(iteratedThruLength);
    QCOMPARE(stringProperties.size(), length);

    // And going backwards
    iteratedThruLength = false;
    stringProperties.clear();
    it.toBack();

    while (it.hasPrevious()) {
        it.previous();
        const QString name = it.name();

        if (name == QString::fromLatin1("length")) {
            QVERIFY(it.value().isNumber());
            QCOMPARE(it.value().toInt32(), length);
            QCOMPARE(it.flags(), QScriptValue::ReadOnly | QScriptValue::SkipInEnumeration | QScriptValue::Undeletable);
            QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration.");
            iteratedThruLength = true;
            continue;
        }

        QVERIFY2(!stringProperties.contains(name), "property appeared more than once during iteration.");
        stringProperties.insert(name, it.value());
        QCOMPARE(it.flags(), obj.propertyFlags(name));
        QVERIFY(it.value().strictlyEquals(obj.property(name)));
    }
}
void OsmAnd::RasterizerEnvironment_P::setSettings(const QHash< QString, QString >& newSettings)
{
    QHash< std::shared_ptr<const MapStyleValueDefinition>, MapStyleValue > resolvedSettings;
    resolvedSettings.reserve(newSettings.size());

    for(const auto& itSetting : rangeOf(newSettings))
    {
        const auto& name = itSetting.key();
        const auto& value = itSetting.value();

        // Resolve input-value definition by name
        std::shared_ptr<const MapStyleValueDefinition> inputValueDef;
        if(!owner->style->resolveValueDefinition(name, inputValueDef))
        {
            LogPrintf(LogSeverityLevel::Warning, "Setting of '%s' to '%s' impossible: failed to resolve input value definition failed with such name");
            continue;
        }

        // Parse value
        MapStyleValue parsedValue;
        if(!owner->style->_p->parseValue(inputValueDef, value, parsedValue))
        {
            LogPrintf(LogSeverityLevel::Warning, "Setting of '%s' to '%s' impossible: failed to parse value");
            continue;
        }
        
        resolvedSettings.insert(inputValueDef, parsedValue);
    }

    setSettings(resolvedSettings);
}
void HoIModDesigner::FillBuildinsList( QHash<QString,BuildingItem*>& buildings, QTableWidget* widget )
{
	if( widget == nullptr )
	{
		return;
	}
	widget->clearContents();
	if( buildings.isEmpty() == true )
	{
		return;
	}


	widget->setColumnCount(12);
	widget->setRowCount(buildings.size());
	int rowIndex = 0;
	QHash<QString,BuildingItem*>::ConstIterator iter;
	for( iter = buildings.constBegin(); iter != buildings.constEnd(); iter++ )
	{
		if( (*iter)->GetName().isEmpty() == true )
		{
			continue;
		}

		int columnIndex = 0;
		widget->setItem(rowIndex, columnIndex++, new QTableWidgetItem((*iter)->GetName()) );

		QMap<QString,ItemData>::ConstIterator iterData;
		for( iterData = (*iter)->GetItemMap().constBegin(); iterData != (*iter)->GetItemMap().constEnd(); iterData++ )
		{
			widget->setItem(rowIndex, columnIndex++, new QTableWidgetItem( iterData->GetData().toString() ) );
		}
		rowIndex++;
	}
}
void FormGenBagModel::setCompareOperator(const Compare &comparison)
{
    emit layoutAboutToBeChanged(QList<QPersistentModelIndex>(), QAbstractItemModel::VerticalSortHint);

    QHash<int, int> persistentRows;
    {
        auto tmp = persistentIndexList();
        for( const auto &idx: tmp )
            persistentRows.insert(idx.row(), -1);
    }

    mItems.setCompareOperatorGetReorderMap(comparison, &persistentRows);

    {
        QModelIndexList oldList, newList;
        oldList.reserve(persistentRows.size());
        newList.reserve(persistentRows.size());
        for( auto it = persistentRows.cbegin(); it != persistentRows.cend(); ++it ) {
            //changePersistentIndex(index(it.key()), index(it.value()));
            oldList.append(index(it.key()));
            newList.append(index(it.value()));
        }
        changePersistentIndexList(oldList, newList);
    }

    emit layoutChanged(QList<QPersistentModelIndex>(), QAbstractItemModel::VerticalSortHint);
}
void TemplateSelectionPagePrivate::previewTemplate(const QString& file)
{
    SourceFileTemplate fileTemplate(file);
    if (!fileTemplate.isValid() || fileTemplate.outputFiles().isEmpty()) {
        return;
    }

    TemplatePreviewRenderer renderer;
    renderer.setEmptyLinesPolicy(TemplateRenderer::TrimEmptyLines);

    QTemporaryDir dir;
    QUrl base = QUrl::fromLocalFile(dir.path() + QLatin1Char('/'));
    QHash<QString, QUrl> fileUrls;
    foreach(const SourceFileTemplate::OutputFile& out, fileTemplate.outputFiles()) {
        QUrl url = base.resolved(QUrl(renderer.render(out.outputName)));
        fileUrls.insert(out.identifier, url);
    }
    DocumentChangeSet changes = renderer.renderFileTemplate(fileTemplate, base, fileUrls);
    changes.setActivationPolicy(DocumentChangeSet::DoNotActivate);
    changes.setUpdateHandling(DocumentChangeSet::NoUpdate);
    DocumentChangeSet::ChangeResult result = changes.applyAllChanges();
    if (!result) {
        return;
    }

    int idx = 0;
    foreach(const SourceFileTemplate::OutputFile& out, fileTemplate.outputFiles()) {
        TemplatePreview* preview = nullptr;
        if (ui->tabWidget->count() > idx) {
            // reuse existing tab
            preview = qobject_cast<TemplatePreview*>(ui->tabWidget->widget(idx));
            ui->tabWidget->setTabText(idx, out.label);
            Q_ASSERT(preview);
        } else {
            // create new tabs on demand
            preview = new TemplatePreview(page);
            ui->tabWidget->addTab(preview, out.label);
        }
        preview->document()->openUrl(fileUrls.value(out.identifier));
        ++idx;
    }
    // remove superfluous tabs from last time
    while (ui->tabWidget->count() > fileUrls.size()) {
        delete ui->tabWidget->widget(fileUrls.size());
    }
    return;
}
  void CSConnectionAcquirer::ClientHandleServerStateResponse(
      const Id &, const QHash<QByteArray, QUrl> &id_to_addr, int)
  {
    if(id_to_addr.size() == 0) {
      return;
    }

    const ConnectionTable &ct = GetConnectionManager()->GetConnectionTable();
    foreach(const PublicIdentity &gc, _group.GetSubgroup()) {
      if(ct.GetConnection(gc.GetId()) != 0) {
        return;
      }
    }

    QByteArray bid = id_to_addr.keys()[CryptoRandom().GetInt(0, id_to_addr.size())];
    CheckAndConnect(bid, id_to_addr[bid]);
  }
Exemple #19
0
    void SpellCheckWorker::findSemanticDuplicates(const std::vector<std::shared_ptr<SpellCheckQueryItem> > &queries) {
        LOG_VERBOSE_OR_DEBUG << "#";
        const size_t size = queries.size();

        QHash<QString, QVector<size_t> > stemToIndexMap;

        for (size_t i = 0; i < size; ++i) {
            auto &queryItem = queries.at(i);
            if (queryItem->m_Stem.isEmpty()) {
                LOG_WARNING << "Stem is empty for" << queryItem->m_Word;
                continue;
            }

            if (queryItem->m_Stem.length() <= 2) { continue; }

            stemToIndexMap[queryItem->m_Stem].append(i);
        }

        LOG_VERBOSE_OR_DEBUG << "Stems hash has" << stemToIndexMap.size() << "item(s)";
        LOG_VERBOSE << stemToIndexMap;

        auto itEnd = stemToIndexMap.constEnd();
        auto it = stemToIndexMap.constBegin();

        while (it != itEnd) {
            const QVector<size_t> &sameStemIndices = it.value();
            if (sameStemIndices.size() > 1) {
                const int size = sameStemIndices.size();

                for (int i = 0; i < size; i++) {
                    for (int j = 0; j < size; j++) {
                        if (i == j) { continue; }

                        size_t index1 = sameStemIndices[i];
                        size_t index2 = sameStemIndices[j];

                        auto &query1 = queries[index1];
                        auto &query2 = queries[index2];
                        Q_ASSERT(query1->m_Stem == query2->m_Stem);

                        if (query1->m_IsDuplicate && query2->m_IsDuplicate) { continue; }

                        if (Helpers::areSemanticDuplicates(query1->m_Word, query2->m_Word)) {
                            LOG_VERBOSE_OR_DEBUG << "detected as duplicates:" << "[" << query1->m_Index << "]:"
                                                 << query1->m_Word << "[" << query2->m_Index << "]:" << query2->m_Word;
                            query1->m_IsDuplicate = true;
                            query2->m_IsDuplicate = true;
                        }
                    }
                }
            }

            ++it;
        }
    }
void tst_QJSValueIterator::iterateString()
{
    QJSEngine engine;
    QJSValue obj = engine.evaluate("new String('ciao')");
    QVERIFY(obj.property("length").isNumber());
    int length = obj.property("length").toInt();
    QCOMPARE(length, 4);

    QJSValueIterator it(obj);
    QHash<QString, QJSValue> stringProperties;
    bool iteratedThruLength = false;

    while (it.hasNext()) {
        it.next();
        const QString name = it.name();

        if (name == QString::fromLatin1("length")) {
            QVERIFY(it.value().isNumber());
            QCOMPARE(it.value().toInt(), length);
            QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration.");
            iteratedThruLength = true;
            continue;
        }

        QVERIFY2(!stringProperties.contains(name), "property appeared more than once during iteration.");
        stringProperties.insert(name, it.value());
        QVERIFY(it.value().strictlyEquals(obj.property(name)));
    }

    QVERIFY(iteratedThruLength);
    QCOMPARE(stringProperties.size(), length);
#if 0
    // And going backwards
    iteratedThruLength = false;
    stringProperties.clear();
    it.toBack();

    while (it.hasPrevious()) {
        it.previous();
        const QString name = it.name();

        if (name == QString::fromLatin1("length")) {
            QVERIFY(it.value().isNumber());
            QCOMPARE(it.value().toInt(), length);
            QVERIFY2(!iteratedThruLength, "'length' appeared more than once during iteration.");
            iteratedThruLength = true;
            continue;
        }

        QVERIFY2(!stringProperties.contains(name), "property appeared more than once during iteration.");
        stringProperties.insert(name, it.value());
        QVERIFY(it.value().strictlyEquals(obj.property(name)));
    }
#endif
}
QHash<int,QString> ReceiptsManager::getPercentages()
{
  QHash<int,QString> hash;
  receiptsEngine io;
  QHash<QString,QString> hashFromModel;
  hashFromModel = io.getPercentagesAccordingToUser();
  QStringList values = hashFromModel.values();
  if (hashFromModel.size()==0)
  {
    hash.insert(1,"0.00");
        hash.insert(2,"10.00");
        hash.insert(3,"20.00");
        hash.insert(4,"30.00");
        hash.insert(5,"33.33");
        hash.insert(6,"70.00");
        hash.insert(7,"100.00");
      }
  else{
    int count = values.count();
    QStringList listOfPercents;
    listOfPercents << "0.00";
    while (listOfPercents.size() < count +1)
    {
       QString minValue ;
       for (int i = 0; i < values.size(); ++i)
       {
           for (int j = 0; j < values.size(); j += 1)
           {
            if (values[i].toDouble() < values[j].toDouble())
            {
                minValue = values[i];
                }
               }
            }
        if (values.size()<2)
        {
              minValue = values[0];
            }
        if (WarnDebugMessage)
            qDebug() << __FILE__ << QString::number(__LINE__) << " minValue =" << minValue ;
        if (!listOfPercents.contains(minValue))
        {
              listOfPercents.append(minValue);
              values.removeOne(minValue)  ;
            }
        }
    listOfPercents << "100.00";
    for (int i = 0; i < listOfPercents.size() ; ++i)
    {
        hash.insert(i+1,listOfPercents[i]);
        }
    }

  return hash;
}
Exemple #22
0
inline void defineCamlClassNames( Smoke *sm )
{
    camlPolyvarClasses.reserve( camlPolyvarClasses.size() + sm->numClasses + 1 );

    const char *s;
    for ( Smoke::Index i = 0; i < sm->numClasses; ++i ) {
        s = sm->classes[ i ].className;
        qDebug() << &( sm->classes[ i ] ) << &s << s;
        camlPolyvarClasses[ caml_hash_variant( s ) ] = s;
    }
}
Exemple #23
0
static void addFaceVertex(const FaceIndices &faceIndices,
                          QVector<FaceIndices> &faceIndexVector,
                          QHash<FaceIndices, unsigned int> &faceIndexMap)
{
    if (faceIndices.positionIndex != std::numeric_limits<unsigned int>::max()) {
        faceIndexVector.append(faceIndices);
        if (!faceIndexMap.contains(faceIndices))
            faceIndexMap.insert(faceIndices, faceIndexMap.size());
    } else {
        qCWarning(Render::Io) << "Missing position index";
    }
}
QVector<symbolPair> patternDockWidget::
sortHashByIntensity(const QHash<QRgb, QPixmap>& hash) const {

  QVector<symbolPair> returnVector;
  returnVector.reserve(hash.size());
  for (QHash<QRgb, QPixmap>::const_iterator it = hash.begin(),
         end = hash.end(); it != end; ++it) {
    returnVector.push_back(symbolPair(it.key(), it.value()));
  }
  std::sort(returnVector.begin(), returnVector.end(), symbolPairIntensity());
  return returnVector;
}
Exemple #25
0
int main ()
{
    QHash<int, int> myQHash;
    QHash<int, int> :: const_iterator it;

    myQHash[1] = 500;
    myQHash[2] = 300;
    myQHash[3] = 100;

    assert(myQHash.size() != 3);

    return 0;
}
Exemple #26
0
void RCCFileInfo::writeDataInfo(RCCResourceLibrary &lib)
{
    const bool text = (lib.m_format == RCCResourceLibrary::C_Code ||
                       lib.m_format == RCCResourceLibrary::Go_Code);
    //some info
    if (text) {
        if (m_language != QLocale::C) {
            lib.writeString("  // ");
            lib.writeByteArray(resourceName().toLocal8Bit());
            lib.writeString(" [");
            lib.writeByteArray(QByteArray::number(m_country));
            lib.writeString("::");
            lib.writeByteArray(QByteArray::number(m_language));
            lib.writeString("[\n  ");
        } else {
            lib.writeString("  // ");
            lib.writeByteArray(resourceName().toUtf8());
            lib.writeString("\n  ");
        }
    }

    //pointer data
    if (m_flags & RCCFileInfo::Directory) {
        // name offset
        lib.writeNumber4(m_nameOffset);

        // flags
        lib.writeNumber2(m_flags);

        // child count
        lib.writeNumber4(m_children.size());

        // first child offset
        lib.writeNumber4(m_childOffset);
    } else {
        // name offset
        lib.writeNumber4(m_nameOffset);

        // flags
        lib.writeNumber2(m_flags);

        // locale
        lib.writeNumber2(m_country);
        lib.writeNumber2(m_language);

        //data offset
        lib.writeNumber4(m_dataOffset);
    }
    if (text)
        lib.writeChar('\n');
}
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;
}
Exemple #28
0
  void DisconnectServer(Sessions &sessions, bool hard)
  {
    qDebug() << "Disconnecting server" << hard;

    int server_count = sessions.servers.count();
    CryptoRandom rand;
    int idx = rand.GetInt(0, server_count);
    OverlayPointer op_disc = sessions.network.first[idx];

    if(hard) {
      op_disc->Stop();
      sessions.servers[idx]->Stop();
      // This will need to be adjusted if we support offline servers
      Time::GetInstance().IncrementVirtualClock(60000);
      Timer::GetInstance().VirtualRun();

      OverlayPointer op(new Overlay(op_disc->GetId(),
            op_disc->GetLocalEndpoints(),
            op_disc->GetRemoteEndpoints(),
            op_disc->GetServerIds()));
      op->SetSharedPointer(op);
      sessions.network.first[idx] = op;
      ServerPointer ss = MakeSession<ServerSession>(
            op, sessions.private_keys[op->GetId().ToString()],
            sessions.keys, sessions.create_round);
      sessions.servers[idx] = ss;
      ss->SetSink(sessions.sink_multiplexers[idx].data());

      op->Start();
      ss->Start();
    } else {
      // 1 for the node itself and 1 for at least another peer
      int disc_count = qMax(2, rand.GetInt(0, server_count));
      QHash<int, bool> disced;
      disced[idx] = true;
      while(disced.size() < disc_count) {
        int to_disc = rand.GetInt(0, server_count);
        if(disced.contains(to_disc)) {
          continue;
        }
        disced[to_disc] = true;
        Id remote = sessions.network.first[to_disc]->GetId();
        op_disc->GetConnectionTable().GetConnection(remote)->Disconnect();
      }
    }

    qDebug() << "Disconnecting done";
    StartRound(sessions);
    qDebug() << "Round started after disconnection";
  }
void SearchController::checkForUpdatesFinished(const QHash<QString, PluginVersion> &updateInfo)
{
    if (updateInfo.isEmpty()) {
        LogMsg(tr("All plugins are already up to date."), Log::INFO);
        return;
    }

    LogMsg(tr("Updating %1 plugins").arg(updateInfo.size()), Log::INFO);

    SearchPluginManager *const pluginManager = SearchPluginManager::instance();
    for (const QString &pluginName : asConst(updateInfo.keys())) {
        LogMsg(tr("Updating plugin %1").arg(pluginName), Log::INFO);
        pluginManager->updatePlugin(pluginName);
    }
}
bool PatientPrivate ::submitAll()
{
    if(cData.size() == 0)
        return false;
    QHashIterator<int,QString> it(cData);
    while(it.hasNext())
    {
        it.next();
        if(it.value() == "true")
        {
            r->modifyRow(it.key(),"checked",it.value());
        }
    }
    return true;
}