Пример #1
0
QList<QMultiMap<QString, QString> > SqlManager::convertToXML(QSqlQuery requete){
    QStringList champs, booleanFields;
    QList<QMultiMap<QString, QString> > data;
    QMap<QString, QString> conversion;
    conversion.insert("sous_titres", "sousTitres");
    conversion.insert("titre_original", "titreOriginal");
    conversion.insert("jaquette", "couverture");
    conversion.insert("nom_editeur", "editeur");
    conversion.insert("nom", "auteur");

    booleanFields << "empruntable" << "prete" << "vu" << "lu" << "fichier" << "ebook";

    for(int i=0; i<requete.record().count(); ++i){
        champs.append(requete.record().fieldName(i));
    }

    while(requete.next()){ //Parcours des résultats
        QMultiMap<QString, QString> item;
        for(int i=0; i<champs.count(); ++i){ //Parcours des champs
            if(booleanFields.contains(champs.at(i)))
                item.insert(champs.at(i), ((requete.record().value(champs.at(i)).toBool()) ? "True" : "False"));
            else{
                if(conversion.contains(champs.at(i))){
                    item.insert(conversion.value(champs.at(i)), ToolsManager::stripSlashes(requete.record().value(champs.at(i)).toString()));
                }
                else{
                    item.insert(champs.at(i), ToolsManager::stripSlashes(requete.record().value(champs.at(i)).toString()));
                }
            }
        }
        data.append(item);
    }
    return data;
}
Пример #2
0
void testQMultiMap()
{
    QMultiMap<uint, float> gg0;
    gg0.insert(11, 11.0);
    gg0.insert(22, 22.0);
    gg0.insert(22, 33.0);
    gg0.insert(22, 34.0);
    gg0.insert(22, 35.0);
    gg0.insert(22, 36.0);
#if 1
    QMultiMap<QString, float> gg1;
    gg1.insert("22.0", 22.0);

    QMultiMap<int, QString> gg2;
    gg2.insert(22, "22.0");

    QMultiMap<QString, Foo> gg3;
    gg3.insert("22.0", Foo(22));
    gg3.insert("33.0", Foo(33));
    gg3.insert("22.0", Foo(22));

    QObject ob;
    QMultiMap<QString, QPointer<QObject> > map;
    map.insert("Hallo", QPointer<QObject>(&ob));
    map.insert("Welt", QPointer<QObject>(&ob));
    map.insert(".", QPointer<QObject>(&ob));
    map.insert(".", QPointer<QObject>(&ob));
#endif
}
Пример #3
0
static void fillFilePathsRecursive(const QDir& dir, QMultiMap<QByteArray, QByteArray>& sourceFilePaths)
{
    QStringList subDirs(dir.entryList(QDir::Dirs|QDir::NoDotAndDotDot|QDir::Readable));
    int i=subDirs.size();
    while(--i>=0)
        fillFilePathsRecursive(QDir(dir.filePath(subDirs.at(i))),sourceFilePaths);

    static QStringList filters = QStringList(QStringLiteral("*.cpp"))
                                           <<QStringLiteral("*.c")
                                           <<QStringLiteral("*.cc")
                                           <<QStringLiteral("*.mm")
                                           <<QStringLiteral("*.ui")
                                           <<QStringLiteral("*rc");
    QStringList files(dir.entryList(filters, QDir::Files|QDir::NoDotAndDotDot|QDir::Readable));
    i=files.size();

    QByteArray absDirPath=dir.absolutePath().toUtf8(); absDirPath.squeeze();
    while(--i>=0)
    {
        //qDebug()<<files.at(i)<<absDirPath;
        QByteArray fn=files.at(i).toUtf8(); fn.squeeze();
        auto it=sourceFilePaths.constFind(fn);
        if (it!=sourceFilePaths.constEnd())
            sourceFilePaths.insert(it.key(), absDirPath); //avoid having identical qbytearray objects to save memory
        else
            sourceFilePaths.insert(fn, absDirPath);
    }
}
Пример #4
0
/*!
  Returns the list of alternative subject names for this
  certificate. The alternate subject names typically contain host
  names, optionally with wildcards, that are valid for this
  certificate.
  
  These names are tested against the connected peer's host name, if
  either the subject information for \l CommonName doesn't define a
  valid host name, or the subject info name doesn't match the peer's
  host name.
  
  \sa subjectInfo()
*/
QMultiMap<QSsl::AlternateNameEntryType, QString> QSslCertificate::alternateSubjectNames() const
{
    QMultiMap<QSsl::AlternateNameEntryType, QString> result;

    if (!d->x509)
        return result;

    STACK *altNames = (STACK *)q_X509_get_ext_d2i(d->x509, NID_subject_alt_name, 0, 0);

    if (altNames) {
        for (int i = 0; i < q_sk_GENERAL_NAME_num(altNames); ++i) {
            const GENERAL_NAME *genName = q_sk_GENERAL_NAME_value(altNames, i);
            if (genName->type != GEN_DNS && genName->type != GEN_EMAIL)
                continue;

            int len = q_ASN1_STRING_length(genName->d.ia5);
            if (len < 0 || len >= 8192) {
                // broken name
                continue;
            }

            const char *altNameStr = reinterpret_cast<const char *>(q_ASN1_STRING_data(genName->d.ia5));
            const QString altName = QLatin1String(QByteArray(altNameStr, len));
            if (genName->type == GEN_DNS)
                result.insert(QSsl::DnsEntry, altName);
            else if (genName->type == GEN_EMAIL)
                result.insert(QSsl::EmailEntry, altName);
        }
        q_sk_free(altNames);
    }

    return result;
}
Пример #5
0
void CAllStockWidget::setSortType( RSortType _st )
{
    QList<CStockInfoItem*> list = CDataEngine::getDataEngine()->getStockInfoList();

    switch(_st)
    {
    case SortByZGB:
    {
        QMultiMap<float,CStockInfoItem*> mapSort;
        foreach(CStockInfoItem* pItem,list)
        {
            mapSort.insert(pItem->getZGB(),pItem);
        }
        list = mapSort.values();
    }
    break;
    case SortByCode:
    {
        QMultiMap<QString,CStockInfoItem*> mapSort;
        foreach(CStockInfoItem* pItem,list)
        {
            mapSort.insert(pItem->getCode(),pItem);
        }
        list = mapSort.values();
    }
Пример #6
0
void PlaylistModel::sort(int column, Qt::SortOrder order)
{
    if (m_tracks.count() < 2)
    {
        return;
    }

    QMultiMap<QString, KUrl> keyMap;
    QMultiMap<qint64, KUrl> durationMap;
    KUrl::List tracks;
    const KUrl url = m_tracks.value(m_currentTrack);

    if (column == DurationColumn)
    {
        for (int i = 0; i < m_tracks.count(); ++i)
        {
            durationMap.insert(MetaDataManager::duration(m_tracks.at(i)), m_tracks.at(i));
        }

        tracks = durationMap.values();
    }
    else if (column > FileNameColumn && column < DurationColumn)
    {
        const MetaDataKey key = translateColumn(column);

        for (int i = 0; i < m_tracks.count(); ++i)
        {
            keyMap.insert(MetaDataManager::metaData(m_tracks.at(i), key), m_tracks.at(i));
        }

        tracks = keyMap.values();
    }
    else
    {
        for (int i = 0; i < m_tracks.count(); ++i)
        {
            keyMap.insert(m_tracks.at(i).pathOrUrl(), m_tracks.at(i));
        }

        tracks = keyMap.values();
    }

    if (order == Qt::AscendingOrder)
    {
        KUrl::List items;

        for (int i = (tracks.count() - 1); i >= 0; --i)
        {
            items.append(tracks.at(i));
        }

        tracks = items;
    }

    m_tracks = tracks;

    setCurrentTrack(findTrack(url));

    emit tracksChanged();
}
Пример #7
0
void Device::reloadPlugins()
{
    QHash<QString, KdeConnectPlugin*> newPluginMap;
    QMultiMap<QString, KdeConnectPlugin*> newPluginsByIncomingInterface;
    QMultiMap<QString, KdeConnectPlugin*> newPluginsByOutgoingInterface;
    QSet<QString> supportedIncomingInterfaces;
    QSet<QString> supportedOutgoingInterfaces;
    QStringList unsupportedPlugins;

    if (isPaired() && isReachable()) { //Do not load any plugin for unpaired devices, nor useless loading them for unreachable devices

        KConfigGroup pluginStates = KSharedConfig::openConfig(pluginsConfigFile())->group("Plugins");

        PluginLoader* loader = PluginLoader::instance();
        const bool deviceSupportsCapabilities = !m_incomingCapabilities.isEmpty() || !m_outgoingCapabilities.isEmpty();

        foreach (const QString& pluginName, loader->getPluginList()) {
            const KPluginMetaData service = loader->getPluginInfo(pluginName);
            const QSet<QString> incomingInterfaces = KPluginMetaData::readStringList(service.rawData(), "X-KdeConnect-SupportedPackageType").toSet();
            const QSet<QString> outgoingInterfaces = KPluginMetaData::readStringList(service.rawData(), "X-KdeConnect-OutgoingPackageType").toSet();

            const bool pluginEnabled = isPluginEnabled(pluginName);

            if (pluginEnabled) {
                supportedIncomingInterfaces += incomingInterfaces;
                supportedOutgoingInterfaces += outgoingInterfaces;
            }

            //If we don't find intersection with the received on one end and the sent on the other, we don't
            //let the plugin stay
            //Also, if no capabilities are specified on the other end, we don't apply this optimizaton, as
            //we assume that the other client doesn't know about capabilities.
            const bool capabilitiesSupported = deviceSupportsCapabilities && (!incomingInterfaces.isEmpty() || !outgoingInterfaces.isEmpty());
            if (capabilitiesSupported
                && (m_incomingCapabilities & outgoingInterfaces).isEmpty()
                && (m_outgoingCapabilities & incomingInterfaces).isEmpty()
            ) {
                qCWarning(KDECONNECT_CORE) << "not loading " << pluginName << "because of unmatched capabilities";
                unsupportedPlugins.append(pluginName);
                continue;
            }

            if (pluginEnabled) {
                KdeConnectPlugin* plugin = m_plugins.take(pluginName);

                if (!plugin) {
                    plugin = loader->instantiatePluginForDevice(pluginName, this);
                }

                foreach(const QString& interface, incomingInterfaces) {
                    newPluginsByIncomingInterface.insert(interface, plugin);
                }
                foreach(const QString& interface, outgoingInterfaces) {
                    newPluginsByOutgoingInterface.insert(interface, plugin);
                }

                newPluginMap[pluginName] = plugin;
            }
Пример #8
0
bool LimitedNodeList::packetVersionAndHashMatch(const QByteArray& packet) {
    PacketType checkType = packetTypeForPacket(packet);
    int numPacketTypeBytes = numBytesArithmeticCodingFromBuffer(packet.data());

    if (packet[numPacketTypeBytes] != versionForPacketType(checkType)
            && checkType != PacketTypeStunResponse) {
        PacketType mismatchType = packetTypeForPacket(packet);

        static QMultiMap<QUuid, PacketType> versionDebugSuppressMap;

        QUuid senderUUID = uuidFromPacketHeader(packet);
        if (!versionDebugSuppressMap.contains(senderUUID, checkType)) {
            qCDebug(networking) << "Packet version mismatch on" << packetTypeForPacket(packet) << "- Sender"
                                << uuidFromPacketHeader(packet) << "sent" << qPrintable(QString::number(packet[numPacketTypeBytes])) << "but"
                                << qPrintable(QString::number(versionForPacketType(mismatchType))) << "expected.";

            emit packetVersionMismatch();

            versionDebugSuppressMap.insert(senderUUID, checkType);
        }

        return false;
    }

    if (!NON_VERIFIED_PACKETS.contains(checkType)) {
        // figure out which node this is from
        SharedNodePointer sendingNode = sendingNodeForPacket(packet);
        if (sendingNode) {
            // check if the md5 hash in the header matches the hash we would expect
            if (hashFromPacketHeader(packet) == hashForPacketAndConnectionUUID(packet, sendingNode->getConnectionSecret())) {
                return true;
            } else {
                static QMultiMap<QUuid, PacketType> hashDebugSuppressMap;

                QUuid senderUUID = uuidFromPacketHeader(packet);
                if (!hashDebugSuppressMap.contains(senderUUID, checkType)) {
                    qCDebug(networking) << "Packet hash mismatch on" << checkType << "- Sender"
                                        << uuidFromPacketHeader(packet);

                    hashDebugSuppressMap.insert(senderUUID, checkType);
                }
            }
        } else {
            static QString repeatedMessage
                = LogHandler::getInstance().addRepeatedMessageRegex("Packet of type \\d+ received from unknown node with UUID");

            qCDebug(networking) << "Packet of type" << checkType << "received from unknown node with UUID"
                                << qPrintable(uuidStringWithoutCurlyBraces(uuidFromPacketHeader(packet)));
        }
    } else {
        return true;
    }

    return false;
}
Пример #9
0
void Device::reloadPlugins()
{
    QHash<QString, KdeConnectPlugin*> newPluginMap;
    QMultiMap<QString, KdeConnectPlugin*> newPluginsByIncomingInterface;
    QMultiMap<QString, KdeConnectPlugin*> newPluginsByOutgoingInterface;

    if (isPaired() && isReachable()) { //Do not load any plugin for unpaired devices, nor useless loading them for unreachable devices

        KConfigGroup pluginStates = KSharedConfig::openConfig(pluginsConfigFile())->group("Plugins");

        PluginLoader* loader = PluginLoader::instance();

        //Code borrowed from KWin
        foreach (const QString& pluginName, loader->getPluginList()) {
            QString enabledKey = pluginName + QString::fromLatin1("Enabled");

            bool isPluginEnabled = (pluginStates.hasKey(enabledKey) ? pluginStates.readEntry(enabledKey, false)
                                                            : loader->getPluginInfo(pluginName).isEnabledByDefault());

            if (isPluginEnabled) {
                KdeConnectPlugin* plugin = m_plugins.take(pluginName);
                QStringList incomingInterfaces, outgoingInterfaces;
                if (plugin) {
                    incomingInterfaces = m_pluginsByIncomingInterface.keys(plugin);
                    outgoingInterfaces = m_pluginsByOutgoingInterface.keys(plugin);
                } else {
                    const KPluginMetaData service = loader->getPluginInfo(pluginName);
                    incomingInterfaces = KPluginMetaData::readStringList(service.rawData(), "X-KdeConnect-SupportedPackageType");
                    outgoingInterfaces = KPluginMetaData::readStringList(service.rawData(), "X-KdeConnect-OutgoingPackageType");
                }

                //If we don't find intersection with the received on one end and the sent on the other, we don't
                //let the plugin stay
                //Also, if no capabilities are specified on the other end, we don't apply this optimizaton, as
                //we assume that the other client doesn't know about capabilities.
                if (!m_incomingCapabilities.isEmpty() && !m_outgoingCapabilities.isEmpty()
                    && (m_incomingCapabilities & outgoingInterfaces.toSet()).isEmpty()
                    && (m_outgoingCapabilities & incomingInterfaces.toSet()).isEmpty()
                ) {
                    delete plugin;
                    continue;
                }

                if (!plugin) {
                    plugin = loader->instantiatePluginForDevice(pluginName, this);
                }

                foreach(const QString& interface, incomingInterfaces) {
                    newPluginsByIncomingInterface.insert(interface, plugin);
                }
                foreach(const QString& interface, outgoingInterfaces) {
                    newPluginsByOutgoingInterface.insert(interface, plugin);
                }
                newPluginMap[pluginName] = plugin;
            }
Пример #10
0
void ThesaurusDatabaseType::load(QFile& file){
	REQUIRE(!buffer); //only call it once
	
	QTextStream stream(&file);
	QString line;
	QStringRef key;
	line = stream.readLine();
	stream.setCodec(qPrintable(line));
	buffer = new QString();
	buffer->reserve(file.size());
	do {
		int currentBufferLength = buffer->length();
		line = stream.readLine();
		int firstSplitter = line.indexOf('|');
        if (firstSplitter >= 0) {
            if (line.startsWith("-|") || line.startsWith("(") || line.startsWith("|")){
				buffer->append(line.mid(firstSplitter+1));
				thesaurus.insert(key, ThesaurusDatabaseType::TinyStringRef(currentBufferLength, buffer->length() - currentBufferLength));
				//using TinyStringRef instead of QString reduces the memory usage (with German thesaurus) by 4mb without any noticable performance decrease (it could even be faster, because the buffer fits better in the cache).

				//TODO: do something something that word type is included in key and still correct search is possible
			} else {
				buffer->append(line.left(firstSplitter));
				key = QStringRef(buffer, currentBufferLength, firstSplitter);
			}
		}
	} while (!line.isNull());
	buffer->squeeze();
	
	if (!userFileName.isEmpty()) {
		//simpler format: category|word|word|...
		QFile f(userFileName);
		if (f.open(QIODevice::ReadOnly)) {
			QTextStream s(&f);
			s.setCodec(QTextCodec::codecForMib(MIB_UTF8));
			do {
				line = s.readLine();
				if (line.startsWith("#") || line.startsWith("%")) continue; //comments
				QStringList splitted = line.split("|",QString::SkipEmptyParts);
				if (splitted.size() < 2) continue;
				userWords.insert(splitted[0].toLower(), splitted);
				for (int i=1;i<splitted.length();i++)
					userCategories.insert(splitted[i].toLower(), splitted[0]);
				
			} while (!line.isNull());
		} 
	}	
}
Пример #11
0
QMap<QString, QString> O2ReplyServer::parseQueryParams(QByteArray *data) {
    qDebug() << "O2ReplyServer::parseQueryParams";

    //qDebug() << QString("O2ReplyServer::parseQueryParams data:\n%1").arg(QString(*data));

    QString splitGetLine = QString(*data).split("\r\n").first();
    splitGetLine.remove("GET ");
    splitGetLine.remove("HTTP/1.1");
    splitGetLine.remove("\r\n");
    splitGetLine.prepend("http://localhost");
    QUrl getTokenUrl(splitGetLine);

    QList< QPair<QString, QString> > tokens;
#if QT_VERSION < 0x050000
    tokens = getTokenUrl.queryItems();
#else
    QUrlQuery query(getTokenUrl);
    tokens = query.queryItems();
#endif
    QMultiMap<QString, QString> queryParams;
    QPair<QString, QString> tokenPair;
    foreach (tokenPair, tokens) {
        // FIXME: We are decoding key and value again. This helps with Google OAuth, but is it mandated by the standard?
        QString key = QUrl::fromPercentEncoding(QByteArray().append(tokenPair.first.trimmed().toLatin1()));
        QString value = QUrl::fromPercentEncoding(QByteArray().append(tokenPair.second.trimmed().toLatin1()));
        queryParams.insert(key, value);
    }
Пример #12
0
void MainWindow::on_cVersion_currentIndexChanged(const QString &version)
{
    QHash<QString, QStringList> &hVersion = reports[version];
    QStringList crashLocations = hVersion.keys();
    ui->cLocation->clear();
    if (crashLocations.size())
    {
        QMultiMap<int, QString> sortedMap;
        for (int i=0; i< crashLocations.size(); i++)
        {
            sortedMap.insert(hVersion.value(crashLocations.at(i)).size(), crashLocations.at(i));
        }
        QStringList sortedLocations = sortedMap.values();
        std::reverse(sortedLocations.begin(), sortedLocations.end());
        ui->cLocation->addItems(sortedLocations);
        ui->cLocation->setCurrentIndex(0);

        int acum = 0;
        for (int i = 0; i < crashLocations.size(); i++)
        {
            acum += hVersion.value(crashLocations[i]).size();
        }
        ui->eVersion->setText(QString::number(acum));
    }
    else
    {
        ui->eVersion->setText(QString::number(0));
        ui->cLocation->addItem(tr("Crash location"));
    }
}
Пример #13
0
void  ModItemsTree::findCompOfInheritingClassesInDescendants2(const QStringList & classNames,QString parentName,QString parentClass,QMultiMap<QString,QString> &result,QRegExp classFilter)
{

    if(classFilter.isValid() && !parentClass.contains(classFilter))
        return ;// no need to carry on


    QStringList compShortNames,compClasses;
    QString childLongName;
    // quick version but does not catch everything
    _moomc->getContainedComponents(parentClass,compShortNames,compClasses,true);

    foreach(QString className, classNames)
    {
        for(int i=0;i<compClasses.size();i++)
        {
            if(!classFilter.isValid() || parentClass.contains(classFilter))
            {
                if((compClasses.at(i)==className)||_moomc->inherits(compClasses.at(i),className))
                {
                    childLongName = parentClass.isEmpty() ? compShortNames.at(i) : parentName+"."+compShortNames.at(i);
                    result.insert(className,childLongName);
                }
            }
        }
    }

    ModItem* compItem;
    for(int i=0;i<compClasses.size();i++)
    {
        childLongName = parentClass.isEmpty() ? compShortNames.at(i) : parentName+"."+compShortNames.at(i);
        findCompOfInheritingClassesInDescendants2(classNames,childLongName,compClasses.at(i),result,classFilter);
    }
}
QMultiMap<QString, int>  MySQLBackEnd::loadCompositeFoodNamesForUser
   (int userId, bool)
{
  QSqlQuery query(db);
  QMultiMap<QString, int> foods;

  // TODO: Use second argument includeExpired

  query.prepare("SELECT composite_food.Composite_Id, composite_food.Description,"
                 "       composite_food.CreationDate, composite_food.ExpiryDate "
                 "FROM   composite_food "
                 "WHERE  composite_food.User_Id = :userId");

  query.bindValue(":userId", userId);

  if (query.exec()) {
    while (query.next()) {
      const QSqlRecord& record = query.record();
      foods.insert(record.field("Description").value().toString() +
                   CompositeFood::generateExpirySuffix
                     (record.field("CreationDate").value().toDate(),
                      record.field("ExpiryDate").value().toDate()),
                   record.field("Composite_Id").value().toInt());
    }
  } else {
    qDebug() << "Query failed: " << query.lastError();
  }

  return foods;
}
Пример #15
0
void NameSortIterator::createCash(const QString &varID)
{
    cash.clear();
    posIncash=-1;

    CompositeVar var;
    if(ids.getVarByID(varID,var)) {
        QString parID = var.getParentID();
        if(!parID.isEmpty()) {
            if(ids.getVarByID(parID,var)) {
                QStringList childrenIDs = var.getChildren();
                QMultiMap<QString,QString> vars;
                foreach (QString id, childrenIDs) {
                    CompositeVar child;
                    if(ids.getVarByID(id,child)) {
                        vars.insert(child.getName(),id);
                    }
                }
                QStringList varNames = vars.keys();
                varNames.removeDuplicates();
                qSort(varNames.begin(),varNames.end(),lessThan);
                //varNames.sort();
                int curId=0;
                foreach (QString vName, varNames) {
                   QStringList varsByName = vars.values(vName);
                   foreach (QString cVar, varsByName) {
                      cash += cVar;
                      if(cVar==varID) posIncash = curId;
                      curId++;
                   }
// +-----------------------------------------------------------
QString ft::Utils::shortenPath(const QString &sPath, int iMaxLen)
{
	// If the string is not long enough, simply return it
	if(sPath.length() <= iMaxLen)
		return QDir::toNativeSeparators(sPath);

	QFileInfo oFile = QFileInfo(sPath);
	QString sPathOnly = oFile.path();
	QString sFileName = QDir::separator() + oFile.fileName();
	QString sDriveLetter = ""; // In case it is running on a Windows OS

    // Firstly, split the path (only) into parts (for the drive letter and/or each subfolder)
    QRegExp oRegex("([\\\\\\/][\\w -\\.]*)");
    QStringList lsParts;
	QMultiMap<int, int> mpSortedParts;
    QString sPart;

    bool bFirst = true;
    int iPos = 0;
    while((iPos = oRegex.indexIn(sPathOnly, iPos)) != -1)
    {
        if(bFirst)
        {
            sDriveLetter = sPathOnly.left(iPos);
            bFirst = false;
        }
        sPart = oRegex.cap(1);
        lsParts.push_back(sPart);
		mpSortedParts.insert(sPart.length(), lsParts.count() - 1);
        iPos += oRegex.matchedLength();
    }

	// Then, iteratively remove the larger parts while the path is bigger than
	// the maximum number of characters desired
	QString sNewPath;
	do
	{
		sNewPath = "";

		// Rebuild the path replacing the so far larger part for "..."
		QMapIterator<int, int> oSorted(mpSortedParts);
		oSorted.toBack();
		if(oSorted.hasPrevious())
		{
			int iLength = oSorted.peekPrevious().key();
			int iIndex = oSorted.peekPrevious().value();
			mpSortedParts.remove(iLength, iIndex);

			lsParts.replace(iIndex, QDir::separator() + QString("..."));
		
			for(QStringList::iterator it = lsParts.begin(); it != lsParts.end(); ++it)
				sNewPath += *it;
		}
	} while(sNewPath.length() > 0 && QString(sDriveLetter + sNewPath + sFileName).length() > iMaxLen);

	if(sNewPath.length() == 0)
		sNewPath = QDir::separator() + QString("...");

	return QDir::toNativeSeparators(sDriveLetter + sNewPath + sFileName);
}
Пример #17
0
void DatabaseData::checkSpecialRatesAccom() {

	QMultiMap<QString,SaverDbSpecialRatesAccom> data;

	QSqlQuery query(db);
	query.prepare("SELECT * FROM rates_accomSpecial");
	allErr->catchSqlError(query,"checkaccomspecial prepare");
	query.exec();
	allErr->catchSqlError(query,"checkaccomspecial exec");

	while(query.next()) {

		SaverDbSpecialRatesAccom s;
		s.type = query.value(query.record().indexOf("type")).toString();
		s.type_long = query.value(query.record().indexOf("type_long")).toString();
		s.rateferryreturn = query.value(query.record().indexOf("ferry_ret")).toDouble();
		s.rateaccom = query.value(query.record().indexOf("accom")).toDouble();

		data.insert(s.type,s);

	}

	query.clear();

	QFile fileSpecialAccom(QDir::homePath() + "/.booker/config/specialratesaccom");
	if(fileSpecialAccom.exists()) fileSpecialAccom.remove();
	if(fileSpecialAccom.open(QIODevice::WriteOnly)) {
		QDataStream out(&fileSpecialAccom);
		out << data;
		fileSpecialAccom.close();
	}

}
Пример #18
0
void DatabaseData::checkSpecialRatesBikes() {

	QMultiMap<QString,SaverDbSpecialRatesBikes> data;

	QSqlQuery query(db);
	query.prepare("SELECT * FROM rates_bikesSpecial");
	allErr->catchSqlError(query,"checkbikesspecial prepare");
	query.exec();
	allErr->catchSqlError(query,"checkbikesspecial exec");

	while(query.next()) {

		SaverDbSpecialRatesBikes s;

		s.group = query.value(query.record().indexOf("peoplegroup")).toString();
		s.rateferryreturn = query.value(query.record().indexOf("ferry_ret")).toDouble();
		s.ratebusreturn = query.value(query.record().indexOf("bus_ret")).toDouble();
		s.ratebikes = query.value(query.record().indexOf("bikes")).toDouble();

		data.insert(s.group.toLower(),s);

	}

	query.clear();

	QFile fileSpecialBikes(QDir::homePath() + "/.booker/config/specialratesbikes");
	if(fileSpecialBikes.exists()) fileSpecialBikes.remove();
	if(fileSpecialBikes.open(QIODevice::WriteOnly)) {
		QDataStream out(&fileSpecialBikes);
		out << data;
		fileSpecialBikes.close();
	}

}
Пример #19
0
void DatabaseData::checkAccommodationLocations() {

	QMultiMap<QString,SaverDbAccomLocations> data;

	QSqlQuery query(db);
	query.prepare("SELECT * FROM accommodation_locations ORDER BY name");
	allErr->catchSqlError(query,"checkaccommodations prepare");
	query.exec();
	allErr->catchSqlError(query,"checkaccommodations exec");

	while(query.next()) {

		SaverDbAccomLocations s;
		s.type = query.value(query.record().indexOf("type")).toString();
		s.name = query.value(query.record().indexOf("name")).toString();

		data.insert(s.type, s);

	}

	query.clear();

	QFile fileAccLoc(QDir::homePath() + "/.booker/config/accommodationlocations");
	if(fileAccLoc.exists()) fileAccLoc.remove();
	if(fileAccLoc.open(QIODevice::WriteOnly)) {
		QDataStream out(&fileAccLoc);
		out << data;
		fileAccLoc.close();
	}

}
Пример #20
0
void test1() {
    auto F = initLazySecondOrderRecurrenceRelation();

    qDebug() << " sqrt(      5) -   1  /    4" << x_mpf(      5,   1,    4) << A_mpf(x_mpf(      5,   1,    4), &F, 0.00000000001);
    qDebug() << "(sqrt(      4) -   0) /    5" << x_mpf(      4,   0,    5) << A_mpf(x_mpf(      4,   0,    5), &F, 0.00000000001);
    qDebug() << "(sqrt(     22) -   2) /    6" << x_mpf(     22,   2,    6) << A_mpf(x_mpf(     22,   2,    6), &F, 0.00000000001);
    qDebug() << "(sqrt(    137) -   5) /   14" << x_mpf(    137,   5,   14) << A_mpf(x_mpf(    137,   5,   14), &F, 0.00000000001);
    qDebug() << "(sqrt(      1) -   0) /    2" << x_mpf(      1,   0,    2) << A_mpf(x_mpf(      1,   0,    2), &F, 0.00000000001);

    QMultiMap<mpf_class, QList<int>> xs;

    for (int a = 1; a < 4000; a += 1) {
        //if (isSquare(a) == false) { continue; } // show only nuggets
        for (int b = 1; b < 1000; b += 1) {
            int c = 6 + (b-1)*2;
            xs.insert(x_mpf(a, b, c), {a, b, c});
        }
    }

    QMapIterator<mpf_class, QList<int>> i(xs);
    while (i.hasNext()) {
        i.next();
        if (i.key() >= 0.309 && i.key() < 0.6) {

            mpf_class result = A_mpf(i.key(), &F, 0.000000001);
            mpf_class resultCeil;
            mpf_ceil(resultCeil.get_mpf_t(), result.get_mpf_t());

            if (resultCeil - result <= 0.0001 && resultCeil+1 == i.value()[1]) { // reduce results to specific c values
            //if (resultCeil - result <= 0.0001) {
                qDebug() << i.key() << i.value() << result << isSquare(i.value()[0]);
            }
        }
    }
}
Пример #21
0
//when getBusStopMessage(const QString&) download finishes
void ArrivalsLogic::onBusStopMessageReceived() {
    QList<QJsonDocument> document = makeDocument(reply_busStopMessage);
    if (document.empty()) { return; } //nothing to do

    QJsonArray versionArray = document.begin()->array();
    if (versionArray.begin() + 2 < versionArray.end() ) {
        double serverTime = (*(versionArray.begin() + 2 )).toDouble();
        QMultiMap<int,QString> messages;
        for (QList<QJsonDocument>::const_iterator iter = document.begin() + 1; iter < document.end(); ++iter) {
            if (iter->array().begin() + 4 < iter->array().end()) {
                int priority = (*(iter->array().begin() + 1)).toDouble();
                QString text = (*(iter->array().begin() + 2)).toString();
                double startTime = (*(iter->array().begin() + 3)).toDouble();
                double expireTime = (*(iter->array().begin() + 4)).toDouble();
                if (startTime <= serverTime && expireTime >= serverTime) {
                    messages.insert(priority, text);
                }
            }
            else {
                qDebug() << "The array doesn't contain 4 elements.";
                break;
            }
        }
        fillCurrentStopMessages(messages);
    }
    else return;
}
Пример #22
0
QMultiMap<QString,FileAttributes> ListFilesInDirectoryTest(QDir dir, bool Hash)
{
    extern Q_CORE_EXPORT int qt_ntfs_permission_lookup;
    qt_ntfs_permission_lookup++; // turn checking on
    QMultiMap<QString, FileAttributes> fileAttHashTable; //making hash table to store file attributes
    dir.setFilter(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
    dir.setSorting(QDir::Name);
    QFileInfoList list = dir.entryInfoList();
    for (int i = 0; i < list.size(); ++i)
    {
       QFileInfo fileInfo = list.at(i);
       if (fileInfo.isFile())
       {
           FileAttributes tempFileAttributes;
           QDateTime date = fileInfo.lastModified();
           QString lastModified = date.toString();

            tempFileAttributes.absoluteFilePath = fileInfo.absoluteFilePath();
            tempFileAttributes.fileName = fileInfo.fileName();
            tempFileAttributes.filePath= fileInfo.path();
            if (Hash) tempFileAttributes.md5Hash = GetFileMd5hash(fileInfo.absoluteFilePath());
            tempFileAttributes.lastModified  = fileInfo.lastModified();
            tempFileAttributes.lastRead = fileInfo.lastRead();
            tempFileAttributes.created = fileInfo.created();
            tempFileAttributes.isHidden =  fileInfo.isHidden();
            tempFileAttributes.size = fileInfo.size();
            tempFileAttributes.owner = fileInfo.owner();
            fileAttHashTable.insert(fileInfo.absoluteFilePath(),tempFileAttributes);
       }

    }
return fileAttHashTable;
}
void WidgetChatCenter::channelNames(QStringList names)
{
	WidgetChatTab* tab	= tabByName(names.at(2));
	QString namestr		= names.at(3);
	QStringList list	= namestr.split(" ");

	list.sort();
	QMultiMap<int, int> map;

	for(int i = 0; i < list.size(); ++i)
	{
		QString user = list.at(i);
		int idx = prefixChars.indexOf(user.at(0));
		if(idx < 0)
		{
			idx = prefixChars.length();    // normal user
		}
		map.insert(idx, i);
	}

	QStringList sorted;
	QList<int> values = map.values();
	for(int i = 0; i < values.size(); ++i)
	{
		sorted.append(list.at(values.at(i)));
	}

	tab->channelNames(sorted);
}
Пример #24
0
void DataFilesModel::sort(int column, Qt::SortOrder order)
{
    // TODO: Make this more efficient
    emit layoutAboutToBeChanged();

    QList<EsmFile *> sortedFiles;

    QMultiMap<QString, QString> timestamps;

    foreach (EsmFile *file, mFiles)
        timestamps.insert(file->modified().toString(Qt::ISODate), file->fileName());

    QMapIterator<QString, QString> ti(timestamps);

    while (ti.hasNext()) {
        ti.next();

        QModelIndex index = indexFromItem(findItem(ti.value()));

        if (!index.isValid())
            continue;

        EsmFile *file = item(index.row());

        if (!file)
            continue;

        sortedFiles.append(file);
    }

    mFiles.clear();
    mFiles = sortedFiles;

    emit layoutChanged();
}
QMultiMap<QString, QString>* FileManager::caricaCollegamenti() const
{
    QMultiMap<QString, QString>* lista = new QMultiMap<QString, QString>();
    QXmlStreamReader rxml;

    QFile file(_fileNameReti);
    if (file.open(QFile::ReadOnly | QFile::Text))
    {
        rxml.setDevice(&file);
        rxml.readNext();

        QString utente1, utente2;

        bool collegamentoAperto = false;

        while(!rxml.atEnd())
        {
            if(rxml.isStartElement())
            {
                if(rxml.name() == "Rete")
                    rxml.readNext();
                else if(rxml.name() == "Collegamento")
                {
                    collegamentoAperto = true;

                    while(!rxml.atEnd())
                    {
                        if(rxml.isEndElement())
                        {
                            if(collegamentoAperto)
                            {
                                lista->insert(utente1, utente2);
                                collegamentoAperto = false;
                            }
                            rxml.readNext();
                            break;
                        }
                        else if(rxml.isCharacters())
                            rxml.readNext();
                        else if(rxml.isStartElement())
                        {
                            if(rxml.name() == "Utente1")
                                utente1 = rxml.readElementText();
                            else if(rxml.name() == "Utente2")
                                utente2 = rxml.readElementText();
                            rxml.readNext();
                        }
                        else
                            rxml.readNext();
                    }
                }
            }
            else
                rxml.readNext();
        }
        file.close();
    }
    return lista;
}
Пример #26
0
QMultiMap<QString,MOParameter*> MOParameters::groupmap() const
{
    QMultiMap<QString,MOParameter*> map;
    for(int i=0;i<size();i++)
        map.insert(this->at(i)->getFieldValue(MOParameter::GROUP).toString(),this->at(i));

    return map;
}
Пример #27
0
/**
 * Return a sorted string list, sorted alphabetically case insensitive
 * @param QStringList list of strings
 * @param bool to normalize or not to normalize
 */
QStringList StringListView::sort(const QStringList &strings, bool normalize) {
	// Recommended way to have arbitrary sorting from QT docs
	QMultiMap<QString, QString> map;
	foreach (QString str, strings) {
		if (normalize)
			map.insert(StringListView::normalizeString(str.toLower()), str);
		else
			map.insert(str.toLower(), str);
	}

	QStringList sorted;
	QMapIterator<QString, QString> ii(map);
	while (ii.hasNext()) {
		sorted += ii.next().value();
	}
	return sorted;
}
void filterNetworkAccessModule::extractObjects()
{
    if(!this->parseQnStack.isEmpty())
    {
        if( this->parseQnStack.front() == this->ObjectLevel)
        {
            while(!this->parseQnStack.isEmpty())
            {
                std::cout << "Processing..." << std::endl;

                QXmlStreamReader::TokenType tempType = this->parseTypeStack.front();
                this->parseTypeStack.pop_front();
                QString tempQn = this->parseQnStack.front();
                this->parseQnStack.pop_front();
                QString tempText = this->parseTextStack.front();
                this->parseTextStack.pop_front();

                std::cout << "QN : " << tempQn.toAscii().data() <<  " : " << tempType << std::endl;

                //create a new object for the stack
                QMultiMap<QString, QString> *temp = new QMultiMap<QString, QString>;
                do
                {
                    //get the next item from the stack
                    tempType = this->parseTypeStack.front();
                    this->parseTypeStack.pop_front();

                    tempQn = this->parseQnStack.front();
                    this->parseQnStack.pop_front();

                    tempText = this->parseTextStack.front();
                    this->parseTextStack.pop_front();

                    //DEBUG
                    std::cout << "Adding: (" << tempQn.toAscii().data() << "," << tempText.toAscii().data() << ")" << std::endl;

                    //create object
                    temp->insert(tempQn, tempText);


                }while(!this->parseQnStack.isEmpty() && this->parseQnStack.front() != this->ObjectLevel);

                //add object to list
                std::cout << "adding record for " << temp->count() << " submaps" << std::endl;
                std::cout << "block: " << temp->value(QString("name")).toAscii().data() << std::endl;
                this->finalObjects->push_back(temp);
            }
//            std::cout << "Number of Objects:" << this->finalObjects->size() << std::endl;

        }
        else
        {
            std::cerr << "Empty Status: " << this->parseQnStack.size() << std::endl;
            std::cerr << "Back Item: " << this->parseQnStack.back().toAscii().data() << std::endl;
            std::cerr << ":EXTRACTION LOOP EXITS WITHOUT EXECUTING:" << std::endl;
        }
    }
}
Пример #29
0
QMultiMap< QByteArray, QByteArray > EWASiteRoutePoint::getRawHeadersMap() const
{
    QMultiMap< QByteArray, QByteArray > res;

    QList<QByteArray> raws = m_qnRequest.rawHeaderList();
    foreach( QByteArray raw, raws )
    {
        res.insert( raw, m_qnRequest.rawHeader( raw ) );
    }
Пример #30
0
QMultiMap<QString, QString> KQOAuthManagerPrivate::createTokensFromResponse(QByteArray reply) {
    QMultiMap<QString, QString> result;
    QString replyString(reply);

    QStringList parameterPairs = replyString.split('&', QString::SkipEmptyParts);
    foreach (const QString &parameterPair, parameterPairs) {
        QStringList parameter = parameterPair.split('=');
        result.insert(parameter.value(0), parameter.value(1));
    }