bool KisXMPIO::loadFrom(KisMetaData::Store* store, QIODevice* ioDevice) const
{
    ioDevice->open(QIODevice::ReadOnly);
    dbgFile << "Load XMP Data";
    std::string xmpPacket_;
    QByteArray arr = ioDevice->readAll();
    xmpPacket_.assign(arr.data(), arr.length());
    dbgFile << xmpPacket_.length();
//     dbgFile << xmpPacket_.c_str();
    Exiv2::XmpData xmpData_;
    Exiv2::XmpParser::decode(xmpData_, xmpPacket_);
    QMap< const KisMetaData::Schema*, QMap<QString, QMap<QString, KisMetaData::Value> > > structures;
    QMap< const KisMetaData::Schema*, QMap<QString, QVector< QMap<QString, KisMetaData::Value> > > > arraysOfStructures;
    for (Exiv2::XmpData::iterator it = xmpData_.begin(); it != xmpData_.end(); ++it) {
        dbgFile << it->key().c_str();
        Exiv2::XmpKey key(it->key());
        dbgFile << key.groupName().c_str() << " " << key.tagName().c_str() << " " << key.ns().c_str();
        if ((key.groupName() == "exif" || key.groupName() == "tiff") && key.tagName() == "NativeDigest") {  // TODO: someone who has time to lose can look in adding support for NativeDigest, it's undocumented use by the XMP SDK to check if exif data has been changed while XMP hasn't been updated
            dbgFile << "dropped";
        } else {
            const KisMetaData::Schema* schema = KisMetaData::SchemaRegistry::instance()->schemaFromPrefix(key.groupName().c_str());
            if (!schema) {
                schema = KisMetaData::SchemaRegistry::instance()->schemaFromUri(key.ns().c_str());
                if (!schema) {
                    schema = KisMetaData::SchemaRegistry::instance()->create(key.ns().c_str(), key.groupName().c_str());
                    Q_ASSERT(schema);
                }
            }
            const Exiv2::Value::AutoPtr value = it->getValue();
            // Decrypt key
            QString structName = "";
            QString tagName = key.tagName().c_str();
            int arrayIndex = -1;
            const KisMetaData::TypeInfo* typeInfo = 0;
            bool isStructureEntry = false;
            bool isStructureInArrayEntry = false;
            if (tagName.contains("/")) {
                QRegExp regexp("([A-Za-z]\\w+)/([A-Za-z]\\w+):([A-Za-z]\\w+)");
                if (regexp.indexIn(tagName) != -1) {
                    structName = regexp.capturedTexts()[1];
                    tagName =  regexp.capturedTexts()[3];
                    typeInfo = schema->propertyType(structName);
                    Q_ASSERT(typeInfo == schema->propertyType(structName));
                    if (typeInfo && typeInfo->propertyType() == KisMetaData::TypeInfo::StructureType) {
                        typeInfo = typeInfo->structureSchema()->propertyType(tagName);
                    }
                    isStructureEntry = true;
                } else {
                    QRegExp regexp2("([A-Za-z]\\w+)\\[(\\d+)\\]/([A-Za-z]\\w+):([A-Za-z]\\w+)");
                    if (regexp2.indexIn(tagName) != -1) {
                        dbgFile << ppVar(tagName);
                        structName = regexp2.capturedTexts()[1];
                        arrayIndex = regexp2.capturedTexts()[2].toInt() - 1;
                        tagName = regexp2.capturedTexts()[4];
                        dbgFile << ppVar(structName) << ppVar(regexp2.capturedTexts()[3]);
                        //Q_ASSERT(schema->propertyType(structName));
                        if (schema->propertyType(structName)) {
                            typeInfo = schema->propertyType(structName)->embeddedPropertyType();
                            Q_ASSERT(typeInfo);
                            if (typeInfo && typeInfo->propertyType() == KisMetaData::TypeInfo::StructureType) {
                                typeInfo = typeInfo->structureSchema()->propertyType(tagName);
                            }
                        }
                        isStructureInArrayEntry = true;
                    } else {
                        dbgFile << "Decoding structure name/entry failed: " << tagName;
                    }
                }
            } else {
                typeInfo = schema->propertyType(tagName);
            }
            KisMetaData::Value v;

            bool ignoreValue = false;
            // Compute the value
            if (value->typeId() == Exiv2::xmpBag
                    || value->typeId() == Exiv2::xmpSeq
                    || value->typeId() == Exiv2::xmpAlt) {
                const KisMetaData::TypeInfo* embeddedTypeInfo = 0;
                if (typeInfo) {
                    embeddedTypeInfo = typeInfo->embeddedPropertyType();
                }
                const KisMetaData::Parser* parser = 0;
                if (embeddedTypeInfo) {
                    parser = embeddedTypeInfo->parser();
                }
                const Exiv2::XmpArrayValue* xav = dynamic_cast<const Exiv2::XmpArrayValue*>(value.get());
                Q_ASSERT(xav);
                QList<KisMetaData::Value> array;
                for (std::vector< std::string >::const_iterator it = xav->value_.begin();
                        it != xav->value_.end(); ++it) {
                    QString value = it->c_str();
                    if (parser) {
                        array.push_back(parser->parse(value));
                    } else {
                        dbgImage << "No parser " << tagName;
                        array.push_back(KisMetaData::Value(value));
                    }
                }
                KisMetaData::Value::ValueType vt = KisMetaData::Value::Invalid;
                switch (xav->xmpArrayType()) {
                case Exiv2::XmpValue::xaNone:
                    warnKrita << "KisXMPIO: Unsupported array";
                    break;
                case Exiv2::XmpValue::xaAlt:
                    vt = KisMetaData::Value::AlternativeArray;
                    break;
                case Exiv2::XmpValue::xaBag:
                    vt = KisMetaData::Value::UnorderedArray;
                    break;
                case Exiv2::XmpValue::xaSeq:
                    vt = KisMetaData::Value::OrderedArray;
                    break;
                }
                v = KisMetaData::Value(array, vt);
            } else if (value->typeId() == Exiv2::langAlt) {
                const Exiv2::LangAltValue* xav = dynamic_cast<const Exiv2::LangAltValue*>(value.get());
                QList<KisMetaData::Value> alt;
                for (std::map< std::string, std::string>::const_iterator it = xav->value_.begin();
                        it != xav->value_.end(); ++it) {
                    KisMetaData::Value valt(it->second.c_str());
                    valt.addPropertyQualifier("xml:lang", KisMetaData::Value(it->first.c_str()));
                    alt.push_back(valt);
                }
                v = KisMetaData::Value(alt, KisMetaData::Value::LangArray);
            } else {
                QString valTxt = value->toString().c_str();
                if (typeInfo && typeInfo->parser()) {
                    v = typeInfo->parser()->parse(valTxt);
                } else {
                    dbgFile << "No parser " << tagName;
                    v = KisMetaData::Value(valTxt);
                }
                if (valTxt == "type=\"Struct\"") {
                    if (!typeInfo || typeInfo->propertyType() == KisMetaData::TypeInfo::StructureType) {
                        ignoreValue = true;
                    }
                }
            }

            // set the value
            dbgFile << ppVar(tagName);
            if (isStructureEntry) {
                structures[schema][structName][tagName] = v;
            } else if (isStructureInArrayEntry) {
                if (arraysOfStructures[schema][structName].size() <= arrayIndex) {
                    arraysOfStructures[schema][structName].resize(arrayIndex + 1);
                }
                arraysOfStructures[schema][structName][arrayIndex][tagName] = v;
            } else {
                if (!ignoreValue) {
                    store->addEntry(KisMetaData::Entry(schema, tagName, v));
                } else {
                    dbgFile << "Ignoring value for " << tagName << " " << v;
                }
            }
        }
    }

    for (QMap< const KisMetaData::Schema*, QMap<QString, QMap<QString, KisMetaData::Value>  > >::iterator it = structures.begin();
            it != structures.end(); ++it) {
        const KisMetaData::Schema* schema = it.key();
        for (QMap<QString, QMap<QString, KisMetaData::Value> >::iterator it2 = it.value().begin();
                it2 != it.value().end(); ++it2) {
            store->addEntry(KisMetaData::Entry(schema, it2.key(), KisMetaData::Value(it2.value())));
        }
    }
    for (QMap< const KisMetaData::Schema*, QMap<QString, QVector< QMap<QString, KisMetaData::Value> > > >::iterator it = arraysOfStructures.begin(); it != arraysOfStructures.end(); ++it) {
        const KisMetaData::Schema* schema = it.key();
        for (QMap<QString, QVector<QMap<QString, KisMetaData::Value> > >::iterator it2 = it.value().begin();
                it2 != it.value().end(); ++it2) {
            KisMetaData::Value::ValueType type = KisMetaData::Value::OrderedArray;
            QString entryName = it2.key();
            if (schema->propertyType(entryName)) {
                switch (schema->propertyType(entryName)->propertyType()) {
                case KisMetaData::TypeInfo::OrderedArrayType:
                    type = KisMetaData::Value::OrderedArray;
                    break;
                case KisMetaData::TypeInfo::UnorderedArrayType:
                    type = KisMetaData::Value::OrderedArray;
                    break;
                case KisMetaData::TypeInfo::AlternativeArrayType:
                    type = KisMetaData::Value::AlternativeArray;
                    break;
                default:
                    type = KisMetaData::Value::Invalid;
                    break;
                }
            } else if (store->containsEntry(schema, entryName)) {
                KisMetaData::Value value = store->getEntry(schema, entryName).value();
                if (value.isArray()) {
                    type = value.type();
                }
            }
            store->removeEntry(schema, entryName);
            if (type != KisMetaData::Value::Invalid) {
                QList< KisMetaData::Value > valueList;
                for (int i = 0; i < it2.value().size(); ++i) {
                    valueList.append(it2.value()[i]);
                }
                store->addEntry(KisMetaData::Entry(schema, entryName, KisMetaData::Value(valueList, type)));
            }
        }
    }

    return true;
}
void KInstitutionsView::loadAccounts(void)
{
  QMap<QString, bool> isOpen;

  ::timetrace("start load institutions view");
  // remember the id of the current selected item
  KMyMoneyAccountTreeBaseItem *item = m_accountTree->selectedItem();
  QString selectedItemId = (item) ? item->id() : QString();

  // keep a map of all 'expanded' accounts
  QListViewItemIterator it_lvi(m_accountTree);
  while(it_lvi.current()) {
    item = dynamic_cast<KMyMoneyAccountTreeItem*>(it_lvi.current());
    if(item && item->isOpen()) {
      isOpen[item->id()] = true;
    }
    ++it_lvi;
  }

  // remember the upper left corner of the viewport
  QPoint startPoint = m_accountTree->viewportToContents(QPoint(0, 0));

  // turn off updates to avoid flickering during reload
  m_accountTree->setUpdatesEnabled(false);

  // clear the current contents and recreate it
  m_accountTree->clear();
  m_accountMap.clear();
  m_securityMap.clear();
  m_transactionCountMap.clear();

  MyMoneyFile* file = MyMoneyFile::instance();

  QValueList<MyMoneyAccount> alist;
  file->accountList(alist);
  QValueList<MyMoneyAccount>::const_iterator it_a;
  for(it_a = alist.begin(); it_a != alist.end(); ++it_a) {
    m_accountMap[(*it_a).id()] = *it_a;
  }

  // we need to make sure we show stock accounts
  // under the right institution (the one of the parent account)
  QMap<QString, MyMoneyAccount>::iterator it_am;
  for(it_am = m_accountMap.begin(); it_am != m_accountMap.end(); ++it_am) {
    if((*it_am).isInvest()) {
      (*it_am).setInstitutionId(m_accountMap[(*it_am).parentAccountId()].institutionId());
    }
  }

  QValueList<MyMoneySecurity> slist = file->currencyList();
  slist += file->securityList();
  QValueList<MyMoneySecurity>::const_iterator it_s;
  for(it_s = slist.begin(); it_s != slist.end(); ++it_s) {
    m_securityMap[(*it_s).id()] = *it_s;
  }

  m_transactionCountMap = file->transactionCountMap();

  m_accountTree->setBaseCurrency(file->baseCurrency());

  // create the items
  try {
    const MyMoneySecurity& security = file->baseCurrency();
    m_accountTree->setBaseCurrency(security);

    MyMoneyInstitution none;
    none.setName(i18n("Accounts with no institution assigned"));
    KMyMoneyAccountTreeItem* noInstitutionItem = new KMyMoneyAccountTreeItem(m_accountTree, none);
    noInstitutionItem->setPixmap(0,none.pixmap());
    loadSubAccounts(noInstitutionItem, QString());

    // hide it, if unused
    noInstitutionItem->setVisible(noInstitutionItem->childCount() != 0);
    
    bool showClosedAccounts = kmymoney2->toggleAction("view_show_all_accounts")->isChecked()
      || !KMyMoneyGlobalSettings::hideClosedAccounts();

    QValueList<MyMoneyInstitution> list = file->institutionList();
    QValueList<MyMoneyInstitution>::const_iterator it_i;
    for(it_i = list.begin(); it_i != list.end(); ++it_i) {
      KMyMoneyAccountTreeItem* item = new KMyMoneyAccountTreeItem(m_accountTree, *it_i);
      item->setPixmap(0, none.pixmap());
      loadSubAccounts(item, (*it_i).id());
      if(!showClosedAccounts)
        item->setVisible(item->childCount() != 0);
    }

  } catch(MyMoneyException *e) {
    kdDebug(2) << "Problem in institutions view: " << e->what();
    delete e;
  }

  // scan through the list of accounts and re-expand those that were
  // expanded and re-select the one that was probably selected before
  it_lvi = QListViewItemIterator(m_accountTree);
  while(it_lvi.current()) {
    item = dynamic_cast<KMyMoneyAccountTreeItem*>(it_lvi.current());
    if(item) {
      if(item->id() == selectedItemId)
        m_accountTree->setSelected(item, true);
      if(isOpen.find(item->id()) != isOpen.end())
        item->setOpen(true);
    }
    ++it_lvi;
  }

  // reposition viewport
  m_accountTree->setContentsPos(startPoint.x(), startPoint.y());

  // turn updates back on
  m_accountTree->setUpdatesEnabled(true);
  m_accountTree->repaintContents();

  ::timetrace("done load institutions view");
}
Exemple #3
0
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
void FindNeighbors::execute()
{
    setErrorCondition(0);
    dataCheck();
    if(getErrorCondition() < 0) {
        return;
    }

    DataContainer::Pointer m = getDataContainerArray()->getDataContainer(m_FeatureIdsArrayPath.getDataContainerName());
    size_t totalPoints = m_FeatureIdsPtr.lock()->getNumberOfTuples();
    size_t totalFeatures = m_NumNeighborsPtr.lock()->getNumberOfTuples();

    size_t udims[3] = { 0, 0, 0 };
    m->getGeometryAs<ImageGeom>()->getDimensions(udims);
#if (CMP_SIZEOF_SIZE_T == 4)
    typedef int32_t DimType;
#else
    typedef int64_t DimType;
#endif
    DimType dims[3] =
    {
        static_cast<DimType>(udims[0]),
        static_cast<DimType>(udims[1]),
        static_cast<DimType>(udims[2]),
    };

    DimType neighpoints[6] = { 0, 0, 0, 0, 0, 0 };
    neighpoints[0] = -dims[0] * dims[1];
    neighpoints[1] = -dims[0];
    neighpoints[2] = -1;
    neighpoints[3] = 1;
    neighpoints[4] = dims[0];
    neighpoints[5] = dims[0] * dims[1];

    DimType column = 0, row = 0, plane = 0;
    int32_t feature = 0;
    int32_t nnum = 0;
    int8_t onsurf = 0;
    bool good = false;
    DimType neighbor = 0;

    std::vector<std::vector<int32_t> > neighborlist;
    std::vector<std::vector<float> > neighborsurfacearealist;

    int32_t nListSize = 100;
    neighborlist.resize(totalFeatures);
    neighborsurfacearealist.resize(totalFeatures);

    uint64_t millis = QDateTime::currentMSecsSinceEpoch();
    uint64_t currentMillis = millis;

    for (size_t i = 1; i < totalFeatures; i++)
    {
        currentMillis = QDateTime::currentMSecsSinceEpoch();
        if (currentMillis - millis > 1000)
        {
            QString ss = QObject::tr("Finding Neighbors || Initializing Neighbor Lists || %1% Complete").arg((static_cast<float>(i) / totalFeatures) * 100);
            notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss);
            millis = QDateTime::currentMSecsSinceEpoch();
        }

        if (getCancel() == true) {
            return;
        }

        m_NumNeighbors[i] = 0;
        neighborlist[i].resize(nListSize);
        neighborsurfacearealist[i].assign(nListSize, -1.0f);
        if (m_StoreSurfaceFeatures == true) {
            m_SurfaceFeatures[i] = false;
        }

    }

    for (size_t j = 0; j < totalPoints; j++)
    {
        currentMillis = QDateTime::currentMSecsSinceEpoch();
        if (currentMillis - millis > 1000)
        {
            QString ss = QObject::tr("Finding Neighbors || Determining Neighbor Lists || %1% Complete").arg((static_cast<float>(j) / totalPoints) * 100);
            notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss);
            millis = QDateTime::currentMSecsSinceEpoch();
        }

        if (getCancel() == true) {
            return;
        }

        onsurf = 0;
        feature = m_FeatureIds[j];
        if (feature > 0)
        {
            column = static_cast<DimType>( j % m->getGeometryAs<ImageGeom>()->getXPoints() );
            row = static_cast<DimType>( (j / m->getGeometryAs<ImageGeom>()->getXPoints()) % m->getGeometryAs<ImageGeom>()->getYPoints() );
            plane = static_cast<DimType>( j / (m->getGeometryAs<ImageGeom>()->getXPoints() * m->getGeometryAs<ImageGeom>()->getYPoints()) );
            if (m_StoreSurfaceFeatures == true)
            {
                if ((column == 0 || column == DimType((m->getGeometryAs<ImageGeom>()->getXPoints() - 1))
                        || row == 0 || row == DimType((m->getGeometryAs<ImageGeom>()->getYPoints()) - 1)
                        || plane == 0 || plane == DimType((m->getGeometryAs<ImageGeom>()->getZPoints() - 1)))
                        && m->getGeometryAs<ImageGeom>()->getZPoints() != 1)
                {
                    m_SurfaceFeatures[feature] = true;
                }
                if ((column == 0 || column == DimType((m->getGeometryAs<ImageGeom>()->getXPoints() - 1)) || row == 0 || row == DimType((m->getGeometryAs<ImageGeom>()->getYPoints() - 1))) && m->getGeometryAs<ImageGeom>()->getZPoints() == 1)
                {
                    m_SurfaceFeatures[feature] = true;
                }
            }
            for (int32_t k = 0; k < 6; k++)
            {
                good = true;
                neighbor = static_cast<DimType>( j + neighpoints[k] );
                if (k == 0 && plane == 0) {
                    good = false;
                }
                if (k == 5 && plane == (m->getGeometryAs<ImageGeom>()->getZPoints() - 1)) {
                    good = false;
                }
                if (k == 1 && row == 0) {
                    good = false;
                }
                if (k == 4 && row == (m->getGeometryAs<ImageGeom>()->getYPoints() - 1)) {
                    good = false;
                }
                if (k == 2 && column == 0) {
                    good = false;
                }
                if (k == 3 && column == (m->getGeometryAs<ImageGeom>()->getXPoints() - 1)) {
                    good = false;
                }
                if (good == true && m_FeatureIds[neighbor] != feature && m_FeatureIds[neighbor] > 0)
                {
                    onsurf++;
                    nnum = m_NumNeighbors[feature];
                    neighborlist[feature].push_back(m_FeatureIds[neighbor]);
                    nnum++;
                    m_NumNeighbors[feature] = nnum;
                }
            }
        }
        if (m_StoreBoundaryCells == true) {
            m_BoundaryCells[j] = onsurf;
        }
    }

    // We do this to create new set of NeighborList objects
    for (size_t i = 1; i < totalFeatures; i++)
    {
        currentMillis = QDateTime::currentMSecsSinceEpoch();
        if (currentMillis - millis > 1000)
        {
            QString ss = QObject::tr("Finding Neighbors || Calculating Surface Areas || %1% Complete").arg(((float)i / totalFeatures) * 100);
            notifyStatusMessage(getMessagePrefix(), getHumanLabel(), ss);
            millis = QDateTime::currentMSecsSinceEpoch();
        }

        if(getCancel() == true) {
            return;
        }


        QMap<int32_t, int32_t> neighToCount;
        int32_t numneighs = static_cast<int32_t>( neighborlist[i].size() );

        // this increments the voxel counts for each feature
        for (int32_t j = 0; j < numneighs; j++)
        {
            neighToCount[neighborlist[i][j]]++;
        }

        QMap<int32_t, int32_t>::Iterator neighiter = neighToCount.find(0);
        neighToCount.erase(neighiter);
        neighiter = neighToCount.find(-1);
        neighToCount.erase(neighiter);
        // Resize the features neighbor list to zero
        neighborlist[i].resize(0);
        neighborsurfacearealist[i].resize(0);

        for (QMap<int32_t, int32_t>::iterator iter = neighToCount.begin(); iter != neighToCount.end(); ++iter)
        {
            int32_t neigh = iter.key(); // get the neighbor feature
            int32_t number = iter.value(); // get the number of voxels
            float area = float(number) * m->getGeometryAs<ImageGeom>()->getXRes() * m->getGeometryAs<ImageGeom>()->getYRes();

            // Push the neighbor feature id back onto the list so we stay synced up
            neighborlist[i].push_back(neigh);
            neighborsurfacearealist[i].push_back(area);
        }
        m_NumNeighbors[i] = int32_t(neighborlist[i].size());

        // Set the vector for each list into the NeighborList Object
        NeighborList<int32_t>::SharedVectorType sharedNeiLst(new std::vector<int32_t>);
        sharedNeiLst->assign(neighborlist[i].begin(), neighborlist[i].end());
        m_NeighborList.lock()->setList(static_cast<int32_t>(i), sharedNeiLst);

        NeighborList<float>::SharedVectorType sharedSAL(new std::vector<float>);
        sharedSAL->assign(neighborsurfacearealist[i].begin(), neighborsurfacearealist[i].end());
        m_SharedSurfaceAreaList.lock()->setList(static_cast<int32_t>(i), sharedSAL);
    }

    notifyStatusMessage(getHumanLabel(), "Complete");
}
void workget() {
    int x = 0;
    QApplication a(x,0);

    QString base ="http://www.zhanqi.tv/api/static/game.lives/66/30-";
    QString end = ".json";

    QMap < QString , QJsonObject >  mapintjo;
    QJsonDocument jd;
    bool ok = loadJsonFile("lolmasterdata.json",jd);
    QJsonArray ja;
    ja = jd.array();

    QFile file("outdata.txt");

    if (!file.open(QIODevice::WriteOnly | QIODevice::Text))             return ;

    QTextStream out(&file);


    for (int i=0; i<ja.size(); i++) {
        QJsonObject jo;
        jo = ja[i].toObject();
        mapintjo[jo["uid"].toString()] = jo;
        out<<jo["gameusername"].toString()<< "   " <<jo["nickname"].toString()<< "   "<<jo["url"].toString()<<endl;
    }
    file.close();

    while(true) {
        for (int x = 1; x< 145; x++) {
            QString s = QString::number(x);
            QString u = base+s+end;
            qDebug()<<u;
            HttpFileDownloader hfd;
            bool ok = hfd.sycGetPageFromURL(QUrl(u));
            qDebug()<<ok;
            if (!ok) continue;
            QString re = hfd.getPage();
            QJsonDocument jd = QJsonDocument::fromJson(re.toUtf8());
            qDebug()<<jd.object()["data"].toObject()["rooms"].toArray().size();
            QJsonArray ja = jd.object()["data"].toObject()["rooms"].toArray();

            for (int i=0; i< ja.size(); i++) {
                QJsonObject jo = ja[i].toObject() ;
                QString nickname = jo["nickname"].toString();
                QString url = jo["url"].toString();
                QString id,uid;
                id = jo["id"].toString();
                uid = jo["uid"].toString();
                //qDebug()<<uid;
                if (mapintjo.contains(uid)  &&  mapintjo[uid]["gameusername"].toString()!="") continue;
                QString bb = "http://www.zhanqi.tv";
                HttpFileDownloader hfd;
                bool ok = hfd.sycGetPageFromURL(QUrl(bb+url));
                //qDebug()<<ok;
                if (!ok) continue;
                QString re = hfd.getPage();

                int x = re.indexOf("getLols5Nickname");
                int a = re.indexOf(myTr("战旗TV丶"),x);
                int b = re.indexOf("</span>",x);
                if (x<0 ) continue;
                if (b<0) {
                    qDebug()<<nickname;
                    continue;
                }
                QString gameusername;
                if (a<0) {
                    gameusername = re.mid(x+22, b-x-22);

                }
                else {
                     gameusername = re.mid(a,b-a);
                }
                qDebug()<<gameusername;

                QJsonObject so;
                so["nickname"] = nickname;
                so["url"] = url;
                so["id"] = id;
                so["uid"] = uid;
                so["gameusername"] = gameusername;
                mapintjo[uid] = so;
            }



            {
                QJsonArray ja;
                for (auto a = mapintjo.begin(); a!= mapintjo.end(); a++) {
                    ja.push_back(a.value());
                }
                bool ok = saveJsonFile("lolmasterdata.json", QJsonDocument(ja));
                qDebug()<<"save file !! " <<ok;
            }
        }

    }
    a.exec();
}
void QgsAtlasComposition::readXML( const QDomElement& atlasElem, const QDomDocument& )
{
  mEnabled = atlasElem.attribute( "enabled", "false" ) == "true" ? true : false;
  emit toggled( mEnabled );
  if ( !mEnabled )
  {
    emit parameterChanged();
    return;
  }

  // look for stored layer name
  mCoverageLayer = 0;
  QMap<QString, QgsMapLayer*> layers = QgsMapLayerRegistry::instance()->mapLayers();
  for ( QMap<QString, QgsMapLayer*>::const_iterator it = layers.begin(); it != layers.end(); ++it )
  {
    if ( it.key() == atlasElem.attribute( "coverageLayer" ) )
    {
      mCoverageLayer = dynamic_cast<QgsVectorLayer*>( it.value() );
      break;
    }
  }
  //look for stored composer map, to upgrade pre 2.1 projects
  int composerMapNo = atlasElem.attribute( "composerMap", "-1" ).toInt();
  QgsComposerMap * composerMap = 0;
  if ( composerMapNo != -1 )
  {
    QList<QgsComposerMap*> maps;
    mComposition->composerItems( maps );
    for ( QList<QgsComposerMap*>::iterator it = maps.begin(); it != maps.end(); ++it )
    {
      if (( *it )->id() == composerMapNo )
      {
        composerMap = ( *it );
        composerMap->setAtlasDriven( true );
        break;
      }
    }
  }
  mHideCoverage = atlasElem.attribute( "hideCoverage", "false" ) == "true" ? true : false;

  //upgrade pre 2.1 projects
  double margin = atlasElem.attribute( "margin", "0.0" ).toDouble();
  if ( composerMap && margin != 0 )
  {
    composerMap->setAtlasMargin( margin );
  }
  bool fixedScale = atlasElem.attribute( "fixedScale", "false" ) == "true" ? true : false;
  if ( composerMap && fixedScale )
  {
    composerMap->setAtlasFixedScale( true );
  }

  mSingleFile = atlasElem.attribute( "singleFile", "false" ) == "true" ? true : false;
  mFilenamePattern = atlasElem.attribute( "filenamePattern", "" );

  mSortFeatures = atlasElem.attribute( "sortFeatures", "false" ) == "true" ? true : false;
  if ( mSortFeatures )
  {
    mSortKeyAttributeIdx = atlasElem.attribute( "sortKey", "0" ).toInt();
    mSortAscending = atlasElem.attribute( "sortAscending", "true" ) == "true" ? true : false;
  }
  mFilterFeatures = atlasElem.attribute( "filterFeatures", "false" ) == "true" ? true : false;
  if ( mFilterFeatures )
  {
    mFeatureFilter = atlasElem.attribute( "featureFilter", "" );
  }

  emit parameterChanged();
}
Exemple #6
0
DTC::ProgramList* Dvr::GetFilteredRecordedList( bool           bDescending,
                                                int            nStartIndex,
                                                int            nCount,
                                                const QString &sTitleRegEx,
                                                const QString &sRecGroup,
                                                const QString &sStorageGroup )
{
    QMap< QString, ProgramInfo* > recMap;

    if (gCoreContext->GetScheduler())
        recMap = gCoreContext->GetScheduler()->GetRecording();

    QMap< QString, uint32_t > inUseMap    = ProgramInfo::QueryInUseMap();
    QMap< QString, bool >     isJobRunning= ProgramInfo::QueryJobsRunning(JOB_COMMFLAG);

    ProgramList progList;

    int desc = 0;
    if (bDescending)
        desc = -1;

    LoadFromRecorded( progList, false, inUseMap, isJobRunning, recMap, desc );

    QMap< QString, ProgramInfo* >::iterator mit = recMap.begin();

    for (; mit != recMap.end(); mit = recMap.erase(mit))
        delete *mit;

    // ----------------------------------------------------------------------
    // Build Response
    // ----------------------------------------------------------------------

    DTC::ProgramList *pPrograms = new DTC::ProgramList();
    int nAvailable = 0;

    if ((sTitleRegEx.isEmpty()) &&
        (sRecGroup.isEmpty()) &&
        (sStorageGroup.isEmpty()))
    {
        nStartIndex   = min( nStartIndex, (int)progList.size() );
        nCount        = (nCount > 0) ? min( nCount, (int)progList.size() ) : progList.size();
        int nEndIndex = min((nStartIndex + nCount), (int)progList.size() );
        nCount        = nEndIndex - nStartIndex;

        nAvailable = progList.size();

        for( int n = nStartIndex; n < nEndIndex; n++)
        {
            ProgramInfo *pInfo = progList[ n ];
            DTC::Program *pProgram = pPrograms->AddNewProgram();

            FillProgramInfo( pProgram, pInfo, true );
        }
    }
    else
    {
        int nMax      = nCount;

        nAvailable = 0;
        nCount = 0;

        QRegExp rTitleRegEx        = QRegExp(sTitleRegEx, Qt::CaseInsensitive);

        for( unsigned int n = 0; n < progList.size(); n++)
        {
            ProgramInfo *pInfo = progList[ n ];

            if ((!sTitleRegEx.isEmpty() && !pInfo->GetTitle().contains(rTitleRegEx)) ||
                (!sRecGroup.isEmpty() && sRecGroup != pInfo->GetRecordingGroup()) ||
                (!sStorageGroup.isEmpty() && sStorageGroup != pInfo->GetStorageGroup()))
                continue;

            ++nAvailable;

            if ((nAvailable < nStartIndex) ||
                (nCount >= nMax))
                continue;

            ++nCount;

            DTC::Program *pProgram = pPrograms->AddNewProgram();

            FillProgramInfo( pProgram, pInfo, true );
        }
    }

    // ----------------------------------------------------------------------

    pPrograms->setStartIndex    ( nStartIndex     );
    pPrograms->setCount         ( nCount          );
    pPrograms->setTotalAvailable( nAvailable      );
    pPrograms->setAsOf          ( QDateTime::currentDateTime() );
    pPrograms->setVersion       ( MYTH_BINARY_VERSION );
    pPrograms->setProtoVer      ( MYTH_PROTO_VERSION  );

    return pPrograms;
}
static bool parse_chan_info(const QString   &rawdata,
                            IPTVChannelInfo &info,
                            QString         &channum,
                            uint            &lineNum)
{
    // #EXTINF:0,2 - France 2                <-- duration,channum - channame
    // #EXTMYTHTV:xmltvid=C2.telepoche.com   <-- optional line (myth specific)
    // #EXTMYTHTV:bitrate=BITRATE            <-- optional line (myth specific)
    // #EXTMYTHTV:fectype=FECTYPE            <-- optional line (myth specific)
    //     The FECTYPE can be rfc2733, rfc5109, or smpte2022
    // #EXTMYTHTV:fecurl0=URL                <-- optional line (myth specific)
    // #EXTMYTHTV:fecurl1=URL                <-- optional line (myth specific)
    // #EXTMYTHTV:fecbitrate0=BITRATE        <-- optional line (myth specific)
    // #EXTMYTHTV:fecbitrate1=BITRATE        <-- optional line (myth specific)
    // #...                                  <-- ignored comments
    // rtsp://maiptv.iptv.fr/iptvtv/201 <-- url

    QString name;
    QMap<QString,QString> values;

    while (true)
    {
        QString line = rawdata.section("\n", lineNum, lineNum);
        if (line.isEmpty())
            return false;

        ++lineNum;
        if (line.startsWith("#"))
        {
            if (line.startsWith("#EXTINF:"))
            {
                parse_extinf(line.mid(line.indexOf(':')+1), channum, name);
            }
            else if (line.startsWith("#EXTMYTHTV:"))
            {
                QString data = line.mid(line.indexOf(':'));
                QString key = data.left(data.indexOf('='));
                if (!key.isEmpty())
                    values[key] = data.mid(data.indexOf('=')+1);
            }
            continue;
        }

        if (name.isEmpty())
            return false;

        QMap<QString,QString>::const_iterator it = values.begin();
        for (; it != values.end(); ++it)
        {
            LOG(VB_GENERAL, LOG_INFO,
                QString("parse_chan_info [%1]='%2'")
                .arg(it.key()).arg(*it));
        }
        info = IPTVChannelInfo(
            name, values["xmltvid"],
            line, values["bitrate"].toUInt(),
            values["fectype"],
            values["fecurl0"], values["fecbitrate0"].toUInt(),
            values["fecurl1"], values["fecbitrate1"].toUInt());
        return true;
    }
}
Exemple #8
0
void TOCGenerator::generateDefault()
{
	if (m_doc == NULL)
		return;
	Q_ASSERT(!m_doc->masterPageMode());
	for(ToCSetupVector::Iterator tocSetupIt = m_doc->tocSetups().begin(); tocSetupIt != m_doc->tocSetups().end(); ++tocSetupIt )
	{
		PageItem* tocFrame = findTargetFrame(tocSetupIt->frameName);
		if (tocFrame == NULL)
			continue;

		PageItem *currentDocItem;
		QMap<QString, QString> tocMap;

		uint *pageCounter = new uint[m_doc->DocPages.count()];
		if (pageCounter == NULL)
			return;
		uint pageNumberWidth = QString("%1").arg(m_doc->DocPages.count()).length();
		for (int i = 0; i < m_doc->DocPages.count(); ++i)
			pageCounter[i] = 0;

		for (int d = 0; d < m_doc->DocItems.count(); ++d)
		{
			currentDocItem = m_doc->DocItems.at(d);
			if (currentDocItem == NULL)
				continue;
			//Item not on a page, continue
			if (currentDocItem->OwnPage == -1)
				continue;
			//If we dont want to list non printing frames and this one is set to not print, continue
			if (!tocSetupIt->listNonPrintingFrames && !currentDocItem->printEnabled())
				continue;

			ObjectAttribute objAttr;
			QList<ObjectAttribute> objAttrs = currentDocItem->getObjectAttributes(tocSetupIt->itemAttrName);
			if (objAttrs.count() <= 0)
				continue;

			QString pageID = QString("%1").arg(currentDocItem->OwnPage + m_doc->FirstPnum, pageNumberWidth);
			QString sectionID = m_doc->getSectionPageNumberForPageIndex(currentDocItem->OwnPage);

			for (int i = 0; i < objAttrs.count(); ++i)
			{
				objAttr = objAttrs.at(i);
				if (objAttr.name.isNull())
					continue;

				//The key is generated to produce a sequence of numbers for the page numbers
				//First is the page of the item
				//Second is an incremented counter for the item so multiple per page works
				//Third is the section based page number which is actually used in the TOC.
				QString tocID = QString("%1").arg(pageCounter[currentDocItem->OwnPage]++, 3 , 10, QChar('0'));
				QString key   = QString("%1,%2,%3").arg(pageID).arg(tocID).arg(sectionID);
				tocMap.insert(key, objAttr.value);
			}
		}

		//Set up the gtWriter instance with the selected paragraph style
		gtWriter writer(false, tocFrame);
		writer.setUpdateParagraphStyles(false);
		writer.setOverridePStyleFont(false);
		gtFrameStyle* fstyle = writer.getDefaultStyle();
		gtParagraphStyle* pstyle = new gtParagraphStyle(*fstyle);
		pstyle->setName(tocSetupIt->textStyle);
		writer.setParagraphStyle(pstyle);
		
		QString oldTocPage = QString::null;
		for (QMap<QString, QString>::Iterator tocIt=tocMap.begin(); tocIt != tocMap.end();++tocIt)
		{
			QString tocPage(tocIt.key().section( ',', 2, 2 ).trimmed());
			QString tocLine;
			//Start with text or numbers
			if (tocSetupIt->pageLocation == End || tocSetupIt->pageLocation == NotShown)
				tocLine = tocIt.value();
			if (tocSetupIt->pageLocation == Beginning && oldTocPage != tocPage)
				tocLine = tocPage;
			//Add in the tab for the leaders
			tocLine += "\t";
			//End with text or numbers
			if (tocSetupIt->pageLocation == Beginning)
				tocLine += tocIt.value();
			if (tocSetupIt->pageLocation == End && oldTocPage != tocPage)
				tocLine += tocPage;
			tocLine += "\n";
			writer.append(tocLine);
		}

		delete[] pageCounter;
	}
}
void
VatsimDataHandler::__clearFlags(QMap< QString, bool >& _flags) {
  for (auto it = _flags.begin(); it != _flags.end(); ++it)
    it.value() = false;
}
 void setCustomFields(const QMap<QString, QString> &fields)
 {
     QMap<QString, QString>::const_iterator it = fields.begin(), end = fields.end();
     for ( ; it != end; ++it)
         setCustomField(it.key(), it.value());
 }
void QgsLineVectorLayerDirector::makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints,
    QVector< QgsPoint >& tiedPoint ) const
{
  QgsVectorLayer *vl = mVectorLayer;

  if ( !vl )
    return;

  int featureCount = ( int ) vl->featureCount() * 2;
  int step = 0;

  QgsCoordinateTransform ct;
  ct.setSourceCrs( vl->crs() );
  if ( builder->coordinateTransformationEnabled() )
  {
    ct.setDestinationCrs( builder->destinationCrs() );
  }
  else
  {
    ct.setDestinationCrs( vl->crs() );
  }

  tiedPoint = QVector< QgsPoint >( additionalPoints.size(), QgsPoint( 0.0, 0.0 ) );

  TiePointInfo tmpInfo;
  tmpInfo.mLength = std::numeric_limits<double>::infinity();

  QVector< TiePointInfo > pointLengthMap( additionalPoints.size(), tmpInfo );
  QVector< TiePointInfo >::iterator pointLengthIt;

  //Graph's points;
  QVector< QgsPoint > points;

  QgsFeatureIterator fit = vl->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( QgsAttributeList() ) );

  // begin: tie points to the graph
  QgsAttributeList la;
  QgsFeature feature;
  while ( fit.nextFeature( feature ) )
  {
    QgsMultiPolyline mpl;
    if ( QgsWkbTypes::flatType( feature.geometry().geometry()->wkbType() ) == QgsWkbTypes::MultiLineString )
      mpl = feature.geometry().asMultiPolyline();
    else if ( QgsWkbTypes::flatType( feature.geometry().geometry()->wkbType() ) == QgsWkbTypes::LineString )
      mpl.push_back( feature.geometry().asPolyline() );

    QgsMultiPolyline::iterator mplIt;
    for ( mplIt = mpl.begin(); mplIt != mpl.end(); ++mplIt )
    {
      QgsPoint pt1, pt2;
      bool isFirstPoint = true;
      QgsPolyline::iterator pointIt;
      for ( pointIt = mplIt->begin(); pointIt != mplIt->end(); ++pointIt )
      {
        pt2 = ct.transform( *pointIt );
        points.push_back( pt2 );

        if ( !isFirstPoint )
        {
          int i = 0;
          for ( i = 0; i != additionalPoints.size(); ++i )
          {
            TiePointInfo info;
            if ( pt1 == pt2 )
            {
              info.mLength = additionalPoints[ i ].sqrDist( pt1 );
              info.mTiedPoint = pt1;
            }
            else
            {
              info.mLength = additionalPoints[ i ].sqrDistToSegment( pt1.x(), pt1.y(),
                             pt2.x(), pt2.y(), info.mTiedPoint );
            }

            if ( pointLengthMap[ i ].mLength > info.mLength )
            {
              Q_UNUSED( info.mTiedPoint );
              info.mFirstPoint = pt1;
              info.mLastPoint = pt2;

              pointLengthMap[ i ] = info;
              tiedPoint[ i ] = info.mTiedPoint;
            }
          }
        }
        pt1 = pt2;
        isFirstPoint = false;
      }
    }
    emit buildProgress( ++step, featureCount );
  }
  // end: tie points to graph

  // add tied point to graph
  int i = 0;
  for ( i = 0; i < tiedPoint.size(); ++i )
  {
    if ( tiedPoint[ i ] != QgsPoint( 0.0, 0.0 ) )
    {
      points.push_back( tiedPoint [ i ] );
    }
  }

  QgsPointCompare pointCompare( builder->topologyTolerance() );

  qSort( points.begin(), points.end(), pointCompare );
  QVector< QgsPoint >::iterator tmp = std::unique( points.begin(), points.end() );
  points.resize( tmp - points.begin() );

  for ( i = 0;i < points.size();++i )
    builder->addVertex( i, points[ i ] );

  for ( i = 0; i < tiedPoint.size() ; ++i )
    tiedPoint[ i ] = *( my_binary_search( points.begin(), points.end(), tiedPoint[ i ], pointCompare ) );

  qSort( pointLengthMap.begin(), pointLengthMap.end(), TiePointInfoCompare );

  {
    // fill attribute list 'la'
    QgsAttributeList tmpAttr;
    if ( mDirectionFieldId != -1 )
    {
      tmpAttr.push_back( mDirectionFieldId );
    }

    QList< QgsArcProperter* >::const_iterator it;
    QgsAttributeList::const_iterator it2;

    for ( it = mProperterList.begin(); it != mProperterList.end(); ++it )
    {
      QgsAttributeList tmp = ( *it )->requiredAttributes();
      for ( it2 = tmp.begin(); it2 != tmp.end(); ++it2 )
      {
        tmpAttr.push_back( *it2 );
      }
    }
    qSort( tmpAttr.begin(), tmpAttr.end() );

    int lastAttrId = -1;
    for ( it2 = tmpAttr.begin(); it2 != tmpAttr.end(); ++it2 )
    {
      if ( *it2 == lastAttrId )
      {
        continue;
      }

      la.push_back( *it2 );

      lastAttrId = *it2;
    }
  } // end fill attribute list 'la'

  // begin graph construction
  fit = vl->getFeatures( QgsFeatureRequest().setSubsetOfAttributes( la ) );
  while ( fit.nextFeature( feature ) )
  {
    int directionType = mDefaultDirection;

    // What direction have feature?
    QString str = feature.attribute( mDirectionFieldId ).toString();
    if ( str == mBothDirectionValue )
    {
      directionType = 3;
    }
    else if ( str == mDirectDirectionValue )
    {
      directionType = 1;
    }
    else if ( str == mReverseDirectionValue )
    {
      directionType = 2;
    }

    // begin features segments and add arc to the Graph;
    QgsMultiPolyline mpl;
    if ( QgsWkbTypes::flatType( feature.geometry().geometry()->wkbType() ) == QgsWkbTypes::MultiLineString )
      mpl = feature.geometry().asMultiPolyline();
    else if ( QgsWkbTypes::flatType( feature.geometry().geometry()->wkbType() ) == QgsWkbTypes::LineString )
      mpl.push_back( feature.geometry().asPolyline() );

    QgsMultiPolyline::iterator mplIt;
    for ( mplIt = mpl.begin(); mplIt != mpl.end(); ++mplIt )
    {
      QgsPoint pt1, pt2;

      bool isFirstPoint = true;
      QgsPolyline::iterator pointIt;
      for ( pointIt = mplIt->begin(); pointIt != mplIt->end(); ++pointIt )
      {
        pt2 = ct.transform( *pointIt );

        if ( !isFirstPoint )
        {
          QMap< double, QgsPoint > pointsOnArc;
          pointsOnArc[ 0.0 ] = pt1;
          pointsOnArc[ pt1.sqrDist( pt2 )] = pt2;

          TiePointInfo t;
          t.mFirstPoint = pt1;
          t.mLastPoint  = pt2;
          t.mLength = 0.0;
          pointLengthIt = my_binary_search( pointLengthMap.begin(), pointLengthMap.end(), t, TiePointInfoCompare );

          if ( pointLengthIt != pointLengthMap.end() )
          {
            QVector< TiePointInfo >::iterator it;
            for ( it = pointLengthIt; it - pointLengthMap.begin() >= 0; --it )
            {
              if ( it->mFirstPoint == pt1 && it->mLastPoint == pt2 )
              {
                pointsOnArc[ pt1.sqrDist( it->mTiedPoint )] = it->mTiedPoint;
              }
            }
            for ( it = pointLengthIt + 1; it != pointLengthMap.end(); ++it )
            {
              if ( it->mFirstPoint == pt1 && it->mLastPoint == pt2 )
              {
                pointsOnArc[ pt1.sqrDist( it->mTiedPoint )] = it->mTiedPoint;
              }
            }
          }

          QMap< double, QgsPoint >::iterator pointsIt;
          QgsPoint pt1;
          QgsPoint pt2;
          int pt1idx = -1, pt2idx = -1;
          bool isFirstPoint = true;
          for ( pointsIt = pointsOnArc.begin(); pointsIt != pointsOnArc.end(); ++pointsIt )
          {
            pt2 = *pointsIt;
            tmp = my_binary_search( points.begin(), points.end(), pt2, pointCompare );
            pt2 = *tmp;
            pt2idx = tmp - points.begin();

            if ( !isFirstPoint && pt1 != pt2 )
            {
              double distance = builder->distanceArea()->measureLine( pt1, pt2 );
              QVector< QVariant > prop;
              QList< QgsArcProperter* >::const_iterator it;
              for ( it = mProperterList.begin(); it != mProperterList.end(); ++it )
              {
                prop.push_back(( *it )->property( distance, feature ) );
              }

              if ( directionType == 1 ||
                   directionType == 3 )
              {
                builder->addArc( pt1idx, pt1, pt2idx, pt2, prop );
              }
              if ( directionType == 2 ||
                   directionType == 3 )
              {
                builder->addArc( pt2idx, pt2, pt1idx, pt1, prop );
              }
            }
            pt1idx = pt2idx;
            pt1 = pt2;
            isFirstPoint = false;
          }
        } // if ( !isFirstPoint )
        pt1 = pt2;
        isFirstPoint = false;
      } // for (it = pl.begin(); it != pl.end(); ++it)
    }
    emit buildProgress( ++step, featureCount );
  } // while( vl->nextFeature(feature) )
} // makeGraph( QgsGraphBuilderInterface *builder, const QVector< QgsPoint >& additionalPoints, QVector< QgsPoint >& tiedPoint )