void PathFinding::internalSearchPath(const QString &destination_map,const quint8 &destination_x,const quint8 &destination_y,const QString &current_map,const quint8 &x,const quint8 &y,const QHash<quint16,quint32> &items)
{
    Q_UNUSED(items);

    QTime time;
    time.restart();

    QHash<QString,SimplifiedMapForPathFinding> simplifiedMapList;
    //transfer from object to local variable
    {
        QMutexLocker locker(&mutex);
        simplifiedMapList=this->simplifiedMapList;
        this->simplifiedMapList.clear();
    }
    //resolv the path
    if(!tryCancel)
    {
        QList<MapPointToParse> mapPointToParseList;

        //init the first case
        {
            MapPointToParse tempPoint;
            tempPoint.map=current_map;
            tempPoint.x=x;
            tempPoint.y=y;
            mapPointToParseList <<  tempPoint;

            QPair<quint8,quint8> coord(tempPoint.x,tempPoint.y);
            SimplifiedMapForPathFinding &tempMap=simplifiedMapList[current_map];
            tempMap.pathToGo[coord].left <<
                    QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_left,1);
            tempMap.pathToGo[coord].right <<
                    QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_right,1);
            tempMap.pathToGo[coord].bottom <<
                    QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_bottom,1);
            tempMap.pathToGo[coord].top <<
                    QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_top,1);
        }

        QPair<quint8,quint8> coord;
        while(!mapPointToParseList.isEmpty())
        {
            const MapPointToParse &tempPoint=mapPointToParseList.takeFirst();
            SimplifiedMapForPathFinding::PathToGo pathToGo;
            if(destination_map==current_map && tempPoint.x==destination_x && tempPoint.y==destination_y)
                qDebug() << QStringLiteral("final dest");
            //resolv the own point
            int index=0;
            while(index<1)/*2*/
            {
                if(tryCancel)
                {
                    tryCancel=false;
                    return;
                }
                {
                    //if the right case have been parsed
                    coord=QPair<quint8,quint8>(tempPoint.x+1,tempPoint.y);
                    if(simplifiedMapList.value(current_map).pathToGo.contains(coord))
                    {
                        const SimplifiedMapForPathFinding::PathToGo &nearPathToGo=simplifiedMapList.value(current_map).pathToGo.value(coord);
                        if(pathToGo.left.isEmpty() || pathToGo.left.size()>nearPathToGo.left.size())
                        {
                            pathToGo.left=nearPathToGo.left;
                            pathToGo.left.last().second++;
                        }
                        if(pathToGo.top.isEmpty() || pathToGo.top.size()>(nearPathToGo.left.size()+1))
                        {
                            pathToGo.top=nearPathToGo.left;
                            pathToGo.top << QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_top,1);
                        }
                        if(pathToGo.bottom.isEmpty() || pathToGo.bottom.size()>(nearPathToGo.left.size()+1))
                        {
                            pathToGo.bottom=nearPathToGo.left;
                            pathToGo.bottom << QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_bottom,1);
                        }
                    }
                    //if the left case have been parsed
                    coord=QPair<quint8,quint8>(tempPoint.x-1,tempPoint.y);
                    if(simplifiedMapList.value(current_map).pathToGo.contains(coord))
                    {
                        const SimplifiedMapForPathFinding::PathToGo &nearPathToGo=simplifiedMapList.value(current_map).pathToGo.value(coord);
                        if(pathToGo.right.isEmpty() || pathToGo.right.size()>nearPathToGo.right.size())
                        {
                            pathToGo.right=nearPathToGo.right;
                            pathToGo.right.last().second++;
                        }
                        if(pathToGo.top.isEmpty() || pathToGo.top.size()>(nearPathToGo.right.size()+1))
                        {
                            pathToGo.top=nearPathToGo.right;
                            pathToGo.top << QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_top,1);
                        }
                        if(pathToGo.bottom.isEmpty() || pathToGo.bottom.size()>(nearPathToGo.right.size()+1))
                        {
                            pathToGo.bottom=nearPathToGo.right;
                            pathToGo.bottom << QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_bottom,1);
                        }
                    }
                    //if the top case have been parsed
                    coord=QPair<quint8,quint8>(tempPoint.x,tempPoint.y+1);
                    if(simplifiedMapList.value(current_map).pathToGo.contains(coord))
                    {
                        const SimplifiedMapForPathFinding::PathToGo &nearPathToGo=simplifiedMapList.value(current_map).pathToGo.value(coord);
                        if(pathToGo.top.isEmpty() || pathToGo.top.size()>nearPathToGo.top.size())
                        {
                            pathToGo.top=nearPathToGo.top;
                            pathToGo.top.last().second++;
                        }
                        if(pathToGo.left.isEmpty() || pathToGo.left.size()>(nearPathToGo.top.size()+1))
                        {
                            pathToGo.left=nearPathToGo.top;
                            pathToGo.left << QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_left,1);
                        }
                        if(pathToGo.right.isEmpty() || pathToGo.right.size()>(nearPathToGo.top.size()+1))
                        {
                            pathToGo.right=nearPathToGo.top;
                            pathToGo.right << QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_right,1);
                        }
                    }
                    //if the bottom case have been parsed
                    coord=QPair<quint8,quint8>(tempPoint.x,tempPoint.y-1);
                    if(simplifiedMapList.value(current_map).pathToGo.contains(coord))
                    {
                        const SimplifiedMapForPathFinding::PathToGo &nearPathToGo=simplifiedMapList.value(current_map).pathToGo.value(coord);
                        if(pathToGo.bottom.isEmpty() || pathToGo.bottom.size()>nearPathToGo.bottom.size())
                        {
                            pathToGo.bottom=nearPathToGo.bottom;
                            pathToGo.bottom.last().second++;
                        }
                        if(pathToGo.left.isEmpty() || pathToGo.left.size()>(nearPathToGo.bottom.size()+1))
                        {
                            pathToGo.left=nearPathToGo.bottom;
                            pathToGo.left << QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_left,1);
                        }
                        if(pathToGo.right.isEmpty() || pathToGo.right.size()>(nearPathToGo.bottom.size()+1))
                        {
                            pathToGo.right=nearPathToGo.bottom;
                            pathToGo.right << QPair<CatchChallenger::Orientation,quint8/*step number*/>(CatchChallenger::Orientation_right,1);
                        }
                    }
                }
                index++;
            }
            coord=QPair<quint8,quint8>(tempPoint.x,tempPoint.y);
            if(!simplifiedMapList.value(current_map).pathToGo.contains(coord))
            {
                #ifdef CATCHCHALLENGER_EXTRA_CHECK
                extraControlOnData(pathToGo.left,CatchChallenger::Orientation_left);
                extraControlOnData(pathToGo.right,CatchChallenger::Orientation_right);
                extraControlOnData(pathToGo.top,CatchChallenger::Orientation_top);
                extraControlOnData(pathToGo.bottom,CatchChallenger::Orientation_bottom);
                #endif
                simplifiedMapList[current_map].pathToGo[coord]=pathToGo;
            }
            if(destination_map==current_map && tempPoint.x==destination_x && tempPoint.y==destination_y)
            {
                tryCancel=false;
                QList<QPair<CatchChallenger::Orientation,quint8/*step number*/> > returnedVar;
                if(returnedVar.isEmpty() || pathToGo.bottom.size()<returnedVar.size())
                    if(!pathToGo.bottom.isEmpty())
                        returnedVar=pathToGo.bottom;
                if(returnedVar.isEmpty() || pathToGo.top.size()<returnedVar.size())
                    if(!pathToGo.top.isEmpty())
                        returnedVar=pathToGo.top;
                if(returnedVar.isEmpty() || pathToGo.right.size()<returnedVar.size())
                    if(!pathToGo.right.isEmpty())
                        returnedVar=pathToGo.right;
                if(returnedVar.isEmpty() || pathToGo.left.size()<returnedVar.size())
                    if(!pathToGo.left.isEmpty())
                        returnedVar=pathToGo.left;
                if(!returnedVar.isEmpty())
                {
                    if(returnedVar.last().second<=1)
                    {
                        qDebug() << "Bug due for last step";
                        return;
                    }
                    else
                    {
                        qDebug() << "Path result into" << time.elapsed() << "ms";
                        returnedVar.last().second--;
                        emit result(returnedVar);
                        return;
                    }
                }
                else
                {
                    qDebug() << "Bug due to resolved path is empty";
                    return;
                }
            }
            //revers resolv
            //add to point to parse
            {
                //if the right case have been parsed
                coord=QPair<quint8,quint8>(tempPoint.x+1,tempPoint.y);
                if(!simplifiedMapList.value(current_map).pathToGo.contains(coord))
                {
                    MapPointToParse newPoint=tempPoint;
                    newPoint.x++;
                    if(newPoint.x<simplifiedMapList.value(current_map).width)
                        if(PathFinding::canGoOn(simplifiedMapList.value(current_map),newPoint.x,newPoint.y))
                        {
                            QPair<quint8,quint8> point(newPoint.x,newPoint.y);
                            if(!simplifiedMapList.value(current_map).pointQueued.contains(point))
                            {
                                simplifiedMapList[current_map].pointQueued << point;
                                mapPointToParseList <<  newPoint;
                            }
                        }
                }
                //if the left case have been parsed
                coord=QPair<quint8,quint8>(tempPoint.x-1,tempPoint.y);
                if(!simplifiedMapList.value(current_map).pathToGo.contains(coord))
                {
                    MapPointToParse newPoint=tempPoint;
                    if(newPoint.x>0)
                    {
                        newPoint.x--;
                        if(PathFinding::canGoOn(simplifiedMapList.value(current_map),newPoint.x,newPoint.y))
                        {
                            QPair<quint8,quint8> point(newPoint.x,newPoint.y);
                            if(!simplifiedMapList.value(current_map).pointQueued.contains(point))
                            {
                                simplifiedMapList[current_map].pointQueued << point;
                                mapPointToParseList <<  newPoint;
                            }
                        }
                    }
                }
                //if the bottom case have been parsed
                coord=QPair<quint8,quint8>(tempPoint.x,tempPoint.y+1);
                if(!simplifiedMapList.value(current_map).pathToGo.contains(coord))
                {
                    MapPointToParse newPoint=tempPoint;
                    newPoint.y++;
                    if(newPoint.y<simplifiedMapList.value(current_map).height)
                        if(PathFinding::canGoOn(simplifiedMapList.value(current_map),newPoint.x,newPoint.y))
                        {
                            QPair<quint8,quint8> point(newPoint.x,newPoint.y);
                            if(!simplifiedMapList.value(current_map).pointQueued.contains(point))
                            {
                                simplifiedMapList[current_map].pointQueued << point;
                                mapPointToParseList <<  newPoint;
                            }
                        }
                }
                //if the top case have been parsed
                coord=QPair<quint8,quint8>(tempPoint.x,tempPoint.y-1);
                if(!simplifiedMapList.value(current_map).pathToGo.contains(coord))
                {
                    MapPointToParse newPoint=tempPoint;
                    if(newPoint.y>0)
                    {
                        newPoint.y--;
                        if(PathFinding::canGoOn(simplifiedMapList.value(current_map),newPoint.x,newPoint.y))
                        {
                            QPair<quint8,quint8> point(newPoint.x,newPoint.y);
                            if(!simplifiedMapList.value(current_map).pointQueued.contains(point))
                            {
                                simplifiedMapList[current_map].pointQueued << point;
                                mapPointToParseList <<  newPoint;
                            }
                        }
                    }
                }
            }
            /*quint8 tempX=x,TempY=y;
            QString tempMap=current_map;
            SimplifiedMapForPathFinding::PathToGo pathToGoTemp;
            simplifiedMapList[current_map].pathToGo[QPair<quint8,quint8>(x,y)]=pathToGoTemp;*/
        }
    }
    //drop the local variable
    {
        QHash<QString,SimplifiedMapForPathFinding>::const_iterator k = simplifiedMapList.constBegin();
        while (k != simplifiedMapList.constEnd()) {
            delete k.value().dirt;
            delete k.value().ledges;
            delete k.value().walkable;
            delete k.value().monstersCollisionMap;
            ++k;
        }
    }
    tryCancel=false;
    emit result(QList<QPair<CatchChallenger::Orientation,quint8> >());
    qDebug() << "Path not found into" << time.elapsed() << "ms";
}
bool Metalink::metalinkInit(const KUrl &src, const QByteArray &data)
{
    kDebug(5001);

    if (!src.isEmpty()) {
        m_localMetalinkLocation = src;
    }

    //use the downloaded metalink-file data directly if possible
    if (!data.isEmpty()) {
        KGetMetalink::HandleMetalink::load(data, &m_metalink);
    }

    //try to parse the locally stored metalink-file
    if (!m_metalink.isValid() && m_localMetalinkLocation.isValid()) {
        KGetMetalink::HandleMetalink::load(m_localMetalinkLocation.toLocalFile(), &m_metalink);
    }

    if (!m_metalink.isValid()) {
        kError(5001) << "Unknown error when trying to load the .metalink-file. Metalink is not valid.";
        setStatus(Job::Aborted);
        setTransferChange(Tc_Status, true);
        return false;
    }

    //offers a dialog to download the newest version of a dynamic metalink
     if ((m_source.isLocalFile() || !m_metalinkJustDownloaded) &&
         m_metalink.dynamic && (UrlChecker::checkSource(m_metalink.origin) == UrlChecker::NoError)) {
        if (KMessageBox::questionYesNo(0, i18n("A newer version of this Metalink might exist, do you want to download it?"),
                                       i18n("Redownload Metalink")) == KMessageBox::Yes) {
            m_localMetalinkLocation.clear();
            m_source = m_metalink.origin;
            downloadMetalink();
            return false;
        }
    }

    QList<KGetMetalink::File>::const_iterator it;
    QList<KGetMetalink::File>::const_iterator itEnd = m_metalink.files.files.constEnd();
    m_totalSize = 0;
    KIO::fileoffset_t segSize = 500 * 1024;//TODO use config here!
    const KUrl tempDest = KUrl(m_dest.directory());
    KUrl dest;
    for (it = m_metalink.files.files.constBegin(); it != itEnd ; ++it)
    {
        dest = tempDest;
        dest.addPath((*it).name);

        QList<KGetMetalink::Url> urlList = (*it).resources.urls;
        //sort the urls according to their priority (highest first)
        qSort(urlList.begin(), urlList.end(), qGreater<KGetMetalink::Url>());

        KIO::filesize_t fileSize = (*it).size;
        m_totalSize += fileSize;

        //create a DataSourceFactory for each separate file
        DataSourceFactory *dataFactory = new DataSourceFactory(this, dest, fileSize, segSize);
        dataFactory->setMaxMirrorsUsed(MetalinkSettings::mirrorsPerFile());

#ifdef HAVE_NEPOMUK
        nepomukHandler()->setProperties((*it).properties(), QList<KUrl>() << dest);
#endif //HAVE_NEPOMUK

//TODO compare available file size (<size>) with the sizes of the server while downloading?

        connect(dataFactory, SIGNAL(capabilitiesChanged()), this, SLOT(slotUpdateCapabilities()));
        connect(dataFactory, SIGNAL(dataSourceFactoryChange(Transfer::ChangesFlags)), this, SLOT(slotDataSourceFactoryChange(Transfer::ChangesFlags)));
        connect(dataFactory->verifier(), SIGNAL(verified(bool)), this, SLOT(slotVerified(bool)));
        connect(dataFactory->signature(), SIGNAL(verified(int)), this, SLOT(slotSignatureVerified()));
        connect(dataFactory, SIGNAL(log(QString,Transfer::LogLevel)), this, SLOT(setLog(QString,Transfer::LogLevel)));

        //add the DataSources
        for (int i = 0; i < urlList.size(); ++i)
        {
            const KUrl url = urlList[i].url;
            if (url.isValid())
            {
                dataFactory->addMirror(url, MetalinkSettings::connectionsPerUrl());
            }
        }
        //no datasource has been created, so remove the datasource factory
        if (dataFactory->mirrors().isEmpty())
        {
            delete dataFactory;
        }
        else
        {
            dataFactory->verifier()->addChecksums((*it).verification.hashes);
            foreach (const KGetMetalink::Pieces &pieces, (*it).verification.pieces) {
                dataFactory->verifier()->addPartialChecksums(pieces.type, pieces.length, pieces.hashes);
            }

            const QHash <QString, QString> signatures = (*it).verification.signatures;
            QHash<QString, QString>::const_iterator it;
            QHash<QString, QString>::const_iterator itEnd = signatures.constEnd();
            for (it = signatures.constBegin(); it != itEnd; ++it) {
                if (it.key().toLower() == "pgp") {
                    dataFactory->signature()->setAsciiDetatchedSignature(*it);
                }
            }

            m_dataSourceFactory[dataFactory->dest()] = dataFactory;
        }
    }

    if ((m_metalink.files.files.size() == 1) && m_dataSourceFactory.size())
    {
        m_dest = dest;
    }

    if (!m_dataSourceFactory.size()) {
        //TODO make this via log in the future + do not display the KMessageBox
        kWarning(5001) << "Download of" << m_source << "failed, no working URLs were found.";
        KMessageBox::error(0, i18n("Download failed, no working URLs were found."), i18n("Error"));
        setStatus(Job::Aborted);
        setTransferChange(Tc_Status, true);
        return false;
    }

    m_ready = !m_dataSourceFactory.isEmpty();
    slotUpdateCapabilities();

    //the metalink-file has just been downloaded, so ask the user to choose the files that
    // should be downloaded
    if (m_metalinkJustDownloaded) {
        KDialog *dialog = new FileSelectionDlg(fileModel());
        dialog->setAttribute(Qt::WA_DeleteOnClose);
        connect(dialog, SIGNAL(finished(int)), this, SLOT(fileDlgFinished(int)));

        dialog->show();
    }

    return true;
}
void PathFinding::searchPath(const QHash<QString, MapVisualiserThread::Map_full *> &all_map,const QString &destination_map,const quint8 &destination_x,const quint8 &destination_y,const QString &current_map,const quint8 &x,const quint8 &y,const QHash<quint16,quint32> &items)
{
    //path finding buggy
    {
        QList<QPair<CatchChallenger::Orientation,quint8> > path;
        emit result(path);
        return;
    }
    if(!all_map.contains(current_map))
    {
        QList<QPair<CatchChallenger::Orientation,quint8> > path;
        emit result(path);
        return;
    }
    tryCancel=false;
    QHash<QString,SimplifiedMapForPathFinding> simplifiedMapList;
    QHash<QString,MapVisualiserThread::Map_full *>::const_iterator i = all_map.constBegin();
    //load the data
    while (i != all_map.constEnd()) {
        if(i.value()->displayed)
        {
            SimplifiedMapForPathFinding simplifiedMap;
            simplifiedMap.width=i.value()->logicalMap.width;
            simplifiedMap.height=i.value()->logicalMap.height;
            if(i.value()->logicalMap.parsed_layer.dirt==NULL)
                simplifiedMap.dirt=NULL;
            else
            {
                simplifiedMap.dirt=new bool[simplifiedMap.width*simplifiedMap.height];
                memcpy(simplifiedMap.dirt,i.value()->logicalMap.parsed_layer.dirt,simplifiedMap.width*simplifiedMap.height);
            }
            if(i.value()->logicalMap.parsed_layer.ledges==NULL)
                simplifiedMap.ledges=NULL;
            else
            {
                simplifiedMap.ledges=new quint8[simplifiedMap.width*simplifiedMap.height];
                memcpy(simplifiedMap.ledges,i.value()->logicalMap.parsed_layer.ledges,simplifiedMap.width*simplifiedMap.height);
            }
            if(i.value()->logicalMap.parsed_layer.walkable==NULL)
                simplifiedMap.walkable=NULL;
            else
            {
                simplifiedMap.walkable=new bool[simplifiedMap.width*simplifiedMap.height];
                memcpy(simplifiedMap.walkable,i.value()->logicalMap.parsed_layer.walkable,simplifiedMap.width*simplifiedMap.height);
            }
            if(i.value()->logicalMap.parsed_layer.monstersCollisionMap==NULL)
                simplifiedMap.monstersCollisionMap=NULL;
            else
            {
                simplifiedMap.monstersCollisionMap=new quint8[simplifiedMap.width*simplifiedMap.height];
                memcpy(simplifiedMap.monstersCollisionMap,i.value()->logicalMap.parsed_layer.monstersCollisionMap,simplifiedMap.width*simplifiedMap.height);
            }
            simplifiedMapList[i.key()]=simplifiedMap;
        }
        ++i;
    }
    //resolv the border
    QHash<QString,SimplifiedMapForPathFinding>::const_iterator j = simplifiedMapList.constBegin();
    while (j != simplifiedMapList.constEnd()) {
        if(all_map.contains(all_map.value(j.key())->logicalMap.border_semi.bottom.fileName))
        {
            simplifiedMapList[j.key()].border.bottom.map=&simplifiedMapList[all_map.value(j.key())->logicalMap.border_semi.bottom.fileName];
            simplifiedMapList[j.key()].border.bottom.x_offset=all_map.value(j.key())->logicalMap.border_semi.bottom.x_offset;
        }
        else
        {
            simplifiedMapList[j.key()].border.bottom.map=NULL;
            simplifiedMapList[j.key()].border.bottom.x_offset=0;
        }
        if(all_map.contains(all_map.value(j.key())->logicalMap.border_semi.left.fileName))
        {
            simplifiedMapList[j.key()].border.left.map=&simplifiedMapList[all_map.value(j.key())->logicalMap.border_semi.left.fileName];
            simplifiedMapList[j.key()].border.left.y_offset=all_map.value(j.key())->logicalMap.border_semi.left.y_offset;
        }
        else
        {
            simplifiedMapList[j.key()].border.left.map=NULL;
            simplifiedMapList[j.key()].border.left.y_offset=0;
        }
        if(all_map.contains(all_map.value(j.key())->logicalMap.border_semi.right.fileName))
        {
            simplifiedMapList[j.key()].border.right.map=&simplifiedMapList[all_map.value(j.key())->logicalMap.border_semi.right.fileName];
            simplifiedMapList[j.key()].border.right.y_offset=all_map.value(j.key())->logicalMap.border_semi.right.y_offset;
        }
        else
        {
            simplifiedMapList[j.key()].border.right.map=NULL;
            simplifiedMapList[j.key()].border.right.y_offset=0;
        }
        if(all_map.contains(all_map.value(j.key())->logicalMap.border_semi.top.fileName))
        {
            simplifiedMapList[j.key()].border.top.map=&simplifiedMapList[all_map.value(j.key())->logicalMap.border_semi.top.fileName];
            simplifiedMapList[j.key()].border.top.x_offset=all_map.value(j.key())->logicalMap.border_semi.top.x_offset;
        }
        else
        {
            simplifiedMapList[j.key()].border.top.map=NULL;
            simplifiedMapList[j.key()].border.top.x_offset=0;
        }
        ++j;
    }
    //load for thread and unload if needed
    {
        QMutexLocker locker(&mutex);
        QHash<QString,SimplifiedMapForPathFinding>::const_iterator k = this->simplifiedMapList.constBegin();
        while (k != this->simplifiedMapList.constEnd()) {
            delete k.value().dirt;
            delete k.value().ledges;
            delete k.value().walkable;
            delete k.value().monstersCollisionMap;
            ++k;
        }
        this->simplifiedMapList=simplifiedMapList;
    }
    emit emitSearchPath(destination_map,destination_x,destination_y,current_map,x,y,items);
}
void tst_Symbols::prefix()
{
#if defined(QT_CROSS_COMPILED)
    QSKIP("Probably no compiler on the target", SkipAll);
#elif defined(Q_OS_LINUX)
    QStringList qtTypes;
    qtTypes << "QString" << "QChar" << "QWidget" << "QObject" << "QVariant" << "QList"
            << "QMap" << "QHash" << "QVector" << "QRect" << "QSize" << "QPoint"
            << "QTextFormat" << "QTextLength" << "QPen" << "QFont" << "QIcon"
            << "QPixmap" << "QImage" << "QRegion" << "QPolygon";
    QStringList qAlgorithmFunctions;
    qAlgorithmFunctions << "qBinaryFind" << "qLowerBound" << "qUpperBound"
                        << "qAbs" << "qMin" << "qMax" << "qBound" << "qSwap"
                        << "qHash" << "qDeleteAll" << "qCopy" << "qSort";

    QStringList exceptionalSymbols;
    exceptionalSymbols << "XRectangle::~XRectangle()"
                       << "XChar2b::~XChar2b()"
                       << "XPoint::~XPoint()"
                       << "glyph_metrics_t::"; // #### Qt 4.2

    QStringList stupidCSymbols;
    stupidCSymbols << "Add_Glyph_Property"
                   << "Check_Property"
                   << "Coverage_Index"
                   << "Get_Class"
                   << "Get_Device"
                   << "rcsid3"
                   << "sfnt_module_class"
                   << "t1cid_driver_class"
                   << "t42_driver_class"
                   << "winfnt_driver_class"
                   << "pshinter_module_class"
                   << "psnames_module_class"
                   // C symbols from Qt
                   << "qt_addObject"
                   << "qt_removeObject"
                   << "qt_startup_hook"
                   ;

    QHash<QString,QStringList> excusedPrefixes;
    excusedPrefixes[QString()] =
        QStringList() << "Ui_Q"; // uic generated, like Ui_QPrintDialog

    excusedPrefixes["QtCore"] =
        QStringList() << "hb_"
                      << "HB_"
                      // zlib symbols, for -qt-zlib ;(
                      << "deflate"
                      << "compress"
                      << "uncompress"
                      << "adler32"
                      << "gz"
                      << "inflate"
                      << "zlib"
                      << "zError"
                      << "get_crc_table"
                      << "crc32";

    excusedPrefixes["QtGui"] =
        QStringList() << "ftglue_"
                      << "Load_"
                      << "otl_"
                      << "TT_"
                      << "tt_"
                      << "t1_"
                      << "Free_"
                      << "FT_"
                      << "FTC_"
                      << "ft_"
                      << "ftc_"
                      << "af_autofitter"
                      << "af_dummy"
                      << "af_latin"
                      << "autofit_"
                      << "XPanorami"
                      << "Xinerama"
                      << "bdf_"
                      << "ccf_"
                      << "gray_raster"
                      << "pcf_"
                      << "cff_"
                      << "otv_"
                      << "pfr_"
                      << "ps_"
                      << "psaux"
                      << "png_";

    excusedPrefixes["QtSql"] =
        QStringList() << "sqlite3";

    excusedPrefixes["QtScript"] =
        QStringList() << "QTJSC";

    excusedPrefixes["QtWebKit"] =
        QStringList() << "WebCore::"
                      << "KJS::"
                      << "kjs"
                      << "kJS"
                      << "JS"
//                      << "OpaqueJS"
                      << "WTF"
                      << "wtf_"
                      << "SVG::"
                      << "NPN_"
                      << "cti"  // ctiTrampoline and ctiVMThrowTrampoline from the JIT
#ifdef QT_NAMESPACE
                      << "QWeb" // Webkit is only 'namespace aware'
                      << "qWeb"
                      << "qt"
                      << "QGraphicsWebView"
                      << "operator"
#endif
        ;

    excusedPrefixes["phonon"] =
        QStringList() << ns + "Phonon";

    QDir dir(qgetenv("QTDIR") + "/lib", "*.so");
    QStringList files = dir.entryList();
    QVERIFY(!files.isEmpty());

    bool isFailed = false;
    foreach (QString lib, files) {
        if (lib.contains("Designer") || lib.contains("QtCLucene") || lib.contains("XmlPatternsSDK") || lib.contains("WebKit"))
            continue;

        bool isPhonon = lib.contains("phonon");

        QProcess proc;
        proc.start("nm",
           QStringList() << "-g" << "-C" << "-D" << "--format=posix"
                         << "--defined-only" << dir.absolutePath() + "/" + lib);
        QVERIFY(proc.waitForFinished());
        QCOMPARE(proc.exitCode(), 0);
        QCOMPARE(QString::fromLocal8Bit(proc.readAllStandardError()), QString());

        QStringList symbols = QString::fromLocal8Bit(proc.readAll()).split("\n");
        QVERIFY(!symbols.isEmpty());
        foreach (QString symbol, symbols) {
            if (symbol.isEmpty())
                continue;

            if (symbol.startsWith("unsigned "))
                // strip modifiers
                symbol = symbol.mid(symbol.indexOf(' ') + 1);
            if (symbol.startsWith("long long ")) {
                symbol = symbol.mid(10);
            } else if (symbol.startsWith("bool ") || symbol.startsWith("bool* ")
                || symbol.startsWith("char ") || symbol.startsWith("char* ")
                || symbol.startsWith("int ") || symbol.startsWith("int* ") || symbol.startsWith("int*&")
                || symbol.startsWith("short") || symbol.startsWith("long ")
                || symbol.startsWith("void ") || symbol.startsWith("void* ")
                || symbol.startsWith("double ") || symbol.startsWith("double* ")
                || symbol.startsWith("float ") || symbol.startsWith("float* ")) {
                // partial templates have the return type in their demangled name, strip it
                symbol = symbol.mid(symbol.indexOf(' ') + 1);
            }
            if (symbol.startsWith("const ") || symbol.startsWith("const* ") ||
                symbol.startsWith("const& ")) {
                // strip modifiers
                symbol = symbol.mid(symbol.indexOf(' ') + 1);
            }

            if (symbol.mid(symbol.indexOf(' ')+1).startsWith("std::"))
                continue;
            if (symbol.startsWith("_") || symbol.startsWith("std::"))
                continue;
            if (symbol.startsWith("vtable ") || symbol.startsWith("VTT for ") ||
                symbol.startsWith("construction vtable for"))
                continue;
            if (symbol.startsWith("typeinfo "))
                continue;
            if (symbol.startsWith("non-virtual thunk ") || symbol.startsWith("virtual thunk"))
                continue;
            if (symbol.startsWith(ns + "operator"))
                continue;
            if (symbol.startsWith("operator new") || symbol.startsWith("operator delete"))
                continue;
            if (symbol.startsWith("guard variable for "))
                continue;
            if (symbol.contains("(" + ns + "QTextStream"))
                // QTextStream is excused.
                continue;
            if (symbol.contains("(" + ns + "Q3TextStream"))
                // Q3TextStream is excused.
                continue;
            if (symbol.startsWith(ns + "bitBlt") || symbol.startsWith(ns + "copyBlt"))
                // you're excused, too
                continue;

            bool symbolOk = false;

            QHash<QString,QStringList>::ConstIterator it = excusedPrefixes.constBegin();
            for ( ; it != excusedPrefixes.constEnd(); ++it) {
                if (!lib.contains(it.key()))
                    continue;
                foreach (QString prefix, it.value())
                    if (symbol.startsWith(prefix)) {
                        symbolOk = true;
                        break;
                    }
            }

            if (symbolOk)
                continue;

            foreach (QString cSymbolPattern, stupidCSymbols)
                if (symbol.contains(cSymbolPattern)) {
                    symbolOk = true;
                    break;
                }

            if (symbolOk)
                continue;

            QStringList fields = symbol.split(' ');
            // the last two fields are address and size and the third last field is the symbol type
            QVERIFY(fields.count() > 3);
            QString type = fields.at(fields.count() - 3);
            // weak symbol
            if (type == QLatin1String("W")) {
                if (symbol.contains("qAtomic"))
                    continue;

                if (symbol.contains("fstat")
                    || symbol.contains("lstat")
                    || symbol.contains("stat64")
                   )
                    continue;

                foreach (QString acceptedPattern, qAlgorithmFunctions + exceptionalSymbols)
                    if (symbol.contains(acceptedPattern)) {
                        symbolOk = true;
                        break;
                    }

                if (symbolOk)
                    continue;

                QString plainSymbol;
                for (int i = 0; i < fields.count() - 3; ++i) {
                    if (i > 0)
                        plainSymbol += QLatin1Char(' ');
                    plainSymbol += fields.at(i);
                }
                foreach (QString qtType, qtTypes)
                    if (plainSymbol.contains(qtType)) {
                        symbolOk = true;
                        break;
                    }

                if (symbolOk)
                    continue;
            }

            QString prefix = ns + "q";
            if (!symbol.startsWith(prefix, Qt::CaseInsensitive)
                && !(isPhonon && symbol.startsWith("Phonon"))) {
                qDebug("symbol in '%s' does not start with prefix '%s': '%s'",
                    qPrintable(lib), qPrintable(prefix), qPrintable(symbol));
                isFailed = true;
            }
        }
    }

#  if defined(Q_OS_LINUX) && defined(Q_CC_INTEL)
    QEXPECT_FAIL("", "linux-icc* incorrectly exports some QtWebkit symbols, waiting for a fix from Intel.", Continue);
#  endif
    QVERIFY2(!isFailed, "Libraries contain non-prefixed symbols. See Debug output above.");
#else
    QSKIP("Linux-specific test", SkipAll);
#endif
}
void MeanwhileSession::syncContactsToServer()
{
    HERE;
    struct mwSametimeList *list = mwSametimeList_new();

    /* set up a fallback group for top-level contacts */
    struct mwSametimeGroup *topstgroup = mwSametimeGroup_new(list,
            mwSametimeGroup_DYNAMIC, "People");
    mwSametimeGroup_setOpen(topstgroup, true);

    const QHash<QString, Kopete::Contact *> contacts = account->contacts();
   // Q3DictIterator<Kopete::Contact> it(account->contacts());
    for(QHash<QString, Kopete::Contact *>::const_iterator it = contacts.constBegin();
            it != contacts.constEnd(); ++it ) {
        MeanwhileContact *contact = static_cast<MeanwhileContact *>(it.value());

        /* Find the group that the metacontact is in */
        Kopete::MetaContact *mc = contact->metaContact();
        if (!mc)
            continue;

        Kopete::Group *contactgroup = mc->groups().value(0);
        if (!contactgroup)
            continue;

        if (contactgroup->type() == Kopete::Group::Temporary)
            continue;

        struct mwSametimeGroup *stgroup;
        if (contactgroup->type() == Kopete::Group::TopLevel) {
            stgroup = topstgroup;
        } else  {
            /* find (or create) a matching sametime list group */
            stgroup = mwSametimeList_findGroup(list,
                        contactgroup->displayName().toUtf8().constData());
            if (!stgroup) {
                stgroup = mwSametimeGroup_new(list, mwSametimeGroup_DYNAMIC,
                        contactgroup->displayName().toUtf8().constData());
            }
            mwSametimeGroup_setOpen(stgroup, contactgroup->isExpanded());
            mwSametimeGroup_setAlias(stgroup,
                    contactgroup->pluginData(account->protocol(), "alias").toUtf8().constData());
        }

        QByteArray tmpMeanwhileId = contact->meanwhileId().toUtf8();
        /* now add the user (by IDBlock) */
        struct mwIdBlock id =
            { (gchar*)tmpMeanwhileId.constData(), 0 };
        struct mwSametimeUser *stuser = mwSametimeUser_new(stgroup,
                mwSametimeUser_NORMAL, &id);

        mwSametimeUser_setAlias(stuser, mc->displayName().toUtf8().constData());
    }

    /* store! */
    struct mwPutBuffer *buf = mwPutBuffer_new();
    struct mwStorageUnit *unit = mwStorageUnit_new(mwStore_AWARE_LIST);
    struct mwOpaque *opaque = mwStorageUnit_asOpaque(unit);

    mwSametimeList_put(buf, list);
    mwPutBuffer_finalize(opaque, buf);

    mwServiceStorage_save(storageService, unit, NULL, NULL, NULL);

    mwSametimeList_free(list);
}
Exemple #6
0
  void medianCut( QVector<QRgb> &colorTable, int nColors, const QImage &inputImage )
  {
    QHash<QRgb, int> inputColors;
    imageColors( inputColors, inputImage );

    if ( inputColors.size() <= nColors ) //all the colors in the image can be mapped to one palette color
    {
      colorTable.resize( inputColors.size() );
      int index = 0;
      for ( auto inputColorIt = inputColors.constBegin(); inputColorIt != inputColors.constEnd(); ++inputColorIt )
      {
        colorTable[index] = inputColorIt.key();
        ++index;
      }
      return;
    }

    //create first box
    QgsColorBox firstBox; //QList< QPair<QRgb, int> >
    int firstBoxPixelSum = 0;
    for ( auto  inputColorIt = inputColors.constBegin(); inputColorIt != inputColors.constEnd(); ++inputColorIt )
    {
      firstBox.push_back( qMakePair( inputColorIt.key(), inputColorIt.value() ) );
      firstBoxPixelSum += inputColorIt.value();
    }

    QgsColorBoxMap colorBoxMap; //QMultiMap< int, ColorBox >
    colorBoxMap.insert( firstBoxPixelSum, firstBox );
    QMap<int, QgsColorBox>::iterator colorBoxMapIt = colorBoxMap.end();

    //split boxes until number of boxes == nColors or all the boxes have color count 1
    bool allColorsMapped = false;
    while ( colorBoxMap.size() < nColors )
    {
      //start at the end of colorBoxMap and pick the first entry with number of colors < 1
      colorBoxMapIt = colorBoxMap.end();
      while ( true )
      {
        --colorBoxMapIt;
        if ( colorBoxMapIt.value().size() > 1 )
        {
          splitColorBox( colorBoxMapIt.value(), colorBoxMap, colorBoxMapIt );
          break;
        }
        if ( colorBoxMapIt == colorBoxMap.begin() )
        {
          allColorsMapped = true;
          break;
        }
      }

      if ( allColorsMapped )
      {
        break;
      }
    }

    //get representative colors for the boxes
    int index = 0;
    colorTable.resize( colorBoxMap.size() );
    for ( auto colorBoxIt = colorBoxMap.constBegin(); colorBoxIt != colorBoxMap.constEnd(); ++colorBoxIt )
    {
      colorTable[index] = boxColor( colorBoxIt.value(), colorBoxIt.key() );
      ++index;
    }
  }
void HoIModDesigner::FillCountryList( const QHash<QString,Nation*>& nations, QTableWidget* widget )
{
	if( widget == nullptr )
	{
		return;
	}

	widget->setSortingEnabled(true);
	widget->setRowCount( nations.size() );
	widget->setColumnCount( 10 );

	QHeaderView *verticalHeader = widget->verticalHeader();
	verticalHeader->setSectionResizeMode(QHeaderView::Fixed);
	verticalHeader->setDefaultSectionSize(20);

	int columnIndex = 0;
	widget->verticalHeader()->setVisible(false);
	widget->setSelectionBehavior(QAbstractItemView::SelectRows);
	QTableWidgetItem *id = new QTableWidgetItem("Name");
	id->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, id );

	QTableWidgetItem *provinces = new QTableWidgetItem("Provinces");
	provinces->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, provinces );

	QTableWidgetItem *ic = new QTableWidgetItem("IC");
	ic->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, ic );

	QTableWidgetItem *points = new QTableWidgetItem("Points");
	points->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, points );

	QTableWidgetItem *manpower = new QTableWidgetItem("Manpower");
	manpower->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, manpower );

	QTableWidgetItem *leadership = new QTableWidgetItem("Leadership");
	leadership->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, leadership );

	QTableWidgetItem *energy = new QTableWidgetItem("Energy");
	energy->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, energy );

	QTableWidgetItem *metal = new QTableWidgetItem("Metal");
	metal->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, metal );

	QTableWidgetItem *oil = new QTableWidgetItem("Crude oil");
	oil->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, oil );

	QTableWidgetItem *rare = new QTableWidgetItem("Rare material");
	rare->setBackground(Qt::lightGray);
	widget->setHorizontalHeaderItem( columnIndex++, rare );
	if( nations.isEmpty() == true )
	{
		return;
	}

	int rowIndex = 0;
	QHash<QString,Nation*>::ConstIterator iter;
	for( iter = nations.constBegin(); iter != nations.constEnd(); iter++ )
	{
		int columnIndex = 0;
		TableWidgetItemNation *nameItem = new TableWidgetItemNation((*iter)->GetID(),(*iter), new TableWidgetItemComparatorString() );
		widget->setItem(rowIndex, columnIndex++, nameItem );
		widget->item(rowIndex,0)->setTextAlignment(Qt::AlignCenter);
		
		QTableWidgetItem *provinces = new TableWidgetItemNation(QString().setNum((*iter)->m_Provinces.size()),(*iter));
		widget->setItem(rowIndex, columnIndex++, provinces );

		QTableWidgetItem *ic = new TableWidgetItemNation(QString().setNum((*iter)->CalcIC()),(*iter));
		widget->setItem(rowIndex, columnIndex++, ic );

		QTableWidgetItem *points = new TableWidgetItemNation(QString().setNum((*iter)->CalcPoints()),(*iter));
		widget->setItem(rowIndex, columnIndex++, points );

		QTableWidgetItem *manpower = new TableWidgetItemNation(QString().setNum((*iter)->CalcManpower()),(*iter));
		widget->setItem(rowIndex, columnIndex++, manpower );

		QTableWidgetItem *leadership = new TableWidgetItemNation(QString().setNum((*iter)->CalcLeadership()),(*iter));
		widget->setItem(rowIndex, columnIndex++, leadership );

		QTableWidgetItem *energy = new TableWidgetItemNation(QString().setNum((*iter)->CalcEnergy()),(*iter));
		widget->setItem(rowIndex, columnIndex++, energy );

		QTableWidgetItem *metal = new TableWidgetItemNation(QString().setNum((*iter)->CalcMetal()),(*iter));
		widget->setItem(rowIndex, columnIndex++, metal );

		QTableWidgetItem *oil = new TableWidgetItemNation(QString().setNum((*iter)->CalcCrudeOil()),(*iter));
		widget->setItem(rowIndex, columnIndex++, oil );

		QTableWidgetItem *rare = new TableWidgetItemNation(QString().setNum((*iter)->CalcRareMaterial()),(*iter));
		widget->setItem(rowIndex, columnIndex++, rare );

		rowIndex++;
	}
}
void DatabaseSynchronizer::run()
{
	QMutexLocker locker(&FMutex);
	while (!FQuit && !FStreams.isEmpty())
	{
		Jid streamJid = FStreams.dequeue();
		locker.unlock();

		Logger::startTiming(STMP_HISTORY_FILE_DATABASE_SYNC);

		bool syncFailed = false;
		QDateTime syncTime = QDateTime::currentDateTime();

		QString archivePath = FFileArchive->fileArchivePath(streamJid);
		if (!archivePath.isEmpty())
		{
			IArchiveRequest loadRequest;
			QHash<Jid, QList<QString> > databaseHeadersMap;
			QHash<QString, DatabaseArchiveHeader> databaseFileHeaders;
			DatabaseTaskLoadHeaders *loadTask = new DatabaseTaskLoadHeaders(streamJid,loadRequest,QString::null);
			if (!FDatabaseWorker->execTask(loadTask))
			{
				syncFailed = true;
				REPORT_ERROR("Failed to synchronize file archive database: Load database headers task not executed");
			}
			else if (loadTask->isFailed())
			{
				syncFailed = true;
				REPORT_ERROR("Failed to synchronize file archive database: Load database headers task failed");
			}
			else foreach(const DatabaseArchiveHeader &header, loadTask->headers())
			{
				if (header.timestamp < syncTime)
				{
					QString fileName = (FFileArchive->collectionDirName(header.with)+"/"+FFileArchive->collectionFileName(header.start)).toLower();
					databaseHeadersMap[header.with].append(fileName);
					databaseFileHeaders.insert(fileName,header);
				}
			}
			delete loadTask;


			QHash<Jid, QList<IArchiveHeader> > fileHeadersMap;
			QDirIterator bareIt(archivePath,QDir::Dirs|QDir::NoDotAndDotDot);
			while (!FQuit && !syncFailed && bareIt.hasNext())
			{
				QDirIterator filesIt(bareIt.next(), QDir::Files, QDirIterator::Subdirectories);
				
				Jid bareWith = Jid::decode(bareIt.fileName());
				bool isGated = bareWith.pDomain().endsWith(".gateway");
				int pathLength = bareIt.filePath().length()-bareIt.fileName().length();

				while (filesIt.hasNext())
				{
					filesIt.next();
					QDateTime fileLastModified = filesIt.fileInfo().lastModified();
					if (fileLastModified < syncTime)
					{
						QString fileName = filesIt.filePath().mid(pathLength).toLower();
						QHash<QString, DatabaseArchiveHeader>::iterator dbHeaderIt = databaseFileHeaders.find(fileName);
						if (dbHeaderIt==databaseFileHeaders.end() || dbHeaderIt->timestamp<fileLastModified)
						{
							IArchiveHeader header = FFileArchive->loadFileHeader(filesIt.filePath());
							if (header.with.isValid() && header.start.isValid() && !fileHeadersMap.value(header.with).contains(header))
							{
								if (!isGated && header.with.pBare()==bareWith.pBare())
									fileHeadersMap[header.with].append(header);
								else if (isGated && header.with.pNode()==bareWith.pNode())
									fileHeadersMap[header.with].append(header);
							}
						}
						else
						{
							databaseFileHeaders.erase(dbHeaderIt);
						}
					}
				}
			}


			for (QHash<Jid, QList<IArchiveHeader> >::iterator it=fileHeadersMap.begin(); !FQuit && !syncFailed && it!=fileHeadersMap.end(); ++it)
			{
				Jid with = it.key();

				QList<IArchiveHeader> newHeaders;
				QList<IArchiveHeader> difHeaders;
				QList<IArchiveHeader> oldHeaders;

				QList<IArchiveHeader> &fileHeaders = it.value();
				qSort(fileHeaders.begin(),fileHeaders.end());

				QList<IArchiveHeader> databaseHeaders;
				foreach(const QString &fileName, databaseHeadersMap.take(with))
				{
					QHash<QString, DatabaseArchiveHeader>::const_iterator dbHeaderIt = databaseFileHeaders.constFind(fileName);
					if (dbHeaderIt != databaseFileHeaders.constEnd())
						databaseHeaders.append(dbHeaderIt.value());
				}
				qSort(databaseHeaders.begin(),databaseHeaders.end());

				if (databaseHeaders.isEmpty())
				{
					newHeaders = fileHeaders;
				}
				else if (fileHeaders.isEmpty())
				{
					oldHeaders = databaseHeaders;
				}
				else while (!fileHeaders.isEmpty() || !databaseHeaders.isEmpty())
				{
					if (fileHeaders.isEmpty())
					{
						oldHeaders += databaseHeaders.takeFirst();
					}
					else if (databaseHeaders.isEmpty())
					{
						newHeaders += fileHeaders.takeFirst();
					}
					else if (fileHeaders.first() < databaseHeaders.first())
					{
						newHeaders += fileHeaders.takeFirst();
					}
					else if (databaseHeaders.first() < fileHeaders.first())
					{
						oldHeaders += databaseHeaders.takeFirst();
					}
					else if (fileHeaders.first().version != databaseHeaders.first().version)
					{
						difHeaders += fileHeaders.takeFirst();
						databaseHeaders.removeFirst();
					}
					else
					{
						fileHeaders.removeFirst();
						databaseHeaders.removeFirst();
					}
				}

				if (!syncFailed && !newHeaders.isEmpty())
				{
					QString gateType = !with.node().isEmpty() ? FFileArchive->contactGateType(with) : QString::null;
					DatabaseTaskInsertHeaders *insertTask = new DatabaseTaskInsertHeaders(streamJid,newHeaders,gateType);
					if (!FDatabaseWorker->execTask(insertTask))
					{
						syncFailed = true;
						REPORT_ERROR("Failed to synchronize file archive database: Insert new headers task not executed");
					}
					else if(insertTask->isFailed())
					{
						syncFailed = true;
						REPORT_ERROR("Failed to synchronize file archive database: Insert new headers task failed");
					}
					delete insertTask;
				}

				if (!syncFailed && !difHeaders.isEmpty())
				{
					DatabaseTaskUpdateHeaders *updateTask = new DatabaseTaskUpdateHeaders(streamJid,difHeaders);
					if (!FDatabaseWorker->execTask(updateTask))
					{
						syncFailed = true;
						REPORT_ERROR("Failed to synchronize file archive database: Update changed headers task not executed");
					}
					else if (updateTask->isFailed())
					{
						syncFailed = true;
						REPORT_ERROR("Failed to synchronize file archive database: Update changed headers task failed");
					}
					delete updateTask;
				}

				if (!syncFailed && !oldHeaders.isEmpty())
				{
					DatabaseTaskRemoveHeaders *removeTask = new DatabaseTaskRemoveHeaders(streamJid,oldHeaders);
					if (!FDatabaseWorker->execTask(removeTask))
					{
						syncFailed = true;
						REPORT_ERROR("Failed to synchronize file archive database: Remove old headers task not executed");
					}
					else if (removeTask->isFailed())
					{
						syncFailed = true;
						REPORT_ERROR("Failed to synchronize file archive database: Remove old headers task failed");
					}
					delete removeTask;
				}
			}


			for (QHash<Jid, QList<QString> >::const_iterator it=databaseHeadersMap.constBegin(); !FQuit && !syncFailed && it!=databaseHeadersMap.constEnd(); ++it)
			{
				QList<IArchiveHeader> oldHeaders;
				foreach(const QString &fileName, it.value())
				{
					QHash<QString, DatabaseArchiveHeader>::const_iterator dbHeaderIt = databaseFileHeaders.constFind(fileName);
					if (dbHeaderIt != databaseFileHeaders.constEnd())
						oldHeaders.append(dbHeaderIt.value());
				}

				if (!oldHeaders.isEmpty())
				{
					DatabaseTaskRemoveHeaders *removeTask = new DatabaseTaskRemoveHeaders(streamJid,oldHeaders);
					if (!FDatabaseWorker->execTask(removeTask))
					{
						syncFailed = true;
						REPORT_ERROR("Failed to synchronize file archive database: Remove old headers task not executed");
					}
					else if (removeTask->isFailed())
					{
						syncFailed = true;
						REPORT_ERROR("Failed to synchronize file archive database: Remove old headers task failed");
					}
					delete removeTask;
				}
			}
		}
		else
		{
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QFile file( "constellations.kml" );
    file.open( QIODevice::WriteOnly );
    QTextStream out( &file );

    out << "<?xml version=\"1.0\" encoding=\"UTF-8\"?> \n"
        << "<kml xmlns=\"http://www.opengis.net/kml/2.2\" hint=\"target=sky\"> \n"
        << "<Document> \n"
        << "    <Style id=\"lineStyle1\"> \n"
        << "        <LineStyle> \n"
        << "            <color>ffffffff</color> \n"
        << "        </LineStyle> \n"
        << "    </Style> \n"
        << "    <Style id=\"lineStyle2\"> \n"
        << "        <LineStyle> \n"
        << "            <color>ffff0000</color> \n"
        << "        </LineStyle> \n"
        << "    </Style> \n"
        << "    <Style id=\"iconStyle\"> \n"
        << "        <IconStyle> \n"
        << "            <Icon> \n"
        << "                <href></href> \n"
        << "            </Icon> \n"
        << "        </IconStyle> \n"
        << "    </Style> \n";

    QFile starsData( "catalog.dat" );
    QFile constellationsData( "constellations.dat" );

    if ( starsData.open( QFile::ReadOnly ) && constellationsData.open( QFile::ReadOnly ) ) {

        QTextStream streamConstellations( &constellationsData );
        QTextStream streamStars( &starsData );

        QHash<int, QPair<qreal, qreal> > hash;

        QString starsLine;
        int index;
        qreal longitude;
        qreal latitude;
        QPair<qreal, qreal> pair;
        do {
            starsLine = streamStars.readLine();
            index = starsLine.mid( 0, 4 ).toInt();

            QString recString = starsLine.mid( 75, 6 );
            double raHH = recString.mid( 0, 2 ).toDouble();
            double raMM = recString.mid( 2, 2 ).toDouble();
            double raSS = recString.mid( 4, 2 ).toDouble();

            longitude = ( raHH + raMM / 60.0 + raSS / 3600.0 ) * 15.0 - 180.0;

            QString decString = starsLine.mid( 83, 7 );
            double deSign = ( decString.mid( 0, 1 ) == "-" ) ? -1.0 : 1.0;
            double deHH = decString.mid( 1, 2 ).toDouble();
            double deMM = decString.mid( 3, 2 ).toDouble();
            double deSS = decString.mid( 5, 2 ).toDouble();

            double deValue = deSign * ( deHH + deMM / 60.0 + deSS / 3600.0 );

            latitude = deValue;

            pair.first = longitude;
            pair.second = latitude;

            hash.insert( index, pair );
        } while ( !starsLine.isNull() );

        QString name;
        QString indexList;
        QStringList starIndexes;
        while ( !streamConstellations.atEnd() ) {
            name = streamConstellations.readLine();

            // Check for null line at end of file
            if ( name.isNull() ) {
                continue;
            }

            // Ignore Comment lines in header and
            // between constellation entries
            if ( name.startsWith( '#' ) )    {
                continue;
            }

            indexList = streamConstellations.readLine();

            // Make sure we have a valid name and indexList
            if ( indexList.isNull() ) {
                break;
            }

            out << "    <Placemark> \n"
                << "        <styleUrl>#lineStyle1</styleUrl> \n"
                << "        <MultiGeometry> \n"
                << "            <LineString> \n"
                << "                <coordinates> \n";

            starIndexes = indexList.split( ' ' );
            QList<qreal> x;
            QList<qreal> y;
            QList<qreal> z;
            int numberOfStars = 0;
            for ( int i = 0; i < starIndexes.size(); ++i ) {
                if ( starIndexes.at(i) == "-1" ) {
                    out << "                </coordinates> \n"
                        << "            </LineString> \n"
                        << "            <LineString> \n"
                        << "                <coordinates> \n";
                } else if ( starIndexes.at(i) == "-2" ) {
                    out << "                </coordinates> \n"
                        << "            </LineString> \n"
                        << "        </MultiGeometry> \n"
                        << "    </Placemark> \n"
                        << "    <Placemark> \n"
                        << "        <styleUrl>#lineStyle2</styleUrl> \n"
                        << "        <MultiGeometry> \n"
                        << "            <LineString> \n"
                        << "                <coordinates> \n";
                } else if ( starIndexes.at(i) == "-3" ) {
                    out << "                </coordinates> \n"
                        << "            </LineString> \n"
                        << "        </MultiGeometry> \n"
                        << "    </Placemark> \n"
                        << "    <Placemark> \n"
                        << "        <styleUrl>#lineStyle1</styleUrl> \n"
                        << "        <MultiGeometry> \n"
                        << "            <LineString> \n"
                        << "                <coordinates> \n";
                }
                QHash<int, QPair<qreal, qreal> >::const_iterator j = hash.constFind( starIndexes.at(i).toInt() );
                while( j != hash.constEnd() && j.key() == starIndexes.at(i).toInt() ) {
                    out << "                " << j.value().first << "," << j.value().second << " \n";
                    x.append( cos( j.value().first * DEG2RAD ) * cos( j.value().second * DEG2RAD ) );
                    y.append( sin( j.value().first * DEG2RAD ) * cos( j.value().second * DEG2RAD ) );
                    z.append( sin( j.value().second * DEG2RAD ) );
                    ++numberOfStars;
                    ++j;
                }
            }

            out << "                </coordinates> \n"
                << "            </LineString> \n"
                << "        </MultiGeometry> \n"
                << "    </Placemark> \n";

            qreal xMean = 0.0;
            qreal yMean = 0.0;
            qreal zMean = 0.0;
            for ( int s = 0; s < numberOfStars; ++s ) {
                xMean += x.at(s);
                yMean += y.at(s);
                zMean += z.at(s);
            }

            xMean = xMean / numberOfStars;
            yMean = yMean / numberOfStars;
            zMean = zMean / numberOfStars;

            qreal labelLongitude = RAD2DEG * atan2( yMean, xMean );
            qreal labelLatitude = RAD2DEG * atan2( zMean, sqrt( xMean * xMean + yMean * yMean ) );

            out << "    <Placemark> \n"
                << "        <styleUrl>#iconStyle</styleUrl> \n"
                << "        <name>" << name << "</name> \n"
                << "        <Point> \n"
                << "            <coordinates>" << labelLongitude << "," << labelLatitude << "</coordinates> \n"
                << "        </Point> \n"
                << "    </Placemark> \n";
        }
    }

    out << "</Document> \n"
        << "</kml> \n";

    constellationsData.close();
    starsData.close();
    file.close();

    app.exit();
}
QVariantMap QgsZonalHistogramAlgorithm::processAlgorithm( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{

  std::unique_ptr< QgsFeatureSource > zones( parameterAsSource( parameters, QStringLiteral( "INPUT_VECTOR" ), context ) );
  if ( !zones )
    throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT_VECTOR" ) ) );

  long count = zones->featureCount();
  double step = count > 0 ? 100.0 / count : 1;
  long current = 0;

  QList< double > uniqueValues;
  QMap< QgsFeatureId, QHash< double, qgssize > > featuresUniqueValues;

  // First loop through the zones to build up a list of unique values across all zones to determine sink fields list
  QgsFeatureRequest request;
  request.setNoAttributes();
  if ( zones->sourceCrs() != mCrs )
  {
    request.setDestinationCrs( mCrs, context.transformContext() );
  }
  QgsFeatureIterator it = zones->getFeatures( request );
  QgsFeature f;
  while ( it.nextFeature( f ) )
  {
    if ( feedback && feedback->isCanceled() )
    {
      break;
    }
    feedback->setProgress( current * step );

    if ( !f.hasGeometry() )
    {
      current++;
      continue;
    }

    QgsGeometry featureGeometry = f.geometry();
    QgsRectangle featureRect = featureGeometry.boundingBox().intersect( mRasterExtent );
    if ( featureRect.isEmpty() )
    {
      current++;
      continue;
    }

    int nCellsX, nCellsY;
    QgsRectangle rasterBlockExtent;
    QgsRasterAnalysisUtils::cellInfoForBBox( mRasterExtent, featureRect, mCellSizeX, mCellSizeY, nCellsX, nCellsY, mNbCellsXProvider, mNbCellsYProvider, rasterBlockExtent );

    QHash< double, qgssize > fUniqueValues;
    QgsRasterAnalysisUtils::statisticsFromMiddlePointTest( mRasterInterface.get(), mRasterBand, featureGeometry, nCellsX, nCellsY, mCellSizeX, mCellSizeY,
    rasterBlockExtent, [ &fUniqueValues]( double value ) { fUniqueValues[value]++; }, false );

    if ( fUniqueValues.count() < 1 )
    {
      // The cell resolution is probably larger than the polygon area. We switch to slower precise pixel - polygon intersection in this case
      // TODO: eventually deal with weight if needed
      QgsRasterAnalysisUtils::statisticsFromPreciseIntersection( mRasterInterface.get(), mRasterBand, featureGeometry, nCellsX, nCellsY, mCellSizeX, mCellSizeY,
      rasterBlockExtent, [ &fUniqueValues]( double value, double ) { fUniqueValues[value]++; }, false );
    }

    for ( auto it = fUniqueValues.constBegin(); it != fUniqueValues.constEnd(); ++it )
    {
      if ( uniqueValues.indexOf( it.key() ) == -1 )
      {
        uniqueValues << it.key();
      }
      featuresUniqueValues[f.id()][it.key()] += it.value();
    }

    current++;
  }

  std::sort( uniqueValues.begin(), uniqueValues.end() );

  QString fieldPrefix = parameterAsString( parameters, QStringLiteral( "COLUMN_PREFIX" ), context );
  QgsFields newFields;
  for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
  {
    newFields.append( QgsField( QStringLiteral( "%1%2" ).arg( fieldPrefix, mHasNoDataValue && *it == mNodataValue ? QStringLiteral( "NODATA" ) : QString::number( *it ) ), QVariant::LongLong, QString(), -1, 0 ) );
  }
  QgsFields fields = QgsProcessingUtils::combineFields( zones->fields(), newFields );

  QString dest;
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, fields,
                                          zones->wkbType(), zones->sourceCrs() ) );
  if ( !sink )
    throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );

  it = zones->getFeatures( QgsFeatureRequest() );
  while ( it.nextFeature( f ) )
  {
    QgsAttributes attributes = f.attributes();
    QHash< double, qgssize > fUniqueValues = featuresUniqueValues.value( f.id() );
    for ( auto it = uniqueValues.constBegin(); it != uniqueValues.constEnd(); ++it )
    {
      attributes += fUniqueValues.value( *it, 0 );
    }

    QgsFeature outputFeature;
    outputFeature.setGeometry( f.geometry() );
    outputFeature.setAttributes( attributes );

    sink->addFeature( outputFeature, QgsFeatureSink::FastInsert );
  }

  QVariantMap outputs;
  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
  return outputs;
}
void QSGSharedDistanceFieldGlyphCache::processPendingGlyphs()
{
    Q_ASSERT(QThread::currentThread() == thread());

    waitForGlyphs();

    {
        QMutexLocker locker(&m_pendingGlyphsMutex);
        if (m_pendingMissingGlyphs.isEmpty()
            && m_pendingReadyGlyphs.isEmpty()
            && m_pendingInvalidatedGlyphs.isEmpty()) {
            return;
        }

        {
            QVector<glyph_t> pendingMissingGlyphs;
            pendingMissingGlyphs.reserve(m_pendingMissingGlyphs.size());

            QSet<glyph_t>::const_iterator it = m_pendingMissingGlyphs.constBegin();
            while (it != m_pendingMissingGlyphs.constEnd()) {
                pendingMissingGlyphs.append(*it);
                ++it;
            }

            markGlyphsToRender(pendingMissingGlyphs);
        }

        {
            QVector<glyph_t> filteredPendingInvalidatedGlyphs;
            filteredPendingInvalidatedGlyphs.reserve(m_pendingInvalidatedGlyphs.size());

            QSet<glyph_t>::const_iterator it = m_pendingInvalidatedGlyphs.constBegin();
            while (it != m_pendingInvalidatedGlyphs.constEnd()) {
                bool rerequestGlyph = false;

                // The glyph was invalidated right after being posted as ready, we throw away
                // the ready glyph and rerequest it to be certain
                QHash<quint32, PendingGlyph>::iterator pendingGlyphIt = m_pendingReadyGlyphs.find(*it);
                if (pendingGlyphIt != m_pendingReadyGlyphs.end()) {
                    m_sharedGraphicsCache->dereferenceBuffer(pendingGlyphIt.value().buffer);
                    pendingGlyphIt = m_pendingReadyGlyphs.erase(pendingGlyphIt);
                    rerequestGlyph = true;
                }

                void *bufferId = m_bufferForGlyph.value(*it, 0);
                if (bufferId != 0) {
                    m_sharedGraphicsCache->dereferenceBuffer(bufferId);
                    m_bufferForGlyph.remove(*it);
                    rerequestGlyph = true;
                }

                if (rerequestGlyph)
                    filteredPendingInvalidatedGlyphs.append(*it);

                ++it;
            }

            // If this cache is still using the glyphs, reset the texture held by them, and mark them
            // to be rendered again since they are still needed.
            if (!filteredPendingInvalidatedGlyphs.isEmpty()) {
                setGlyphsTexture(filteredPendingInvalidatedGlyphs, Texture());
                markGlyphsToRender(filteredPendingInvalidatedGlyphs);
            }
        }

        {
            QList<GlyphPosition> glyphPositions;

            QHash<void *, TextureContent> textureContentForBuffer;
            {
                QHash<quint32, PendingGlyph>::iterator it = m_pendingReadyGlyphs.begin();
                while (it != m_pendingReadyGlyphs.end()) {
                    void *currentGlyphBuffer = m_bufferForGlyph.value(it.key(), 0);
                    if (currentGlyphBuffer != 0) {
                        if (!m_sharedGraphicsCache->dereferenceBuffer(currentGlyphBuffer)) {
                            Q_ASSERT(!textureContentForBuffer.contains(currentGlyphBuffer));
                        }
                    }

                    PendingGlyph &pendingGlyph  = it.value();

                    // We don't ref or deref the buffer here, since it was already referenced when
                    // added to the pending ready glyphs
                    m_bufferForGlyph[it.key()] = pendingGlyph.buffer;

                    textureContentForBuffer[pendingGlyph.buffer].size = pendingGlyph.bufferSize;
                    textureContentForBuffer[pendingGlyph.buffer].glyphs.append(it.key());

                    GlyphPosition glyphPosition;
                    glyphPosition.glyph = it.key();
                    glyphPosition.position = pendingGlyph.position;

                    glyphPositions.append(glyphPosition);

                    ++it;
                }
            }

            setGlyphsPosition(glyphPositions);

            {
                QHash<void *, TextureContent>::const_iterator it = textureContentForBuffer.constBegin();
                while (it != textureContentForBuffer.constEnd()) {
                    Texture texture;
                    texture.textureId = m_sharedGraphicsCache->textureIdForBuffer(it.key());
                    texture.size = m_sharedGraphicsCache->sizeOfBuffer(it.key());

#if defined(QSGSHAREDDISTANCEFIELDGLYPHCACHE_DEBUG_)
                    saveTexture(texture.textureId, texture.size.width(), texture.size.height());
#endif
                    setGlyphsTexture(it.value().glyphs, texture);

                    ++it;
                }
            }
        }

        m_pendingMissingGlyphs.clear();
        m_pendingInvalidatedGlyphs.clear();
        m_pendingReadyGlyphs.clear();
    }
}
QVariantMap QgsCollectorAlgorithm::processCollection( const QVariantMap &parameters, QgsProcessingContext &context, QgsProcessingFeedback *feedback,
    const std::function<QgsGeometry( const QVector< QgsGeometry >& )> &collector, int maxQueueLength )
{
  std::unique_ptr< QgsFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) );
  if ( !source )
    throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) );

  QString dest;
  std::unique_ptr< QgsFeatureSink > sink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, dest, source->fields(), QgsWkbTypes::multiType( source->wkbType() ), source->sourceCrs() ) );

  if ( !sink )
    throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) );

  QStringList fields = parameterAsFields( parameters, QStringLiteral( "FIELD" ), context );

  long count = source->featureCount();

  QgsFeature f;
  QgsFeatureIterator it = source->getFeatures();

  double step = count > 0 ? 100.0 / count : 1;
  int current = 0;

  if ( fields.isEmpty() )
  {
    // dissolve all - not using fields
    bool firstFeature = true;
    // we dissolve geometries in blocks using unaryUnion
    QVector< QgsGeometry > geomQueue;
    QgsFeature outputFeature;

    while ( it.nextFeature( f ) )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      if ( firstFeature )
      {
        outputFeature = f;
        firstFeature = false;
      }

      if ( f.hasGeometry() && !f.geometry().isNull() )
      {
        geomQueue.append( f.geometry() );
        if ( maxQueueLength > 0 && geomQueue.length() > maxQueueLength )
        {
          // queue too long, combine it
          QgsGeometry tempOutputGeometry = collector( geomQueue );
          geomQueue.clear();
          geomQueue << tempOutputGeometry;
        }
      }

      feedback->setProgress( current * step );
      current++;
    }

    outputFeature.setGeometry( collector( geomQueue ) );
    sink->addFeature( outputFeature, QgsFeatureSink::FastInsert );
  }
  else
  {
    QList< int > fieldIndexes;
    const auto constFields = fields;
    for ( const QString &field : constFields )
    {
      int index = source->fields().lookupField( field );
      if ( index >= 0 )
        fieldIndexes << index;
    }

    QHash< QVariant, QgsAttributes > attributeHash;
    QHash< QVariant, QVector< QgsGeometry > > geometryHash;

    while ( it.nextFeature( f ) )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      QVariantList indexAttributes;
      const auto constFieldIndexes = fieldIndexes;
      for ( int index : constFieldIndexes )
      {
        indexAttributes << f.attribute( index );
      }

      if ( !attributeHash.contains( indexAttributes ) )
      {
        // keep attributes of first feature
        attributeHash.insert( indexAttributes, f.attributes() );
      }

      if ( f.hasGeometry() && !f.geometry().isNull() )
      {
        geometryHash[ indexAttributes ].append( f.geometry() );
      }
    }

    int numberFeatures = attributeHash.count();
    QHash< QVariant, QgsAttributes >::const_iterator attrIt = attributeHash.constBegin();
    for ( ; attrIt != attributeHash.constEnd(); ++attrIt )
    {
      if ( feedback->isCanceled() )
      {
        break;
      }

      QgsFeature outputFeature;
      if ( geometryHash.contains( attrIt.key() ) )
      {
        QgsGeometry geom = collector( geometryHash.value( attrIt.key() ) );
        if ( !geom.isMultipart() )
        {
          geom.convertToMultiType();
        }
        outputFeature.setGeometry( geom );
      }
      outputFeature.setAttributes( attrIt.value() );
      sink->addFeature( outputFeature, QgsFeatureSink::FastInsert );

      feedback->setProgress( current * 100.0 / numberFeatures );
      current++;
    }
  }

  QVariantMap outputs;
  outputs.insert( QStringLiteral( "OUTPUT" ), dest );
  return outputs;
}
void QInotifyFileSystemWatcherEngine::readFromInotify()
{
    QMutexLocker locker(&mutex);

    // qDebug() << "QInotifyFileSystemWatcherEngine::readFromInotify";

    int buffSize = 0;
    ioctl(inotifyFd, FIONREAD, (char *) &buffSize);
    QVarLengthArray<char, 4096> buffer(buffSize);
    buffSize = read(inotifyFd, buffer.data(), buffSize);
    char *at = buffer.data();
    char * const end = at + buffSize;

    QHash<int, inotify_event *> eventForId;
    while (at < end) {
        inotify_event *event = reinterpret_cast<inotify_event *>(at);

        if (eventForId.contains(event->wd))
            eventForId[event->wd]->mask |= event->mask;
        else
            eventForId.insert(event->wd, event);

        at += sizeof(inotify_event) + event->len;
    }

    QHash<int, inotify_event *>::const_iterator it = eventForId.constBegin();
    while (it != eventForId.constEnd()) {
        const inotify_event &event = **it;
        ++it;

        // qDebug() << "inotify event, wd" << event.wd << "mask" << hex << event.mask;

        int id = event.wd;
        QString path = idToPath.value(id);
        if (path.isEmpty()) {
            // perhaps a directory?
            id = -id;
            path = idToPath.value(id);
            if (path.isEmpty())
                continue;
        }

        // qDebug() << "event for path" << path;

        if ((event.mask & (IN_DELETE_SELF | IN_MOVE_SELF | IN_UNMOUNT)) != 0) {
            pathToID.remove(path);
            idToPath.remove(id);
            inotify_rm_watch(inotifyFd, event.wd);

            if (id < 0)
                emit directoryChanged(path, true);
            else
                emit fileChanged(path, true);
        } else {
            if (id < 0)
                emit directoryChanged(path, false);
            else
                emit fileChanged(path, false);
        }
    }
}
    // TODO: test signals
    void testMove()
    {
        QFETCH( Collection, source );
        QFETCH( Collection, destination );
        QFETCH( bool, crossResource );
        QVERIFY( source.isValid() );
        QVERIFY( destination.isValid() );

        CollectionFetchJob *fetch = new CollectionFetchJob( source, CollectionFetchJob::Base, this );
        AKVERIFYEXEC( fetch );
        QCOMPARE( fetch->collections().count(), 1 );
        source = fetch->collections().first();

        // obtain reference listing
        fetch = new CollectionFetchJob( source, CollectionFetchJob::Recursive );
        AKVERIFYEXEC( fetch );
        QHash<Collection, Item::List> referenceData;
        foreach ( const Collection &c, fetch->collections() ) {
            ItemFetchJob *job = new ItemFetchJob( c, this );
            AKVERIFYEXEC( job );
            referenceData.insert( c, job->items() );
        }

        // move collection
        CollectionMoveJob *mod = new CollectionMoveJob( source, destination, this );
        AKVERIFYEXEC( mod );

        // check if source was modified correctly
        CollectionFetchJob *ljob = new CollectionFetchJob( source, CollectionFetchJob::Base );
        AKVERIFYEXEC( ljob );
        Collection::List list = ljob->collections();

        QCOMPARE( list.count(), 1 );
        Collection col = list.first();
        QCOMPARE( col.name(), source.name() );
        QCOMPARE( col.parentCollection(), destination );

        // list destination and check if everything is still there
        ljob = new CollectionFetchJob( destination, CollectionFetchJob::Recursive );
        AKVERIFYEXEC( ljob );
        list = ljob->collections();

        QVERIFY( list.count() >= referenceData.count() );
        for ( QHash<Collection, Item::List>::ConstIterator it = referenceData.constBegin(); it != referenceData.constEnd(); ++it ) {
            QVERIFY( list.contains( it.key() ) );
            if ( crossResource ) {
                QVERIFY( list[ list.indexOf( it.key() ) ].resource() != it.key().resource() );
            } else {
                QCOMPARE( list[ list.indexOf( it.key() ) ].resource(), it.key().resource() );
            }
            ItemFetchJob *job = new ItemFetchJob( it.key(), this );
            job->fetchScope().fetchFullPayload();
            AKVERIFYEXEC( job );
            QCOMPARE( job->items().count(), it.value().count() );
            foreach ( const Item &item, job->items() ) {
                QVERIFY( it.value().contains( item ) );
                QVERIFY( item.hasPayload() );
            }
        }

        // cleanup
        mod = new CollectionMoveJob( col, source.parentCollection(), this );
        AKVERIFYEXEC( mod );
    }
Exemple #15
0
QVector<QgsDataItem *> QgsGeoNodeServiceItem::createChildren()
{
  QVector<QgsDataItem *> children;
  QHash<QgsDataItem *, QString> serviceItems; // service/provider key

  int layerCount = 0;
  // Try to open with service provider
  bool skipProvider = false;

  QgsGeoNodeConnectionItem *parentItem = dynamic_cast<QgsGeoNodeConnectionItem *>( mParent );
  QString pathPrefix = parentItem->mGeoNodeName.toLower() + QStringLiteral( ":/" );

  while ( !skipProvider )
  {
    const QString &key = mServiceName != QStringLiteral( "WFS" ) ? QStringLiteral( "wms" ) : mServiceName;
    std::unique_ptr< QLibrary > library( QgsProviderRegistry::instance()->createProviderLibrary( key ) );
    if ( !library )
    {
      skipProvider = true;
      continue;
    }

    dataItemProviders_t *dataItemProvidersFn = reinterpret_cast< dataItemProviders_t * >( cast_to_fptr( library->resolve( "dataItemProviders" ) ) );
    dataItem_t *dItem = ( dataItem_t * ) cast_to_fptr( library->resolve( "dataItem" ) );
    if ( !dItem && !dataItemProvidersFn )
    {
      skipProvider = true;
      continue;
    }

    QString path = pathPrefix + mName;

    QVector<QgsDataItem *> items;
    QList<QgsDataItemProvider *> *providerList = dataItemProvidersFn();
    for ( QgsDataItemProvider *pr : qgis::as_const( *providerList ) )
    {
      if ( !pr->name().startsWith( mServiceName ) )
        continue;

      items = pr->createDataItems( path, this );
      if ( !items.isEmpty() )
      {
        break;
      }
    }

    if ( items.isEmpty() )
    {
      skipProvider = true;
      continue;
    }

    if ( mServiceName == QStringLiteral( "XYZ" ) )
    {
      return items;
    }

    for ( QgsDataItem *item : qgis::as_const( items ) )
    {
      item->populate( true ); // populate in foreground - this is already run in a thread

      layerCount += item->rowCount();
      if ( item->rowCount() > 0 )
      {
        serviceItems.insert( item, key );
      }
      else
      {
        //delete item;
      }
    }

    skipProvider = true;
  }

  auto serviceItemIt = serviceItems.constBegin();
  for ( ; serviceItemIt != serviceItems.constEnd(); ++serviceItemIt )
  {
    QgsDataItem *item = serviceItemIt.key();
    QString providerKey = serviceItemIt.value();

    // Add layers directly to service item
    const QVector< QgsDataItem * > serviceChildItems = item->children();
    for ( QgsDataItem *subItem : serviceChildItems )
    {
      if ( subItem->path().endsWith( QStringLiteral( "error" ) ) )
      {
        continue;
      }
      item->removeChildItem( subItem );
      subItem->setParent( this );
      replacePath( subItem, providerKey.toLower() + QStringLiteral( ":/" ), pathPrefix );
      children.append( subItem );
    }

    delete item;
  }

  return children;
}
Exemple #16
0
void Locator::buildPathDistMat( const QHash<SymbolPath, SymbolData>& symbolWordList, 
							    Eigen::MatrixXd& distMat, 
								Eigen::VectorXd& radiusVec,
								Eigen::VectorXd& alignVec)
{
	// add to path index map
	QHash<SymbolPath, int> pathIdxMap;
	QList<QString> pathStrVec;
	int ithPath = 0;
	for (QHash<SymbolPath, SymbolData>::ConstIterator pPath = symbolWordList.constBegin();
		pPath != symbolWordList.constEnd(); ++pPath, ++ithPath)
	{
		pathIdxMap[pPath.key()] = ithPath;
		pathStrVec.push_back(pPath.key().getLastSymbol()->toString());
	}

	// build adjencency matrix
	int n = ithPath;
	ithPath = 0;
	radiusVec.resize(n);
	alignVec = Eigen::VectorXd::Ones(n);
	Eigen::MatrixXf adjMat = Eigen::MatrixXf::Constant(n,n,-1);
	for (QHash<SymbolPath, SymbolData>::ConstIterator pPath = symbolWordList.constBegin();
		pPath != symbolWordList.constEnd(); ++pPath, ++ithPath)
	{
		const SymbolData& symData = pPath.value();
		const SymbolPath& symPath = pPath.key();
		int   srcIdx = pathIdxMap[pPath.key()];

		for (QSet<SymbolPath>::ConstIterator pChild = symData.m_lowLevelSym.constBegin();
			pChild != symData.m_lowLevelSym.constEnd(); ++pChild)
		{
			QHash<SymbolPath, int>::ConstIterator pTar = pathIdxMap.find(*pChild);
			if (pTar == pathIdxMap.constEnd())
				continue;
			int tarIdx = pTar.value();
			adjMat(srcIdx, tarIdx) = adjMat(tarIdx, srcIdx) = 1;
		}

		radiusVec(ithPath) = symData.getRadius();
		if(const SymbolInfo* info = symPath.getLastSymbol())
		{
			alignVec(ithPath) = MDSSolver::getAlignVal(info->name());
		}
	}

	// build distance matrix
	MatrixXf dMat;
	GraphUtility::computePairDist(adjMat, dMat);
	distMat = dMat.cast<double>();

	// save mats for debug
	QString matStr = GlobalUtility::toMatlabString(adjMat, "adjMat");
	matStr +=        GlobalUtility::toMatlabString(dMat, "distMat");
	matStr +=        GlobalUtility::toMatlabString(pathStrVec, "entityName");
	matStr +=        "adjMat(find(adjMat<0)) = 0;\n";
	GlobalUtility::saveString("H:\\Programs\\QtCreator\\qt-creator_master\\src\\plugins\\MyPlugin\\CodeAtlas\\tests\\2-20\\matStr.m", matStr);

	// fill distances of different connect components 
	float maxDist= distMat.maxCoeff() * 2.f;
	for (int i = 0; i < distMat.rows(); i++)
		for (int j = 0; j < distMat.cols(); j++)
			if (distMat(i,j) == -1)
				distMat(i,j) = maxDist;
}
QVariantMap AddKitOperation::addKit(const QVariantMap &map, const QVariantMap &tcMap,
                                    const QVariantMap &qtMap, const QVariantMap &devMap,
                                    const QVariantMap &cmakeMap,
                                    const QString &id, const QString &displayName,
                                    const QString &icon, const QString &debuggerId,
                                    const quint32 &debuggerType, const QString &debugger,
                                    const QString &deviceType, const QString &device,
                                    const QString &sysRoot, const QHash<QString, QString> &tcs, const QString &qt,
                                    const QString &mkspec, const QString &cmakeId,
                                    const QString &cmakeGenerator, const QString &cmakeExtraGenerator,
                                    const QString &cmakeGeneratorToolset,
                                    const QString &cmakeGeneratorPlatform,
                                    const QStringList &cmakeConfiguration, const QStringList &env,
                                    const KeyValuePairList &extra)
{
    // Sanity check: Make sure autodetection source is not in use already:
    QStringList valueKeys = FindValueOperation::findValue(map, QVariant(id));
    bool hasId = false;
    foreach (const QString &k, valueKeys) {
        if (k.endsWith(QString('/') + ID)) {
            hasId = true;
            break;
        }
    }
    if (hasId) {
        std::cerr << "Error: Id " << qPrintable(id) << " already defined as kit." << std::endl;
        return QVariantMap();
    }

    for (auto i = tcs.constBegin(); i != tcs.constEnd(); ++i) {
        if (!i.value().isEmpty() && !AddToolChainOperation::exists(tcMap, i.value())) {
            QRegExp abiRegExp = QRegExp("[a-z0-9_]+-[a-z0-9_]+-[a-z0-9_]+-[a-z0-9_]+-(8|16|32|64|128)bit");
            if (!abiRegExp.exactMatch(i.value())) {
                std::cerr << "Error: Toolchain " << qPrintable(i.value())
                          << " for language " << qPrintable(i.key()) << " does not exist." << std::endl;
                return QVariantMap();
            }
        }
    }

    QString qtId = qt;
    if (!qtId.isEmpty() && !qtId.startsWith("SDK."))
        qtId = QString::fromLatin1("SDK.") + qt;
    if (!qtId.isEmpty() && !AddQtOperation::exists(qtMap, qtId)) {
        std::cerr << "Error: Qt " << qPrintable(qtId) << " does not exist." << std::endl;
        return QVariantMap();
    }
    if (!device.isEmpty() && !AddDeviceOperation::exists(devMap, device)) {
        std::cerr << "Error: Device " << qPrintable(device) << " does not exist." << std::endl;
        return QVariantMap();
    }
    if (!cmakeId.isEmpty() && !AddCMakeOperation::exists(cmakeMap, cmakeId)) {
        std::cerr << "Error: CMake tool " << qPrintable(cmakeId) << " does not exist." << std::endl;
        return QVariantMap();
    }

    // Find position to insert:
    bool ok;
    int count = GetOperation::get(map, COUNT).toInt(&ok);
    if (!ok || count < 0) {
        std::cerr << "Error: Count found in kits file seems wrong." << std::endl;
        return QVariantMap();
    }
    const QString kit = QString::fromLatin1(PREFIX) + QString::number(count);

    QString defaultKit = GetOperation::get(map, DEFAULT).toString();
    if (defaultKit.isEmpty())
        defaultKit = id;

    // remove data:
    QVariantMap cleaned = RmKeysOperation::rmKeys(map, { COUNT, DEFAULT });

    // Sanity check: Make sure displayName is unique.
    QStringList nameKeys = FindKeyOperation::findKey(map, DISPLAYNAME);
    QStringList nameList;
    foreach (const QString &nameKey, nameKeys)
        nameList << GetOperation::get(map, nameKey).toString();
    const QString uniqueName = makeUnique(displayName, nameList);

    // insert data:
    KeyValuePairList data = { KeyValuePair({ kit, ID }, QVariant(id)),
                              KeyValuePair({ kit, DISPLAYNAME }, QVariant(uniqueName)),
                              KeyValuePair({ kit, ICON }, QVariant(icon)),
                              KeyValuePair({ kit, AUTODETECTED }, QVariant(true)),
                              KeyValuePair({ kit, SDK }, QVariant(true)) };

    if (!debuggerId.isEmpty() || !debugger.isEmpty()) {
        if (debuggerId.isEmpty()) {
            data << KeyValuePair({ kit, DATA, DEBUGGER, DEBUGGER_ENGINE }, QVariant(debuggerType));
            data << KeyValuePair({ kit, DATA, DEBUGGER, DEBUGGER_BINARY }, QVariant(debugger));
        } else {
            data << KeyValuePair({ kit, DATA, DEBUGGER }, QVariant(debuggerId));
        }
    }
    if (!deviceType.isNull())
        data << KeyValuePair({ kit, DATA, DEVICE_TYPE }, QVariant(deviceType));
    if (!device.isNull())
        data << KeyValuePair({ kit, DATA, DEVICE_ID }, QVariant(device));
    if (!sysRoot.isNull())
        data << KeyValuePair({ kit, DATA, SYSROOT }, QVariant(sysRoot));
    for (auto i = tcs.constBegin(); i != tcs.constEnd(); ++i)
        data << KeyValuePair({ kit, DATA, TOOLCHAIN, i.key() }, QVariant(i.value()));
    if (!qtId.isNull())
        data << KeyValuePair({ kit, DATA, QT }, QVariant(qtId));
    if (!mkspec.isNull())
        data << KeyValuePair({ kit, DATA, MKSPEC }, QVariant(mkspec));
    if (!cmakeId.isNull())
        data << KeyValuePair({kit, DATA, CMAKE_ID}, QVariant(cmakeId));
    if (!cmakeGenerator.isNull()) {
        QVariantMap generatorMap;
        generatorMap.insert("Generator", cmakeGenerator);
        if (!cmakeExtraGenerator.isNull())
            generatorMap.insert("ExtraGenerator", cmakeExtraGenerator);
        if (!cmakeGeneratorToolset.isNull())
            generatorMap.insert("Toolset", cmakeGeneratorToolset);
        if (!cmakeGeneratorPlatform.isNull())
            generatorMap.insert("Platform", cmakeGeneratorPlatform);
        data << KeyValuePair({ kit, DATA, CMAKE_GENERATOR }, generatorMap);
    }
    if (!cmakeConfiguration.isEmpty())
        data << KeyValuePair({kit, DATA, CMAKE_CONFIGURATION}, QVariant(cmakeConfiguration));
    if (!env.isEmpty())
        data << KeyValuePair({ kit, DATA, ENV }, QVariant(env));

    data << KeyValuePair(DEFAULT, QVariant(defaultKit));
    data << KeyValuePair(COUNT, QVariant(count + 1));

    KeyValuePairList qtExtraList;
    foreach (const KeyValuePair &pair, extra)
        qtExtraList << KeyValuePair(QStringList() << kit << pair.key, pair.value);
    data.append(qtExtraList);

    return AddKeysOperation::addKeys(cleaned, data);
}
void Diagnostics::run()
{
	QString info;
	QTextStream s( &info );

	QLocale::Language language = QLocale::system().language();
	QString ctype = QProcessEnvironment::systemEnvironment().value( "LC_CTYPE",
		QProcessEnvironment::systemEnvironment().value( "LANG" ) );
	s << "<b>" << tr("Locale (time-, number format / codepage):") << "</b> "
		<< (language == QLocale::C ? "English/United States" : QLocale::languageToString( language )) << " / "
		<< ctype << "<br /><br />";
	emit update( info );
	info.clear();

#ifndef Q_OS_MAC
	QStringList package = Common::packages( { "estonianidcard" }, false );
	if( !package.isEmpty() )
		s << "<b>" << tr("Base version:") << "</b> " << package.first() << "<br />";
#endif
	s << "<b>" << tr("Application version:") << "</b> " << QCoreApplication::applicationVersion()
#ifdef INTERNATIONAL
		<< " INTERNATIONAL"
#endif
		<< "<br />";
	emit update( info );
	info.clear();

	s << "<b>" << tr("OS:") << "</b> " << Common::applicationOs() << "<br />";
#ifndef Q_OS_MAC
	s << "<b>" << tr("CPU:") << "</b> ";
	QFile f( "/proc/cpuinfo" );
	if( f.open( QFile::ReadOnly ) )
	{
		QRegExp rx( "model name.*\\: (.*)\n" );
		rx.setMinimal( true );
		if( rx.indexIn( QString::fromLocal8Bit( f.readAll() ) ) != -1 )
			s << rx.cap( 1 );
	}
	s << "<br />";
#endif
	struct utsname unameData;
	uname(&unameData);
	s << "<b>" << tr("Kernel:") << "</b> "
		<< unameData.sysname << " " << unameData.release << " "
		<< unameData.version << " " << unameData.machine << "<br /><br />";
	emit update( info );
	info.clear();

	s << "<b>" << "URLs:" << "</b>";
	const QHash<QString,QString> urls = qApp->urls();
	for(auto i = urls.constBegin(); i != urls.constEnd(); ++i)
		s << "<br />" << i.key() << ": " << i.value();
	s << "<br /><br />";

	s << "<b>" << tr("Arguments:") << "</b> " << qApp->arguments().join(" ") << "<br />";
	s << "<b>" << tr("Library paths:") << "</b> " << QCoreApplication::libraryPaths().join( ";" ) << "<br />";
	s << "<b>" << tr("Libraries") << ":</b><br />";
#ifdef Q_OS_MAC
	s << Common::packages( { "libdigidoc", "digidocpp" } ).join( "<br />" ) << "<br />";
#else
	s << Common::packages( { "libdigidoc2", "libdigidocpp0", "qdigidoc", "qesteidutil",
		"esteidpkcs11loader", "esteidfirefoxplugin", "chrome-token-signing", "openssl",
		"libpcsclite1", "pcsc-lite", "opensc", "esteid-pkcs11" } ).join( "<br />" ) << "<br />";
#endif
	s << "QT (" << qVersion() << ")" << "<br /><br />";
	emit update( info );
	info.clear();

	getReaderInfo( s );
	emit update( info );
	info.clear();

#ifndef Q_OS_MAC
	QStringList browsers = Common::packages( { "chromium-browser", "firefox", "MozillaFirefox" } );
	if( !browsers.isEmpty() )
		s << "<br /><br /><b>" << tr("Browsers:") << "</b><br />" << browsers.join( "<br />" ) << "<br /><br />";
	emit update( info );
	info.clear();

	QProcess p;
	p.start( "lsusb" );
	p.waitForFinished();
	QString cmd = QString::fromLocal8Bit( p.readAll() );
	if( !cmd.isEmpty() )
		s << "<b>" << tr("USB info:") << "</b><br/> " << cmd.replace( "\n", "<br />" ) << "<br />";
	emit update( info );
	info.clear();
#endif
}
Exemple #19
0
void ReadyInstallPage::createWidget()
{
    ui.setupUi(this);

    if (PMHandler::instance()->operationStack().operations().isEmpty()) {
        ui.formatLabel->hide();
    }

    foreach (const Operation* op, PMHandler::instance()->operationStack().operations()) {
        QHBoxLayout *horizontalLayout = new QHBoxLayout();

        QLabel *label = new QLabel(this);
        label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

        horizontalLayout->addWidget(label);

        ui.formatLayout->addLayout(horizontalLayout);
        label->setText(op->description());
    }

    QHash< QString, const Partition* > mountList = PMHandler::instance()->mountList(m_install->rootDevice());
    for (QHash< QString, const Partition* >::const_iterator i = mountList.constBegin(); i != mountList.constEnd(); ++i) {
        QHBoxLayout *horizontalLayout = new QHBoxLayout();

        QLabel *label = new QLabel(this);
        label->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);

        horizontalLayout->addWidget(label);
        ui.mountLayout->addLayout(horizontalLayout);

        QString partitionPath;
        if (i.value()->number() > 0) {
            partitionPath = QString("%1%2").arg(i.value()->devicePath()).arg(i.value()->number());
        } else {
            partitionPath = i18n("New partition (%1) on %2", i.value()->fileSystem().name(), i.value()->devicePath());
        }

        label->setText(i18n("%1 will be used as %2", partitionPath, i.key()));
    }
}
Exemple #20
0
void LogWriter::writeHtmlLogFormat(const QString& path)
{
    QFile *filePtr = new QFile(path);

    if (!filePtr->open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "DEBUG::File Writer:: file not writable";
        return;
    }

    QStringList scanValues = m_pObject->getHostName().split(' ', QString::SkipEmptyParts);
    const QString& hostName = scanValues[scanValues.size() - 1];

    QString htmlPage;
    // Html header
    htmlPage += "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.1//EN\"\"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd\">";
    htmlPage += "<html xmlns=\"http://www.w3.org/1999/xhtml\">";
    htmlPage += "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />";
    htmlPage += "<title>" + hostName + "</title>";
    // css Style
    htmlPage += "<style type=\"text/css\">";
    htmlPage += ".head { width:700px; background: #ccc; color: #000; float: left;}";
    htmlPage += ".sectionHead { width:700px; background: #ccc; color: #000; float:}";
    htmlPage += ".container { width:700px; background: #82b9ed; color: #000;}";
    htmlPage += ".title { width:700px; background: #82b9ed; color: #000; float: left;}";
    htmlPage += ".result { width:700px; background: #fff; color: #000; float: left;}";
    htmlPage += ".resultWhite { width:700px; background: #fff; color: #000; float: left;}";
    htmlPage += ".resultGrey { width:700px; background: #ccc; color: #000; float: left;}";
    htmlPage += ".space { width:700px; background: #fff; float: left; }";
    htmlPage += "</style></head>";
    //Html core
    htmlPage += "<body>";
    // hostname
    htmlPage += "<div class=\"head\"><b>Scan parameters:</b> ";
    htmlPage += m_pObject->getParameters();
    htmlPage += "</div>";

    //htmlPage += "<div class=\"space\">&nbsp;</div>";
    int index = 0;
    // Open Ports
    htmlPage += "<div class=\"container\"><div class=\"title\"><b>Services</b></div>";
    htmlPage += "<div class=\"result\">";
    Q_FOREACH(const QString & token, m_pObject->getPortOpen()) {
        if (index % 2 == 0) {
            htmlPage += "<div class=\"resultWhite\">";
        } else {
            htmlPage += "<div class=\"resultGrey\">";
        }
        index++;

        htmlPage += token + "<br/>\n";
        htmlPage += "</div>";
    }

    // close Ports
    Q_FOREACH(const QString & token, m_pObject->getPortClose()) {
        if (index % 2 == 0) {
            htmlPage += "<div class=\"resultWhite\">";
        } else {
            htmlPage += "<div class=\"resultGrey\">";
        }
        index++;

        htmlPage += token + "<br/>\n";
        htmlPage += "</div>";
    }

    // filtered/unfilteres Ports
    Q_FOREACH(const QString & token, m_pObject->getPortFiltered()) {
        if (index % 2 == 0) {
            htmlPage += "<div class=\"resultWhite\">";
        } else {
            htmlPage += "<div class=\"resultGrey\">";
        }
        index++;

        htmlPage += token + "<br/>\n";
        htmlPage += "</div>";
    }

    htmlPage += "</div></div>";
    //htmlPage += "<div class=\"space\">&nbsp;</div>";

    // Info
    htmlPage += "<div class=\"container\"><div class=\"title\"><b>General information</b></div>";
    htmlPage += "<div class=\"result\">";
    Q_FOREACH(const QString & token, m_pObject->getHostInfo()) {
        if (index % 2 == 0) {
            htmlPage += "<div class=\"resultWhite\">";
        } else {
            htmlPage += "<div class=\"resultGrey\">";
        }
        index++;

        htmlPage += token + "<br/>\n";
        htmlPage += "</div>";
    }
    htmlPage += "</div></div>";

    // Traceroute
    htmlPage += "<div class=\"container\"><div class=\"title\"><b>Traceroute information</b></div>";
    htmlPage += "<div class=\"result\">";
    Q_FOREACH(const QString & token, m_pObject->getTraceRouteInfo()) {
        if (index % 2 == 0) {
            htmlPage += "<div class=\"resultWhite\">";
        } else {
            htmlPage += "<div class=\"resultGrey\">";
        }
        index++;

        htmlPage += token + "<br/>\n";
        htmlPage += "</div>";
    }
    htmlPage += "</div></div>";
    //htmlPage += "<div class=\"space\">&nbsp;</div>";

    // scan errors/Warning
    htmlPage += "<div class=\"container\"><div class=\"title\"><b>Scan Errors/Warning</b></div>";
    htmlPage += "<div class=\"result\">";
    Q_FOREACH(const QString & token, m_pObject->getErrorScan()) {
        if (index % 2 == 0) {
            htmlPage += "<div class=\"resultWhite\">";
        } else {
            htmlPage += "<div class=\"resultGrey\">";
        }
        index++;

        htmlPage += token + "<br/>\n";
        htmlPage += "</div>";
    }
    htmlPage += "</div></div>";
    htmlPage += "<div class=\"space\">&nbsp;</div>";

    // Show Nss Info
    htmlPage += "<div class=\"sectionHead\"><b>Nse result</b></div>";
    //htmlPage += "<div class=\"space\">&nbsp;</div>";
    QHash<QString, QStringList> nseResult = m_pObject->getNseResult();
    QHash<QString, QStringList>::const_iterator i;

    for (i = nseResult.constBegin(); i != nseResult.constEnd(); ++i) {
        htmlPage += "<div class=\"container\"><div class=\"title\">";
        htmlPage += "<b>" + i.key() + "</b>\n";
        htmlPage += "</div>";

        htmlPage += "<div class=\"result\">";
        Q_FOREACH(const QString & value, i.value()) {
            if (index % 2 == 0) {
                htmlPage += "<div class=\"resultWhite\">";
            } else {
                htmlPage += "<div class=\"resultGrey\">";
            }
            index++;

            htmlPage += value + "<br/>\n";
            htmlPage += "</div>";
        }

        htmlPage += "</div></div>";
    }
    htmlPage += "<div class=\"space\">&nbsp;</div>";
    htmlPage += "</body></html>";

    // write html page into file
    QTextStream fileStream(filePtr);
    fileStream << htmlPage;

    filePtr->close();
    delete filePtr;
}
Exemple #21
0
void
FormMain::folderChanged( QTreeWidgetItem * current, QTreeWidgetItem * )
{
	editInfo->clear();

	if ( ! current )
		return;

	const int folder_id = current->data( 0, Qt::UserRole ).toInt();

	QString text("Folder: ");

	QSqlQuery q;

	// self
	q.prepare("SELECT "
			"name, "
			"path, "
			"size "
		"FROM "
			"folders "
		"WHERE "
			"id = :id ");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		if ( q.first() )
			text += q.value( 0 ).toString() + "<BR>" +
				"Path: " + q.value( 1 ).toString() + "<BR>" +
				"Size: " + prettyPrint( q.value( 2 ).toLongLong() ) + "<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	// count of folders
	int folderCount = 0;
	countFolders( folder_id, folderCount );

	// count of types
	int typeCount = 0;
	QHash< QString, int > types;
	countTypes( folder_id, types, typeCount );

	// ordering
	QMultiMap< int, QString > typesMap;
	QHash< QString, int >::const_iterator h = types.constBegin();

	while ( h != types.constEnd() ) {
		typesMap.insert( h.value(), h.key() );
		++h;
	}

	// percent of folders
	text += tr("folders: %1 (%2%)<BR>")
		.arg( folderCount )
		.arg( folderCount / ( qreal )( folderCount + typeCount ) * 100., 0, 'f', 1 );

	// percents of files

	chart->clear();

	if ( typesMap.count() > 0 ) {
		QMultiMap< int, QString >::const_iterator mm = typesMap.constEnd();

		do {
			--mm;

			const qreal percent = mm.key() / ( qreal )( folderCount + typeCount ) * 100;

			text += tr("%1: %2 (%3%)<BR>")
				.arg( mm.value() )
				.arg( mm.key() )
				.arg( percent, 0, 'f', 1 );

			chart->addPiece( percent, mm.value() );

		} while ( mm != typesMap.constBegin() );
	}

	text += QString( 50, '-' ) + "<BR>";		// horizontal line -------

	// folders
	text += "<BR><B>folders:</B><BR>";

	q.prepare("SELECT "
			"name, "
			"size "
		"FROM "
			"folders "
		"WHERE "
			"parent_id = :id "
		"ORDER BY "
			"size DESC");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		while ( q.next() )
			text += q.value( 0 ).toString() +
				" (" + prettyPrint( q.value( 1 ).toLongLong() ) + ")<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	// files
	text += "<BR><B>files:</B><BR>";

	q.prepare("SELECT "
			"name, "
			"size "
		"FROM "
			"files "
		"WHERE "
			"folders_id = :id "
		"ORDER BY "
			"size DESC");

	q.bindValue(":id", folder_id );

	if ( q.exec() ) {
		while ( q.next() )
			text += q.value( 0 ).toString() +
				" (" + prettyPrint( q.value( 1 ).toLongLong() ) + ")<BR>";

	} else {
		emit yell( q.lastError().text() );
		return;
	}

	editInfo->setHtml( text );
}
Exemple #22
0
void LogWriter::writeFancyLogFormat(const QString& path)
{
    QFile *filePtr = new QFile(path);

    if (!filePtr->open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "DEBUG::File Writer:: file not writable";
        return;
    }

    QTextStream fileStream(filePtr);

    // hostname
    fileStream << "\n" << m_pObject->getParameters() << "\n\n";
    fileStream << "|---------- Services" << "\n\n";

    // Open Ports
    Q_FOREACH(const QString & token, m_pObject->getPortOpen()) {
        fileStream << token << "\n";
    }

    // close Ports
    Q_FOREACH(const QString & token, m_pObject->getPortClose()) {
        fileStream << token << "\n";
    }

    // filtered/unfilteres Ports
    Q_FOREACH(const QString & token, m_pObject->getPortFiltered()) {
        fileStream << token << "\n";
    }

    fileStream << "\n|---------- General information" << "\n\n";

    // filtered/unfilteres Ports
    Q_FOREACH(const QString & token, m_pObject->getHostInfo()) {
        fileStream << token << "\n";
    }

    fileStream << "\n|---------- Traceroute information" << "\n\n";

    // Traceroute info
    Q_FOREACH(const QString & token, m_pObject->getTraceRouteInfo()) {
        fileStream << token << "\n";
    }

    fileStream << "\n|---------- Nse result" << "\n";

    // Show Nss Info
    QHash<QString, QStringList> nseResult = m_pObject->getNseResult();
    QHash<QString, QStringList>::const_iterator i;

    for (i = nseResult.constBegin(); i != nseResult.constEnd(); ++i) {
        fileStream << "\n--- " << i.key() << "\n\n";

        Q_FOREACH(const QString & value, i.value()) {
            fileStream << value << "\n";
        }
    }

    fileStream << "\n|---------- Scan Errors/Warning" << "\n\n";

    // scan errors/Warning
    Q_FOREACH(const QString & token, m_pObject->getErrorScan()) {
        fileStream << token << "\n";
    }

    filePtr->close();
    delete filePtr;
}
Exemple #23
0
void NetworkManager::sslError(QNetworkReply* reply, QList<QSslError> errors)
{
    if (m_ignoreAllWarnings || reply->property("downReply").toBool()) {
        reply->ignoreSslErrors(errors);
        return;
    }

    QNetworkRequest request = reply->request();
    QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
    WebPage* webPage = static_cast<WebPage*>(v.value<void*>());
    if (!WebPage::isPointerSafeToUse(webPage)) {
        return;
    }

    QHash<QSslCertificate, QStringList> errorHash;
    foreach(const QSslError & error, errors) {
        // Weird behavior on Windows
        if (error.error() == QSslError::NoError) {
            continue;
        }

        const QSslCertificate &cert = error.certificate();

        if (errorHash.contains(cert)) {
            errorHash[cert].append(error.errorString());
        }
        else {
            errorHash.insert(cert, QStringList(error.errorString()));
        }
    }

    // User already rejected those certs on this page
    if (webPage->containsRejectedCerts(errorHash.keys())) {
        return;
    }

    QString title = tr("SSL Certificate Error!");
    QString text1 = tr("The page you are trying to access has the following errors in the SSL certificate:");

    QString certs;

    QHash<QSslCertificate, QStringList>::const_iterator i = errorHash.constBegin();
    while (i != errorHash.constEnd()) {
        const QSslCertificate &cert = i.key();
        const QStringList &errors = i.value();

        if (m_localCerts.contains(cert) || errors.isEmpty()) {
            ++i;
            continue;
        }

        certs += "<ul><li>";
        certs += tr("<b>Organization: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::Organization));
        certs += "</li><li>";
        certs += tr("<b>Domain Name: </b>") + CertificateInfoWidget::clearCertSpecialSymbols(cert.subjectInfo(QSslCertificate::CommonName));
        certs += "</li><li>";
        certs += tr("<b>Expiration Date: </b>") + cert.expiryDate().toString("hh:mm:ss dddd d. MMMM yyyy");
        certs += "</li></ul>";

        certs += "<ul>";
        foreach(const QString & error, errors) {
            certs += "<li>";
            certs += tr("<b>Error: </b>") + error;
            certs += "</li>";
        }
        certs += "</ul>";

        ++i;
    }
void TemplateOptionsPage::load(const SourceFileTemplate& fileTemplate, TemplateRenderer* renderer)
{
    d->entries.clear();

    QLayout* layout = new QVBoxLayout();
    QHash<QString, QList<SourceFileTemplate::ConfigOption> > options = fileTemplate.customOptions(renderer);
    QHash<QString, QList<SourceFileTemplate::ConfigOption> >::const_iterator it;

    for (it = options.constBegin(); it != options.constEnd(); ++it)
    {
        QGroupBox* box = new QGroupBox(this);
        box->setTitle(it.key());

        QFormLayout* formLayout = new QFormLayout;

        d->entries << it.value();
        foreach (const SourceFileTemplate::ConfigOption& entry, it.value())
        {
            QLabel* label = new QLabel(entry.label, box);
            QWidget* control = nullptr;
            const QString type = entry.type;
            if (type == QLatin1String("String"))
            {
                control = new QLineEdit(entry.value.toString(), box);
            }
            else if (type == QLatin1String("Int"))
            {
                auto input = new QSpinBox(box);
                input->setValue(entry.value.toInt());
                if (!entry.minValue.isEmpty())
                {
                    input->setMinimum(entry.minValue.toInt());
                }
                if (!entry.maxValue.isEmpty())
                {
                    input->setMaximum(entry.maxValue.toInt());
                }
                control = input;
            }
            else if (type == QLatin1String("Bool"))
            {
                bool checked = (QString::compare(entry.value.toString(), QStringLiteral("true"), Qt::CaseInsensitive) == 0);
                QCheckBox* checkBox = new QCheckBox(entry.label, box);
                checkBox->setCheckState(checked ? Qt::Checked : Qt::Unchecked);
            }
            else
            {
                qCDebug(PLUGIN_FILETEMPLATES) << "Unrecognized option type" << entry.type;
            }
            if (control)
            {
                formLayout->addRow(label, control);
                d->controls.insert(entry.name, control);
            }
        }

        box->setLayout(formLayout);
        layout->addWidget(box);
    }
    setLayout(layout);
}
Exemple #25
0
//sligthly modified from tst_QMap
void tst_QHash::iterators()
{
    QHash<int, QString> hash;
    QMap<int, QString> testMap;
    QString testString="Teststring %1";
    QString testString1;
    int i;

    for(i = 1; i < 100; ++i)
        hash.insert(i, testString.arg(i));

    //to get some chaos in the hash
    hash.squeeze();

    //STL-Style iterators

    QHash<int, QString>::iterator stlIt = hash.begin();
    for(stlIt = hash.begin(), i = 1; stlIt != hash.end(), i < 100; ++stlIt, ++i) {
            testMap.insert(i,stlIt.value());
            //QVERIFY(stlIt.value() == hash.value(
    }
    stlIt = hash.begin();

    QVERIFY(stlIt.value() == testMap.value(1));

    stlIt+=5;
    QVERIFY(stlIt.value() == testMap.value(6));

    stlIt++;
    QVERIFY(stlIt.value() == testMap.value(7));

    stlIt-=3;
    QVERIFY(stlIt.value() == testMap.value(4));

    stlIt--;
    QVERIFY(stlIt.value() == testMap.value(3));

    testMap.clear();

    //STL-Style const-iterators

    QHash<int, QString>::const_iterator cstlIt = hash.constBegin();
    for(cstlIt = hash.constBegin(), i = 1; cstlIt != hash.constEnd(), i < 100; ++cstlIt, ++i) {
            testMap.insert(i,cstlIt.value());
            //QVERIFY(stlIt.value() == hash.value(
    }
    cstlIt = hash.constBegin();

    QVERIFY(cstlIt.value() == testMap.value(1));

    cstlIt+=5;
    QVERIFY(cstlIt.value() == testMap.value(6));

    cstlIt++;
    QVERIFY(cstlIt.value() == testMap.value(7));

    cstlIt-=3;
    QVERIFY(cstlIt.value() == testMap.value(4));

    cstlIt--;
    QVERIFY(cstlIt.value() == testMap.value(3));

    testMap.clear();

    //Java-Style iterators

    QHashIterator<int, QString> javaIt(hash);

    //walk through
    i = 0;
    while(javaIt.hasNext()) {
        ++i;
        javaIt.next();
        testMap.insert(i,javaIt.value());
    }
    javaIt.toFront();
    i = 0;
    while(javaIt.hasNext()) {
        ++i;
        javaIt.next();
        //qDebug(javaIt.value());
        QVERIFY(javaIt.value() == testMap.value(i));
    }

    ++i;
    while(javaIt.hasPrevious()) {
        --i;
        javaIt.previous();
        QVERIFY(javaIt.value() == testMap.value(i));
    }

    /*
        I've removed findNextKey() and findPreviousKey() from the API
        for Qt 4.0 beta 1.
    */

#if 0
    //findPreviousKey()  findNextKey()
    for(i = 1; i < 100; ++i) {
        if(javaIt.findNextKey(i))
            QVERIFY(javaIt.value() == testString.arg(i));
        else {
            QVERIFY(!javaIt.hasNext());
            QVERIFY(javaIt.findPreviousKey(i));
            QVERIFY(javaIt.value() == testString.arg(i));
        }

        if(javaIt.findPreviousKey(i))
            QVERIFY(javaIt.value() == testString.arg(i));
        else {
            QVERIFY(!javaIt.hasPrevious());
            QVERIFY(javaIt.findNextKey(i));
            QVERIFY(javaIt.value() == testString.arg(i));
        }
    }
#endif

    //peekNext()  peekPrevious()
    javaIt.toFront();
    javaIt.next();
    while(javaIt.hasNext()) {
        testString = javaIt.value();
        testString1 = javaIt.peekNext().value();
        javaIt.next();
        //qDebug(testString + "  " + testString1 + "    " + javaIt.peekPrevious().value());
        QVERIFY(javaIt.value() == testString1);
        QCOMPARE(javaIt.peekPrevious().value(), testString1);
    }
    while(javaIt.hasPrevious()) {
        testString = javaIt.value();
        testString1 = javaIt.peekPrevious().value();
        javaIt.previous();
        QVERIFY(javaIt.value() == testString1);
        //qDebug(testString + testString1 + javaIt.peekNext().value());
        QCOMPARE(javaIt.peekNext().value(), testString1);
    }
}
Exemple #26
0
/*
* Entity loading control and customization.
* taken from xsltproc.c
*/
static xmlParserInputPtr xsltprocExternalEntityLoader(const char *_URL, const char *ID, xmlParserCtxtPtr ctxt)
{
    xmlParserInputPtr ret;
    warningSAXFunc warning = NULL;

    // use local available dtd versions instead of fetching it every time from the internet
    QString url = QLatin1String(_URL);
    QHash<QString, QString>::const_iterator i;
    for (i = replaceURLList.constBegin(); i != replaceURLList.constEnd(); i++) {
        if (url.startsWith(i.key())) {
            url.replace(i.key(), i.value());
            qDebug() << "converted" << _URL << "to" << url;
        }
    }
    char URL[1024];
    strcpy(URL, url.toLatin1().constData());

    const char *lastsegment = URL;
    const char *iter = URL;

    if (nbpaths > 0) {
        while (*iter != 0) {
            if (*iter == '/') {
                lastsegment = iter + 1;
            }
            iter++;
        }
    }

    if ((ctxt != NULL) && (ctxt->sax != NULL)) {
        warning = ctxt->sax->warning;
        ctxt->sax->warning = NULL;
    }

    if (defaultEntityLoader != NULL) {
        ret = defaultEntityLoader(URL, ID, ctxt);
        if (ret != NULL) {
            if (warning != NULL) {
                ctxt->sax->warning = warning;
            }
            qDebug() << "Loaded URL=\"" << URL << "\" ID=\"" << ID << "\"";
            return (ret);
        }
    }
    for (int i = 0; i < nbpaths; i++) {
        xmlChar *newURL;

        newURL = xmlStrdup((const xmlChar *) paths[i]);
        newURL = xmlStrcat(newURL, (const xmlChar *) "/");
        newURL = xmlStrcat(newURL, (const xmlChar *) lastsegment);
        if (newURL != NULL) {
            ret = defaultEntityLoader((const char *)newURL, ID, ctxt);
            if (ret != NULL) {
                if (warning != NULL) {
                    ctxt->sax->warning = warning;
                }
                qDebug() << "Loaded URL=\"" << newURL << "\" ID=\"" << ID << "\"";
                xmlFree(newURL);
                return (ret);
            }
            xmlFree(newURL);
        }
    }
    if (warning != NULL) {
        ctxt->sax->warning = warning;
        if (URL != NULL) {
            warning(ctxt, "failed to load external entity \"%s\"\n", URL);
        } else if (ID != NULL) {
            warning(ctxt, "failed to load external entity \"%s\"\n", ID);
        }
    }
    return (NULL);
}