/*! Returns true if \a text contains any HTML tags, attributes or CSS properties which are unrelated to text, fonts or text layout. Otherwise the function returns false. If the return value is false, \a text is considered to be easily representable in the scenegraph. If it returns true, then the text should be prerendered into a pixmap before it's displayed on screen. */ bool QSGTextNode::isComplexRichText(QTextDocument *doc) { if (doc == 0) return false; static QSet<QString> supportedTags; if (supportedTags.isEmpty()) { supportedTags.insert(QLatin1String("i")); supportedTags.insert(QLatin1String("b")); supportedTags.insert(QLatin1String("u")); supportedTags.insert(QLatin1String("div")); supportedTags.insert(QLatin1String("big")); supportedTags.insert(QLatin1String("blockquote")); supportedTags.insert(QLatin1String("body")); supportedTags.insert(QLatin1String("br")); supportedTags.insert(QLatin1String("center")); supportedTags.insert(QLatin1String("cite")); supportedTags.insert(QLatin1String("code")); supportedTags.insert(QLatin1String("tt")); supportedTags.insert(QLatin1String("dd")); supportedTags.insert(QLatin1String("dfn")); supportedTags.insert(QLatin1String("em")); supportedTags.insert(QLatin1String("font")); supportedTags.insert(QLatin1String("h1")); supportedTags.insert(QLatin1String("h2")); supportedTags.insert(QLatin1String("h3")); supportedTags.insert(QLatin1String("h4")); supportedTags.insert(QLatin1String("h5")); supportedTags.insert(QLatin1String("h6")); supportedTags.insert(QLatin1String("head")); supportedTags.insert(QLatin1String("html")); supportedTags.insert(QLatin1String("meta")); supportedTags.insert(QLatin1String("nobr")); supportedTags.insert(QLatin1String("p")); supportedTags.insert(QLatin1String("pre")); supportedTags.insert(QLatin1String("qt")); supportedTags.insert(QLatin1String("s")); supportedTags.insert(QLatin1String("samp")); supportedTags.insert(QLatin1String("small")); supportedTags.insert(QLatin1String("span")); supportedTags.insert(QLatin1String("strong")); supportedTags.insert(QLatin1String("sub")); supportedTags.insert(QLatin1String("sup")); supportedTags.insert(QLatin1String("title")); supportedTags.insert(QLatin1String("var")); supportedTags.insert(QLatin1String("style")); } static QSet<QCss::Property> supportedCssProperties; if (supportedCssProperties.isEmpty()) { supportedCssProperties.insert(QCss::Color); supportedCssProperties.insert(QCss::Float); supportedCssProperties.insert(QCss::Font); supportedCssProperties.insert(QCss::FontFamily); supportedCssProperties.insert(QCss::FontSize); supportedCssProperties.insert(QCss::FontStyle); supportedCssProperties.insert(QCss::FontWeight); supportedCssProperties.insert(QCss::Margin); supportedCssProperties.insert(QCss::MarginBottom); supportedCssProperties.insert(QCss::MarginLeft); supportedCssProperties.insert(QCss::MarginRight); supportedCssProperties.insert(QCss::MarginTop); supportedCssProperties.insert(QCss::TextDecoration); supportedCssProperties.insert(QCss::TextIndent); supportedCssProperties.insert(QCss::TextUnderlineStyle); supportedCssProperties.insert(QCss::VerticalAlignment); supportedCssProperties.insert(QCss::Whitespace); supportedCssProperties.insert(QCss::Padding); supportedCssProperties.insert(QCss::PaddingLeft); supportedCssProperties.insert(QCss::PaddingRight); supportedCssProperties.insert(QCss::PaddingTop); supportedCssProperties.insert(QCss::PaddingBottom); supportedCssProperties.insert(QCss::PageBreakBefore); supportedCssProperties.insert(QCss::PageBreakAfter); supportedCssProperties.insert(QCss::Width); supportedCssProperties.insert(QCss::Height); supportedCssProperties.insert(QCss::MinimumWidth); supportedCssProperties.insert(QCss::MinimumHeight); supportedCssProperties.insert(QCss::MaximumWidth); supportedCssProperties.insert(QCss::MaximumHeight); supportedCssProperties.insert(QCss::Left); supportedCssProperties.insert(QCss::Right); supportedCssProperties.insert(QCss::Top); supportedCssProperties.insert(QCss::Bottom); supportedCssProperties.insert(QCss::Position); supportedCssProperties.insert(QCss::TextAlignment); supportedCssProperties.insert(QCss::FontVariant); } QXmlStreamReader reader(doc->toHtml("utf-8")); while (!reader.atEnd()) { reader.readNext(); if (reader.isStartElement()) { if (!supportedTags.contains(reader.name().toString().toLower())) return true; QXmlStreamAttributes attributes = reader.attributes(); if (attributes.hasAttribute(QLatin1String("bgcolor"))) return true; if (attributes.hasAttribute(QLatin1String("style"))) { QCss::StyleSheet styleSheet; QCss::Parser(attributes.value(QLatin1String("style")).toString()).parse(&styleSheet); QVector<QCss::Declaration> decls; for (int i=0; i<styleSheet.pageRules.size(); ++i) decls += styleSheet.pageRules.at(i).declarations; QVector<QCss::StyleRule> styleRules = styleSheet.styleRules + styleSheet.idIndex.values().toVector() + styleSheet.nameIndex.values().toVector(); for (int i=0; i<styleSheet.mediaRules.size(); ++i) styleRules += styleSheet.mediaRules.at(i).styleRules; for (int i=0; i<styleRules.size(); ++i) decls += styleRules.at(i).declarations; for (int i=0; i<decls.size(); ++i) { if (!supportedCssProperties.contains(decls.at(i).d->propertyId)) return true; } } } } return reader.hasError(); }
QSet<QString> QgsServerProjectParser::findRestrictedLayers() const { QSet<QString> restrictedLayerSet; if ( !mXMLDoc ) { return restrictedLayerSet; } //names of unpublished layers / groups QDomElement propertiesElem = mXMLDoc->documentElement().firstChildElement( "properties" ); if ( !propertiesElem.isNull() ) { QDomElement wmsLayerRestrictionElem = propertiesElem.firstChildElement( "WMSRestrictedLayers" ); if ( !wmsLayerRestrictionElem.isNull() ) { QStringList restrictedLayersAndGroups; QDomNodeList wmsLayerRestrictionValues = wmsLayerRestrictionElem.elementsByTagName( "value" ); for ( int i = 0; i < wmsLayerRestrictionValues.size(); ++i ) { restrictedLayerSet.insert( wmsLayerRestrictionValues.at( i ).toElement().text() ); } } } //get legend dom element if ( restrictedLayerSet.size() < 1 || !mXMLDoc ) { return restrictedLayerSet; } QDomElement legendElem = mXMLDoc->documentElement().firstChildElement( "legend" ); if ( legendElem.isNull() ) { return restrictedLayerSet; } //go through all legend groups and insert names of subgroups / sublayers if there is a match QDomNodeList legendGroupList = legendElem.elementsByTagName( "legendgroup" ); for ( int i = 0; i < legendGroupList.size(); ++i ) { //get name QDomElement groupElem = legendGroupList.at( i ).toElement(); QString groupName = groupElem.attribute( "name" ); if ( restrictedLayerSet.contains( groupName ) ) //match: add names of subgroups and sublayers to set { //embedded group? -> also get names of subgroups and sublayers from embedded projects if ( groupElem.attribute( "embedded" ) == "1" ) { sublayersOfEmbeddedGroup( convertToAbsolutePath( groupElem.attribute( "project" ) ), groupName, restrictedLayerSet ); } else //local group { QDomNodeList subgroupList = groupElem.elementsByTagName( "legendgroup" ); for ( int j = 0; j < subgroupList.size(); ++j ) { restrictedLayerSet.insert( subgroupList.at( j ).toElement().attribute( "name" ) ); } QDomNodeList sublayerList = groupElem.elementsByTagName( "legendlayer" ); for ( int k = 0; k < sublayerList.size(); ++k ) { restrictedLayerSet.insert( sublayerList.at( k ).toElement().attribute( "name" ) ); } } } } return restrictedLayerSet; }
// This is a lighter weight merge since we know at this stage everything stays // within its own task and the partitions that must be merged are contiguous // Therefore we only need to merge the groups and remove the previous ones // from the partition list -- so we create the new ones and point the old // ones toward it so we can make a single pass to remove those that point to // a new partition. void OTFConverter::mergeContiguous(QList<QList<Partition * > *> * groups) { // Create the new partitions and store them in new parts QList<Partition *> * newparts = new QList<Partition *>(); for (QList<QList<Partition *> *>::Iterator group = groups->begin(); group != groups->end(); ++group) { Partition * p = new Partition(); for (QList<Partition *>::Iterator part = (*group)->begin(); part != (*group)->end(); ++part) { (*part)->new_partition = p; for (QMap<int, QList<CommEvent *> *>::Iterator proc = (*part)->events->begin(); proc != (*part)->events->end(); ++proc) { for (QList<CommEvent *>::Iterator evt = (proc.value())->begin(); evt != (proc.value())->end(); ++evt) { (*evt)->partition = p; p->addEvent(*evt); } } } p->new_partition = p; //newparts->append(p); } // Add in the partitions in order -- those that didn't get changed // just added in normally. Add the first instance of the others so // that order can be maintained and delete the ones that represent // changes. QSet<Partition *> sortSet = QSet<Partition *>(); QList<Partition *> toDelete = QList<Partition *>(); for (QList<Partition *>::Iterator part = trace->partitions->begin(); part != trace->partitions->end(); ++part) { if ((*part)->new_partition == *part) { newparts->append(*part); } else { if (!sortSet.contains((*part)->new_partition)) { newparts->append((*part)->new_partition); sortSet.insert((*part)->new_partition); } toDelete.append(*part); } } // Delete old parts for (QList<Partition *>::Iterator oldpart = toDelete.begin(); oldpart != toDelete.end(); ++oldpart) { delete *oldpart; *oldpart = NULL; } // Add the new partitions to trace->partitions delete trace->partitions; trace->partitions = newparts; }
void runTagsTest() { ImplicitTagRulesSqliteReader reader; reader.setAddTopTagOnly(false); reader.setAllowWordsInvolvedInMultipleRules(false); reader.open("test-files/io/ImplicitTagRulesSqliteReaderTest/rules.sqlite"); QSet<QString> words; QSet<QString> wordsInvolved; bool wordsInvolvedInMultipleRules = false; Tags tags; words.insert("Mosque"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(2, tags.size()); CPPUNIT_ASSERT(tags["amenity"] == "place_of_worship"); CPPUNIT_ASSERT(tags["leisure"] == "park"); CPPUNIT_ASSERT_EQUAL(1, wordsInvolved.size()); CPPUNIT_ASSERT(wordsInvolved.contains("Mosque")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); words.insert("MOSQUE"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(2, tags.size()); CPPUNIT_ASSERT(tags["amenity"] == "place_of_worship"); CPPUNIT_ASSERT(tags["leisure"] == "park"); CPPUNIT_ASSERT_EQUAL(1, wordsInvolved.size()); CPPUNIT_ASSERT(wordsInvolved.contains("Mosque")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); words.insert("mosque"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(2, tags.size()); CPPUNIT_ASSERT(tags["amenity"] == "place_of_worship"); CPPUNIT_ASSERT(tags["leisure"] == "park"); CPPUNIT_ASSERT_EQUAL(1, wordsInvolved.size()); CPPUNIT_ASSERT(wordsInvolved.contains("Mosque")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); words.insert("mosque2"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(0, tags.size()); CPPUNIT_ASSERT_EQUAL(0, wordsInvolved.size()); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); words.insert("mosque 3"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(0, tags.size()); CPPUNIT_ASSERT_EQUAL(0, wordsInvolved.size()); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); words.insert("Eid Prayer Ground"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, tags.size()); CPPUNIT_ASSERT(tags["amenity"] == "place_of_worship"); CPPUNIT_ASSERT_EQUAL(1, wordsInvolved.size()); CPPUNIT_ASSERT(wordsInvolved.contains("Eid Prayer Ground")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); words.insert("Mustashfa"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, tags.size()); CPPUNIT_ASSERT(tags["amenity"] == "hospital"); CPPUNIT_ASSERT_EQUAL(1, wordsInvolved.size()); CPPUNIT_ASSERT(wordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); words.insert("alwhdt"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, tags.size()); CPPUNIT_ASSERT(tags["amenity"] == "clinic"); CPPUNIT_ASSERT_EQUAL(1, wordsInvolved.size()); CPPUNIT_ASSERT(wordsInvolved.contains("alwhdt")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); words.insert("Mustashfa alwhdt"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, tags.size()); CPPUNIT_ASSERT(tags["amenity"] == "hospital"); CPPUNIT_ASSERT_EQUAL(1, wordsInvolved.size()); CPPUNIT_ASSERT(wordsInvolved.contains("Mustashfa alwhdt")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); words.clear(); //the AddImplicitlyDerivedTagsPoiVisitor won't pass a word phrase and its constituent //tokens in the same tags request, but if it did, then it should identify the words as //belonging to multiple rules words.insert("Mustashfa"); words.insert("alwhdt"); words.insert("Mustashfa alwhdt"); tags = reader.getImplicitTags(words, wordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(0, tags.size()); CPPUNIT_ASSERT_EQUAL(3, wordsInvolved.size()); CPPUNIT_ASSERT(wordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(wordsInvolved.contains("alwhdt")); CPPUNIT_ASSERT(wordsInvolved.contains("Mustashfa alwhdt")); CPPUNIT_ASSERT(wordsInvolvedInMultipleRules); words.clear(); reader.close(); }
/*! \internal Returns the canonicalized form of \a path (i.e., with all symlinks resolved, and all redundant path elements removed. */ QString QFSFileEnginePrivate::canonicalized(const QString &path) { if (path.isEmpty()) return path; // FIXME let's see if this stuff works, then we might be able to remove some of the other code. #if defined(Q_OS_UNIX) && !defined(Q_OS_SYMBIAN) if (path.size() == 1 && path.at(0) == QLatin1Char('/')) return path; #endif #if defined(Q_OS_UNIX) // ... but Linux with uClibc does not have it #if !defined(__UCLIBC__) char *ret = 0; #if defined(Q_OS_MAC) // Mac OS X 10.5.x doesn't support the realpath(X,0) extension we use here. if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_6) { ret = realpath(path.toLocal8Bit().constData(), (char*)0); } else { // on 10.5 we can use FSRef to resolve the file path. FSRef fsref; if (FSPathMakeRef((const UInt8 *)QDir::cleanPath(path).toUtf8().data(), &fsref, 0) == noErr) { CFURLRef urlref = CFURLCreateFromFSRef(NULL, &fsref); CFStringRef canonicalPath = CFURLCopyFileSystemPath(urlref, kCFURLPOSIXPathStyle); QString ret = QCFString::toQString(canonicalPath); CFRelease(canonicalPath); CFRelease(urlref); return ret; } } #else ret = realpath(path.toLocal8Bit().constData(), (char*)0); #endif if (ret) { QString canonicalPath = QDir::cleanPath(QString::fromLocal8Bit(ret)); free(ret); return canonicalPath; } #endif #endif QFileInfo fi; const QChar slash(QLatin1Char('/')); QString tmpPath = path; int separatorPos = 0; QSet<QString> nonSymlinks; QSet<QString> known; known.insert(path); do { #if defined(Q_OS_WIN) || defined(Q_OS_CYGWIN) // UNC, skip past the first two elements if (separatorPos == 0 && tmpPath.startsWith(QLatin1String("//"))) separatorPos = tmpPath.indexOf(slash, 2); if (separatorPos != -1) #endif separatorPos = tmpPath.indexOf(slash, separatorPos + 1); QString prefix = separatorPos == -1 ? tmpPath : tmpPath.left(separatorPos); if ( #ifdef Q_OS_SYMBIAN // Symbian doesn't support directory symlinks, so do not check for link unless we // are handling the last path element. This not only slightly improves performance, // but also saves us from lot of unnecessary platform security check failures // when dealing with files under *:/private directories. separatorPos == -1 && #endif !nonSymlinks.contains(prefix)) { fi.setFile(prefix); if (fi.isSymLink()) { QString target = fi.symLinkTarget(); if (separatorPos != -1) { if (fi.isDir() && !target.endsWith(slash)) target.append(slash); target.append(tmpPath.mid(separatorPos)); } tmpPath = QDir::cleanPath(target); separatorPos = 0; if (known.contains(tmpPath)) return QString(); known.insert(tmpPath); } else { nonSymlinks.insert(prefix); } } } while (separatorPos != -1); return QDir::cleanPath(tmpPath); }
void ApiWrap::gotStickerSet(uint64 setId, const MTPmessages_StickerSet &result) { _stickerSetRequests.remove(setId); if (result.type() != mtpc_messages_stickerSet) return; const MTPDmessages_stickerSet &d(result.c_messages_stickerSet()); if (d.vset.type() != mtpc_stickerSet) return; const MTPDstickerSet &s(d.vset.c_stickerSet()); StickerSets &sets(cRefStickerSets()); StickerSets::iterator it = sets.find(setId); if (it == sets.cend()) return; it->access = s.vaccess_hash.v; it->hash = s.vhash.v; it->shortName = qs(s.vshort_name); QString title = qs(s.vtitle); if ((it->flags & MTPDstickerSet_flag_official) && !title.compare(qstr("Great Minds"), Qt::CaseInsensitive)) { title = lang(lng_stickers_default_set); } it->title = title; it->flags = s.vflags.v; const QVector<MTPDocument> &d_docs(d.vdocuments.c_vector().v); StickerSets::iterator custom = sets.find(CustomStickerSetId); QSet<DocumentData*> found; int32 wasCount = -1; for (int32 i = 0, l = d_docs.size(); i != l; ++i) { DocumentData *doc = App::feedDocument(d_docs.at(i)); if (!doc || !doc->sticker()) continue; if (wasCount < 0) wasCount = it->stickers.size(); if (it->stickers.indexOf(doc) < 0) { it->stickers.push_back(doc); } else { found.insert(doc); } if (custom != sets.cend()) { int32 index = custom->stickers.indexOf(doc); if (index >= 0) { custom->stickers.removeAt(index); } } } if (custom != sets.cend() && custom->stickers.isEmpty()) { sets.erase(custom); custom = sets.end(); } bool writeRecent = false; RecentStickerPack &recent(cGetRecentStickers()); if (wasCount < 0) { // no stickers received for (RecentStickerPack::iterator i = recent.begin(); i != recent.cend();) { if (it->stickers.indexOf(i->first) >= 0) { i = recent.erase(i); writeRecent = true; } else { ++i; } } cRefStickerSetsOrder().removeOne(setId); sets.erase(it); } else { for (int32 j = 0, l = wasCount; j < l;) { if (found.contains(it->stickers.at(j))) { ++j; } else { for (RecentStickerPack::iterator i = recent.begin(); i != recent.cend();) { if (it->stickers.at(j) == i->first) { i = recent.erase(i); writeRecent = true; } else { ++i; } } it->stickers.removeAt(j); --l; } } if (it->stickers.isEmpty()) { cRefStickerSetsOrder().removeOne(setId); sets.erase(it); } } if (writeRecent) { Local::writeUserSettings(); } Local::writeStickers(); if (App::main()) emit App::main()->stickersUpdated(); }
/*! Returns a list with the default source in it. \sa defaultSource() */ QSet<QPimSource> QDependentEventsContext::sources() const { QSet<QPimSource> list; list.insert(defaultSource()); return list; }
bool JQNetworkServer::begin() { JQNETWORK_THISNULL_CHECK( "JQNetworkServer::begin", false ); nodeMarkSummary_ = JQNetworkNodeMark::calculateNodeMarkSummary( serverSettings_->dutyMark ); if ( globalServerThreadPool_ ) { serverThreadPool_ = globalServerThreadPool_.toStrongRef(); } else { serverThreadPool_ = QSharedPointer< JQNetworkThreadPool >( new JQNetworkThreadPool( serverSettings_->globalServerThreadCount ) ); globalServerThreadPool_ = serverThreadPool_.toWeakRef(); } if ( globalSocketThreadPool_ ) { socketThreadPool_ = globalSocketThreadPool_.toStrongRef(); } else { socketThreadPool_ = QSharedPointer< JQNetworkThreadPool >( new JQNetworkThreadPool( serverSettings_->globalSocketThreadCount ) ); globalSocketThreadPool_ = socketThreadPool_.toWeakRef(); } if ( globalCallbackThreadPool_ ) { callbackThreadPool_ = globalCallbackThreadPool_.toStrongRef(); } else { callbackThreadPool_ = QSharedPointer< JQNetworkThreadPool >( new JQNetworkThreadPool( serverSettings_->globalCallbackThreadCount ) ); globalCallbackThreadPool_ = callbackThreadPool_.toWeakRef(); } if ( !processors_.isEmpty() ) { QSet< QThread * > receivedPossibleThreads; callbackThreadPool_->waitRunEach( [ &receivedPossibleThreads ]() { receivedPossibleThreads.insert( QThread::currentThread() ); } ); for ( const auto &processor: processors_ ) { processor->setReceivedPossibleThreads( receivedPossibleThreads ); } } bool listenSucceed = false; serverThreadPool_->waitRun( [ this, &listenSucceed ]() { this->tcpServer_ = QSharedPointer< QTcpServer >( new JQNetworkServerHelper( [ this ]( auto socketDescriptor ) { this->incomingConnection( socketDescriptor ); } ) ); listenSucceed = this->tcpServer_->listen( this->serverSettings_->listenAddress, this->serverSettings_->listenPort ); } ); if ( !listenSucceed ) { return false; } socketThreadPool_->waitRunEach( [ this ]() { JQNetworkConnectPoolSettingsSharedPointer connectPoolSettings( new JQNetworkConnectPoolSettings( *this->connectPoolSettings_ ) ); JQNetworkConnectSettingsSharedPointer connectSettings( new JQNetworkConnectSettings( *this->connectSettings_ ) ); connectPoolSettings->connectToHostErrorCallback = bind( &JQNetworkServer::onConnectToHostError, this, _1, _2 ); connectPoolSettings->connectToHostTimeoutCallback = bind( &JQNetworkServer::onConnectToHostTimeout, this, _1, _2 ); connectPoolSettings->connectToHostSucceedCallback = bind( &JQNetworkServer::onConnectToHostSucceed, this, _1, _2 ); connectPoolSettings->remoteHostClosedCallback = bind( &JQNetworkServer::onRemoteHostClosed, this, _1, _2 ); connectPoolSettings->readyToDeleteCallback = bind( &JQNetworkServer::onReadyToDelete, this, _1, _2 ); connectPoolSettings->packageSendingCallback = bind( &JQNetworkServer::onPackageSending, this, _1, _2, _3, _4, _5, _6 ); connectPoolSettings->packageReceivingCallback = bind( &JQNetworkServer::onPackageReceiving, this, _1, _2, _3, _4, _5, _6 ); connectPoolSettings->packageReceivedCallback = bind( &JQNetworkServer::onPackageReceived, this, _1, _2, _3 ); connectSettings->randomFlagRangeStart = 1000000000; connectSettings->randomFlagRangeEnd = 1999999999; connectPools_[ QThread::currentThread() ] = JQNetworkConnectPoolSharedPointer( new JQNetworkConnectPool( connectPoolSettings, connectSettings ) ); } ); return true; }
QSet<QString> ElementAvailableFN::allXSLTInstructions() { enum { StringSetSize = 27 }; QSet<QString> retval; retval.reserve(StringSetSize); /* Alphabetically. */ retval.insert(QLatin1String("analyze-string")); retval.insert(QLatin1String("apply-imports")); retval.insert(QLatin1String("apply-templates")); retval.insert(QLatin1String("attribute")); retval.insert(QLatin1String("attribute-set")); retval.insert(QLatin1String("call-template")); retval.insert(QLatin1String("character-map")); retval.insert(QLatin1String("choose")); retval.insert(QLatin1String("comment")); retval.insert(QLatin1String("copy")); retval.insert(QLatin1String("copy-of")); retval.insert(QLatin1String("document")); retval.insert(QLatin1String("element")); retval.insert(QLatin1String("fallback")); retval.insert(QLatin1String("for-each")); retval.insert(QLatin1String("for-each-group")); retval.insert(QLatin1String("if")); retval.insert(QLatin1String("message")); retval.insert(QLatin1String("namespace")); retval.insert(QLatin1String("next-match")); retval.insert(QLatin1String("number")); retval.insert(QLatin1String("perform-sort")); retval.insert(QLatin1String("processing-instruction")); retval.insert(QLatin1String("result-document")); retval.insert(QLatin1String("sequence")); retval.insert(QLatin1String("text")); retval.insert(QLatin1String("variable")); Q_ASSERT(retval.count() == StringSetSize); return retval; }
bool checkUnicodeEscape(QString & source, QString const & locationFilename, std::size_t const locationLine) { QFile inFile(inFilePath + '/' + locationFilename); if (!inFile.open(QIODevice::ReadOnly)) { std::cerr << inFilename << ": Failed to open source file: " << locationFilename.toStdString() << std::endl; return false; } QTextStream in(&inFile); for (std::size_t line = 1u; line < locationLine; ++line) if (in.readLine().isNull()) return false; auto line(in.readLine()); if (line.isNull()) return false; line = line.trimmed(); QStringList strings; int start = 0; for (;;) { start = line.indexOf('"', start); if (start < 0) break; ++start; auto end = line.indexOf('"', start); if (end < 0) break; if (start != end) { auto str(line.mid(start, end - start)); strings.append(std::move(str)); } start = end; ++start; } for (;;) { line = in.readLine(); if (line.isNull()) break; line = line.trimmed(); if (line.isEmpty()) continue; while (line.startsWith('"')) { auto end = line.indexOf('"', 1); if (end < 0) goto finish; if (end > 1) { auto str(line.mid(1, end - 1)); strings.last().append(std::move(str)); } line = line.mid(end + 1).trimmed(); } if (!line.isEmpty()) break; } finish: QSet<QString> rStrings; for (auto const & str : strings) { auto s(str); s.replace("\\u", "u"); if (source == s) rStrings.insert(str); } switch (rStrings.size()) { case 0: return false; case 1: { source = *rStrings.begin(); int from = 0; for (;;) { int const i = source.indexOf(unicodeEscape, from); if (i < 0) break; bool ok = false; ushort const codePoint = source.mid(i + 2, 4).toUShort(&ok, 16); assert(ok); source = (source.left(i) + QChar(codePoint)) + source.mid(i + 6); from = i + 1; } return true; } default: std::cerr << inFilename << ": Strange strings in " << locationFilename.toStdString() << ':' << locationLine << std::endl; return false; } }
bool OsmAnd::BinaryMapDataProvider_P::obtainData( const TileId tileId, const ZoomLevel zoom, std::shared_ptr<MapTiledData>& outTiledData, const IQueryController* const queryController) { std::shared_ptr<TileEntry> tileEntry; for (;;) { // Try to obtain previous instance of tile _tileReferences.obtainOrAllocateEntry(tileEntry, tileId, zoom, [] (const TiledEntriesCollection<TileEntry>& collection, const TileId tileId, const ZoomLevel zoom) -> TileEntry* { return new TileEntry(collection, tileId, zoom); }); // If state is "Undefined", change it to "Loading" and proceed with loading if (tileEntry->setStateIf(TileState::Undefined, TileState::Loading)) break; // In case tile entry is being loaded, wait until it will finish loading if (tileEntry->getState() == TileState::Loading) { QReadLocker scopedLcoker(&tileEntry->_loadedConditionLock); // If tile is in 'Loading' state, wait until it will become 'Loaded' while (tileEntry->getState() != TileState::Loaded) REPEAT_UNTIL(tileEntry->_loadedCondition.wait(&tileEntry->_loadedConditionLock)); } // Try to lock tile reference outTiledData = tileEntry->_tile.lock(); // If successfully locked, just return it if (outTiledData) return true; // Otherwise consider this tile entry as expired, remove it from collection (it's safe to do that right now) // This will enable creation of new entry on next loop cycle _tileReferences.removeEntry(tileId, zoom); tileEntry.reset(); } #if OSMAND_PERFORMANCE_METRICS const auto total_Begin = std::chrono::high_resolution_clock::now(); #endif // OSMAND_PERFORMANCE_METRICS // Obtain OBF data interface #if OSMAND_PERFORMANCE_METRICS const auto obtainDataInterface_Begin = std::chrono::high_resolution_clock::now(); #endif // OSMAND_PERFORMANCE_METRICS const auto& dataInterface = owner->obfsCollection->obtainDataInterface(); #if OSMAND_PERFORMANCE_METRICS const auto obtainDataInterface_End = std::chrono::high_resolution_clock::now(); const std::chrono::duration<float> obtainDataInterface_Elapsed = obtainDataInterface_End - obtainDataInterface_Begin; #endif // OSMAND_PERFORMANCE_METRICS // Get bounding box that covers this tile const auto tileBBox31 = Utilities::tileBoundingBox31(tileId, zoom); // Perform read-out QList< std::shared_ptr<const Model::BinaryMapObject> > referencedMapObjects; QList< proper::shared_future< std::shared_ptr<const Model::BinaryMapObject> > > futureReferencedMapObjects; QList< std::shared_ptr<const Model::BinaryMapObject> > loadedMapObjects; QSet< uint64_t > loadedSharedMapObjects; MapFoundationType tileFoundation; #if OSMAND_PERFORMANCE_METRICS float dataFilter = 0.0f; const auto dataRead_Begin = std::chrono::high_resolution_clock::now(); #endif // OSMAND_PERFORMANCE_METRICS #if OSMAND_PERFORMANCE_METRICS > 1 ObfMapSectionReader_Metrics::Metric_loadMapObjects dataRead_Metric; #endif // OSMAND_PERFORMANCE_METRICS > 1 dataInterface->loadMapObjects(&loadedMapObjects, &tileFoundation, tileBBox31, zoom, nullptr, [this, zoom, &referencedMapObjects, &futureReferencedMapObjects, &loadedSharedMapObjects, tileBBox31 #if OSMAND_PERFORMANCE_METRICS , &dataFilter #endif // OSMAND_PERFORMANCE_METRICS ] (const std::shared_ptr<const ObfMapSectionInfo>& section, const uint64_t id, const AreaI& bbox, const ZoomLevel firstZoomLevel, const ZoomLevel lastZoomLevel) -> bool { #if OSMAND_PERFORMANCE_METRICS const auto dataFilter_Begin = std::chrono::high_resolution_clock::now(); #endif // OSMAND_PERFORMANCE_METRICS // This map object may be shared only in case it crosses bounds of a tile const auto canNotBeShared = tileBBox31.contains(bbox); // If map object can not be shared, just read it if (canNotBeShared) { #if OSMAND_PERFORMANCE_METRICS const auto dataFilter_End = std::chrono::high_resolution_clock::now(); const std::chrono::duration<float> dataRead_Elapsed = dataFilter_End - dataFilter_Begin; dataFilter += dataRead_Elapsed.count(); #endif // OSMAND_PERFORMANCE_METRICS return true; } // Otherwise, this map object can be shared, so it should be checked for // being present in shared mapObjects storage, or be reserved there std::shared_ptr<const Model::BinaryMapObject> sharedMapObjectReference; proper::shared_future< std::shared_ptr<const Model::BinaryMapObject> > futureSharedMapObjectReference; if (_sharedMapObjects.obtainReferenceOrFutureReferenceOrMakePromise(id, zoom, Utilities::enumerateZoomLevels(firstZoomLevel, lastZoomLevel), sharedMapObjectReference, futureSharedMapObjectReference)) { if (sharedMapObjectReference) { // If map object is already in shared objects cache and is available, use that one referencedMapObjects.push_back(qMove(sharedMapObjectReference)); } else { futureReferencedMapObjects.push_back(qMove(futureSharedMapObjectReference)); } #if OSMAND_PERFORMANCE_METRICS const auto dataFilter_End = std::chrono::high_resolution_clock::now(); const std::chrono::duration<float> dataRead_Elapsed = dataFilter_End - dataFilter_Begin; dataFilter += dataRead_Elapsed.count(); #endif // OSMAND_PERFORMANCE_METRICS return false; } // This map object was reserved, and is going to be shared, but needs to be loaded loadedSharedMapObjects.insert(id); return true; }, #if OSMAND_PERFORMANCE_METRICS > 1 & dataRead_Metric #else nullptr #endif // OSMAND_PERFORMANCE_METRICS > 1 ); #if OSMAND_PERFORMANCE_METRICS const auto dataRead_End = std::chrono::high_resolution_clock::now(); const std::chrono::duration<float> dataRead_Elapsed = dataRead_End - dataRead_Begin; const auto dataIdsProcess_Begin = std::chrono::high_resolution_clock::now(); #endif // OSMAND_PERFORMANCE_METRICS // Process loaded-and-shared map objects for (auto& mapObject : loadedMapObjects) { // Check if this map object is shared if (!loadedSharedMapObjects.contains(mapObject->id)) continue; // Add unique map object under lock to all zoom levels, for which this map object is valid assert(mapObject->level); _sharedMapObjects.fulfilPromiseAndReference( mapObject->id, Utilities::enumerateZoomLevels(mapObject->level->minZoom, mapObject->level->maxZoom), mapObject); } for (auto& futureMapObject : futureReferencedMapObjects) { auto mapObject = futureMapObject.get(); referencedMapObjects.push_back(qMove(mapObject)); } #if OSMAND_PERFORMANCE_METRICS const auto dataIdsProcess_End = std::chrono::high_resolution_clock::now(); const std::chrono::duration<float> dataIdsProcess_Elapsed = dataIdsProcess_End - dataIdsProcess_Begin; const auto dataProcess_Begin = std::chrono::high_resolution_clock::now(); #endif // OSMAND_PERFORMANCE_METRICS #if OSMAND_PERFORMANCE_METRICS > 1 Rasterizer_Metrics::Metric_prepareContext dataProcess_metric; #endif // OSMAND_PERFORMANCE_METRICS > 1 // Prepare data for the tile const auto sharedMapObjectsCount = referencedMapObjects.size() + loadedSharedMapObjects.size(); const auto allMapObjects = loadedMapObjects + referencedMapObjects; // Allocate and prepare rasterizer context bool nothingToRasterize = false; std::shared_ptr<RasterizerContext> rasterizerContext(new RasterizerContext(owner->rasterizerEnvironment, owner->rasterizerSharedContext)); Rasterizer::prepareContext(*rasterizerContext, tileBBox31, zoom, tileFoundation, allMapObjects, ¬hingToRasterize, nullptr, #if OSMAND_PERFORMANCE_METRICS > 1 & dataProcess_metric #else nullptr #endif // OSMAND_PERFORMANCE_METRICS > 1 ); #if OSMAND_PERFORMANCE_METRICS const auto dataProcess_End = std::chrono::high_resolution_clock::now(); const std::chrono::duration<float> dataProcess_Elapsed = dataProcess_End - dataProcess_Begin; #endif // OSMAND_PERFORMANCE_METRICS // Create tile const std::shared_ptr<BinaryMapDataTile> newTile(new BinaryMapDataTile( tileFoundation, allMapObjects, rasterizerContext, nothingToRasterize, tileId, zoom)); newTile->_p->_weakLink = _link->getWeak(); newTile->_p->_refEntry = tileEntry; // Publish new tile outTiledData = newTile; // Store weak reference to new tile and mark it as 'Loaded' tileEntry->_tile = newTile; tileEntry->setState(TileState::Loaded); // Notify that tile has been loaded { QWriteLocker scopedLcoker(&tileEntry->_loadedConditionLock); tileEntry->_loadedCondition.wakeAll(); } #if OSMAND_PERFORMANCE_METRICS const auto total_End = std::chrono::high_resolution_clock::now(); const std::chrono::duration<float> total_Elapsed = total_End - total_Begin; #if OSMAND_PERFORMANCE_METRICS <= 1 LogPrintf(LogSeverityLevel::Info, "%d map objects (%d unique, %d shared) from %dx%d@%d in %fs", allMapObjects.size(), allMapObjects.size() - sharedMapObjectsCount, sharedMapObjectsCount, tileId.x, tileId.y, zoom, total_Elapsed.count()); #else LogPrintf(LogSeverityLevel::Info, "%d map objects (%d unique, %d shared) from %dx%d@%d in %fs:\n" "\topen %fs\n" "\tread %fs (filter-by-id %fs):\n" "\t - visitedLevels = %d\n" "\t - acceptedLevels = %d\n" "\t - visitedNodes = %d\n" "\t - acceptedNodes = %d\n" "\t - elapsedTimeForNodes = %fs\n" "\t - mapObjectsBlocksRead = %d\n" "\t - visitedMapObjects = %d\n" "\t - acceptedMapObjects = %d\n" "\t - elapsedTimeForMapObjectsBlocks = %fs\n" "\t - elapsedTimeForOnlyVisitedMapObjects = %fs\n" "\t - elapsedTimeForOnlyAcceptedMapObjects = %fs\n" "\t - average time per 1K only-visited map objects = %fms\n" "\t - average time per 1K only-accepted map objects = %fms\n" "\tprocess-ids %fs\n" "\tprocess-content %fs:\n" "\t - elapsedTimeForSortingObjects = %fs\n" "\t - elapsedTimeForPolygonizingCoastlines = %fs\n" "\t - polygonizedCoastlines = %d\n" "\t - elapsedTimeForObtainingPrimitives = %fs\n" "\t - elapsedTimeForOrderEvaluation = %fs\n" "\t - orderEvaluations = %d\n" "\t - average time per 1K order evaluations = %fms\n" "\t - elapsedTimeForPolygonEvaluation = %fs\n" "\t - polygonEvaluations = %d\n" "\t - average time per 1K polygon evaluations = %fms\n" "\t - polygonPrimitives = %d\n" "\t - elapsedTimeForPolylineEvaluation = %fs\n" "\t - polylineEvaluations = %d\n" "\t - average time per 1K polyline evaluations = %fms\n" "\t - polylinePrimitives = %d\n" "\t - elapsedTimeForPointEvaluation = %fs\n" "\t - pointEvaluations = %d\n" "\t - average time per 1K point evaluations = %fms\n" "\t - pointPrimitives = %d\n" "\t - elapsedTimeForObtainingPrimitivesSymbols = %fs", allMapObjects.size(), allMapObjects.size() - sharedMapObjectsCount, sharedMapObjectsCount, tileId.x, tileId.y, zoom, total_Elapsed.count(), obtainDataInterface_Elapsed.count(), dataRead_Elapsed.count(), dataFilter, dataRead_Metric.visitedLevels, dataRead_Metric.acceptedLevels, dataRead_Metric.visitedNodes, dataRead_Metric.acceptedNodes, dataRead_Metric.elapsedTimeForNodes, dataRead_Metric.mapObjectsBlocksRead, dataRead_Metric.visitedMapObjects, dataRead_Metric.acceptedMapObjects, dataRead_Metric.elapsedTimeForMapObjectsBlocks, dataRead_Metric.elapsedTimeForOnlyVisitedMapObjects, dataRead_Metric.elapsedTimeForOnlyAcceptedMapObjects, (dataRead_Metric.elapsedTimeForOnlyVisitedMapObjects * 1000.0f) / (static_cast<float>(dataRead_Metric.visitedMapObjects - dataRead_Metric.acceptedMapObjects) / 1000.0f), (dataRead_Metric.elapsedTimeForOnlyAcceptedMapObjects * 1000.0f) / (static_cast<float>(dataRead_Metric.acceptedMapObjects) / 1000.0f), dataIdsProcess_Elapsed.count(), dataProcess_Elapsed.count(), dataProcess_metric.elapsedTimeForSortingObjects, dataProcess_metric.elapsedTimeForPolygonizingCoastlines, dataProcess_metric.polygonizedCoastlines, dataProcess_metric.elapsedTimeForObtainingPrimitives, dataProcess_metric.elapsedTimeForOrderEvaluation, dataProcess_metric.orderEvaluations, (dataProcess_metric.elapsedTimeForOrderEvaluation * 1000.0f / static_cast<float>(dataProcess_metric.orderEvaluations)) * 1000.0f, dataProcess_metric.elapsedTimeForPolygonEvaluation, dataProcess_metric.polygonEvaluations, (dataProcess_metric.elapsedTimeForPolygonEvaluation * 1000.0f / static_cast<float>(dataProcess_metric.polygonEvaluations)) * 1000.0f, dataProcess_metric.polygonPrimitives, dataProcess_metric.elapsedTimeForPolylineEvaluation, dataProcess_metric.polylineEvaluations, (dataProcess_metric.elapsedTimeForPolylineEvaluation * 1000.0f / static_cast<float>(dataProcess_metric.polylineEvaluations)) * 1000.0f, dataProcess_metric.polylinePrimitives, dataProcess_metric.elapsedTimeForPointEvaluation, dataProcess_metric.pointEvaluations, (dataProcess_metric.elapsedTimeForPointEvaluation * 1000.0f / static_cast<float>(dataProcess_metric.pointEvaluations)) * 1000.0f, dataProcess_metric.pointPrimitives, dataProcess_metric.elapsedTimeForObtainingPrimitivesSymbols); #endif // OSMAND_PERFORMANCE_METRICS <= 1 #endif // OSMAND_PERFORMANCE_METRICS return true; }
void ClassTemplate::resolveStringProperty(ClassProperty *aProperty, QSet<ClassProperty *> &aCleanSet, QSet<ClassProperty *> &aCallstack, QSet<ClassProperty *>aAll) { //qDebug() << "resolveStringProperty " << aProperty->name(); if(aCallstack.contains(aProperty)) { qDebug() << "Property tokens circular dependency! " + aProperty->name(); return; } if(aCleanSet.contains(aProperty)) { //resolved already return; } QString value = aProperty->defaultValue(); if((!value.contains("{") && !value.contains("}")) || aProperty->isConst()) { aCleanSet.insert(aProperty); if(!aProperty->isConst()) initializationSection_ += "\t" + aProperty->name() + " = " + wrap(value) + ";\n"; //nothing to resolve return; } QRegularExpression token("\\{([^\\}]+)\\}"); QString temp = value; QRegularExpressionMatchIterator i = token.globalMatch(value); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString toReplace = match.captured(0); if(toReplace == "{a}") continue;//skipping article QString token = toReplace; token = token.replace("{", ""); token = token.replace("}", ""); ClassProperty *property = propertyByName(token, aAll); if(!property) { temp = temp.replace(toReplace, "\" + " + toCamelCase(token, false) + "() + \""); } else if(aCleanSet.contains(property)) { temp = temp.replace(toReplace, "\" + " + toCamelCase(token, false) + "() + \""); } else { /*aCallstack.insert(aProperty); resolveStringProperty(property, aCleanSet, aCallstack, aAll);//recursion temp = temp.replace(toReplace, "\" + " + toCamelCase(token, false) + "_ + \""); aCallstack.remove(aProperty);*/ qDebug() << "Pattern contains non-const tokens: " + value; } } aCleanSet.insert(aProperty); initializationSection_ += "\t" + aProperty->name() + " = " + wrap(temp) + ";\n"; }
// ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void MergeColonies::execute() { setErrorCondition(0); dataCheck(); if(getErrorCondition() < 0) { return; } axisTolerance = m_AxisTolerance * SIMPLib::Constants::k_Pi / 180.0f; GroupFeatures::execute(); size_t totalFeatures = m_ActivePtr.lock()->getNumberOfTuples(); if (totalFeatures < 2) { setErrorCondition(-87000); notifyErrorMessage(getHumanLabel(), "The number of Grouped Features was 0 or 1 which means no grouped Features were detected. A grouping value may be set too high", getErrorCondition()); return; } int32_t numParents = 0; size_t totalPoints = m_FeatureIdsPtr.lock()->getNumberOfTuples(); for (size_t k = 0; k < totalPoints; k++) { int32_t featurename = m_FeatureIds[k]; m_CellParentIds[k] = m_FeatureParentIds[featurename]; if (m_FeatureParentIds[featurename] > numParents) { numParents = m_FeatureParentIds[featurename]; } } numParents += 1; notifyStatusMessage(getHumanLabel(), "Characterizing Colonies"); characterize_colonies(); if (true == m_RandomizeParentIds) { // Generate all the numbers up front const int32_t rangeMin = 1; const int32_t rangeMax = numParents - 1; typedef boost::uniform_int<int32_t> NumberDistribution; typedef boost::mt19937 RandomNumberGenerator; typedef boost::variate_generator < RandomNumberGenerator&, NumberDistribution > Generator; NumberDistribution distribution(rangeMin, rangeMax); RandomNumberGenerator generator; Generator numberGenerator(generator, distribution); generator.seed(static_cast<boost::uint32_t>( QDateTime::currentMSecsSinceEpoch() )); // seed with the current time DataArray<int32_t>::Pointer rndNumbers = DataArray<int32_t>::CreateArray(numParents, "_INTERNAL_USE_ONLY_NewParentIds"); int32_t* pid = rndNumbers->getPointer(0); pid[0] = 0; QSet<int32_t> parentIdSet; parentIdSet.insert(0); for (int32_t i = 1; i < numParents; ++i) { pid[i] = i; // numberGenerator(); parentIdSet.insert(pid[i]); } int32_t r = 0; int32_t temp = 0; //--- Shuffle elements by randomly exchanging each with one other. for (int32_t i = 1; i < numParents; i++) { r = numberGenerator(); // Random remaining position. if (r >= numParents) { continue; } temp = pid[i]; pid[i] = pid[r]; pid[r] = temp; } // Now adjust all the Feature Id values for each Voxel for (size_t i = 0; i < totalPoints; ++i) { m_CellParentIds[i] = pid[ m_CellParentIds[i] ]; m_FeatureParentIds[m_FeatureIds[i]] = m_CellParentIds[i]; } } if (m_IdentifyGlobAlpha == true) { identify_globAlpha(); } notifyStatusMessage(getHumanLabel(), "Complete"); }
bool QgsComposerAttributeTable::readXML( const QDomElement& itemElem, const QDomDocument& doc ) { if ( itemElem.isNull() ) { return false; } //read general table properties if ( !tableReadXML( itemElem, doc ) ) { return false; } mShowOnlyVisibleFeatures = itemElem.attribute( "showOnlyVisibleFeatures", "1" ).toInt(); mFilterFeatures = itemElem.attribute( "filterFeatures", "false" ) == "true" ? true : false; mFeatureFilter = itemElem.attribute( "featureFilter", "" ); //composer map int composerMapId = itemElem.attribute( "composerMap", "-1" ).toInt(); if ( composerMapId == -1 ) { mComposerMap = 0; } if ( composition() ) { mComposerMap = composition()->getComposerMapById( composerMapId ); } else { mComposerMap = 0; } if ( mComposerMap ) { //if we have found a valid map item, listen out to extent changes on it and refresh the table QObject::connect( mComposerMap, SIGNAL( extentChanged() ), this, SLOT( refreshAttributes() ) ); } //vector layer QString layerId = itemElem.attribute( "vectorLayer", "not_existing" ); if ( layerId == "not_existing" ) { mVectorLayer = 0; } else { QgsMapLayer* ml = QgsMapLayerRegistry::instance()->mapLayer( layerId ); if ( ml ) { mVectorLayer = dynamic_cast<QgsVectorLayer*>( ml ); if ( mVectorLayer ) { //if we have found a valid vector layer, listen for modifications on it and refresh the table QObject::connect( mVectorLayer, SIGNAL( layerModified() ), this, SLOT( refreshAttributes() ) ); } } } //restore display attribute map. This is required to upgrade pre 2.4 projects. QSet<int> displayAttributes; QDomNodeList displayAttributeList = itemElem.elementsByTagName( "displayAttributes" ); if ( displayAttributeList.size() > 0 ) { QDomElement displayAttributesElem = displayAttributeList.at( 0 ).toElement(); QDomNodeList attributeEntryList = displayAttributesElem.elementsByTagName( "attributeEntry" ); for ( int i = 0; i < attributeEntryList.size(); ++i ) { QDomElement attributeEntryElem = attributeEntryList.at( i ).toElement(); int index = attributeEntryElem.attribute( "index", "-1" ).toInt(); if ( index != -1 ) { displayAttributes.insert( index ); } } setDisplayAttributes( displayAttributes, false ); } //restore alias map. This is required to upgrade pre 2.4 projects. QMap<int, QString> fieldAliasMap; QDomNodeList aliasMapNodeList = itemElem.elementsByTagName( "attributeAliasMap" ); if ( aliasMapNodeList.size() > 0 ) { QDomElement attributeAliasMapElem = aliasMapNodeList.at( 0 ).toElement(); QDomNodeList aliasMepEntryList = attributeAliasMapElem.elementsByTagName( "aliasEntry" ); for ( int i = 0; i < aliasMepEntryList.size(); ++i ) { QDomElement aliasEntryElem = aliasMepEntryList.at( i ).toElement(); int key = aliasEntryElem.attribute( "key", "-1" ).toInt(); QString value = aliasEntryElem.attribute( "value", "" ); fieldAliasMap.insert( key, value ); } restoreFieldAliasMap( fieldAliasMap ); } //restore sort columns. This is required to upgrade pre 2.4 projects. QDomElement sortColumnsElem = itemElem.firstChildElement( "sortColumns" ); if ( !sortColumnsElem.isNull() && mVectorLayer ) { QDomNodeList columns = sortColumnsElem.elementsByTagName( "column" ); const QgsFields& fields = mVectorLayer->pendingFields(); for ( int i = 0; i < columns.size(); ++i ) { QDomElement columnElem = columns.at( i ).toElement(); int attribute = columnElem.attribute( "index" ).toInt(); Qt::SortOrder order = columnElem.attribute( "ascending" ) == "true" ? Qt::AscendingOrder : Qt::DescendingOrder; //find corresponding column QList<QgsComposerTableColumn*>::iterator columnIt = mColumns.begin(); for ( ; columnIt != mColumns.end(); ++columnIt ) { if (( *columnIt )->attribute() == fields[attribute].name() ) { ( *columnIt )->setSortByRank( i + 1 ); ( *columnIt )->setSortOrder( order ); break; } } } } //must be done here because tableReadXML->setSceneRect changes mMaximumNumberOfFeatures mMaximumNumberOfFeatures = itemElem.attribute( "maxFeatures", "5" ).toInt(); refreshAttributes(); emit itemChanged(); return true; }
/** Add items to the table in order to edit them. */ bool TagEditorTableWidget::addItemsToEditor(const QStringList &tracks, QMap<int, Cover*> &covers) { QSet<QPair<QString, QString>> artistAlbumSet; for (QString track : tracks) { FileHelper fh(track); if (!fh.isValid()) { continue; } /// XXX: warning, this information is difficult to find even if public QTableWidgetItem *fileName = new QTableWidgetItem(fh.fileInfo().fileName()); fileName->setData(Qt::UserRole, fh.fileInfo().absoluteFilePath()); // The second column is not editable QTableWidgetItem *absPath = new QTableWidgetItem(QDir::toNativeSeparators(fh.fileInfo().path())); absPath->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); QTableWidgetItem *title = new QTableWidgetItem(fh.title()); QTableWidgetItem *artist = new QTableWidgetItem(fh.artist()); QTableWidgetItem *artistAlbum = new QTableWidgetItem(fh.artistAlbum()); QTableWidgetItem *album = new QTableWidgetItem(fh.album()); QTableWidgetItem *trackNumber = NULL; if (fh.trackNumber() == "00") { trackNumber = new QTableWidgetItem(); } else { trackNumber = new QTableWidgetItem(fh.trackNumber()); } QTableWidgetItem *disc; if (fh.discNumber() == 0) { disc = new QTableWidgetItem; } else { disc = new QTableWidgetItem(QString::number(fh.discNumber())); } QTableWidgetItem *year = new QTableWidgetItem(fh.year()); QTableWidgetItem *genre = new QTableWidgetItem(fh.genre()); QTableWidgetItem *comment = new QTableWidgetItem(fh.comment()); QList<QTableWidgetItem*> items; items << fileName << absPath << title << artist << artistAlbum << album << trackNumber << disc << year << genre << comment; // Check if there's only one album in the list, used for the context menu of the cover artistAlbumSet.insert(qMakePair(artist->text(), album->text())); // Create a new row with right data int row = rowCount(); this->insertRow(row); for (int column = 0; column < items.size(); column++) { this->setItem(row, column, items.at(column)); } _indexes.insert(row, fh.fileInfo().absoluteFilePath()); /// XXX is it really necessary to extract cover in this class? /// It might be better to build a fileHelper outside, in the container (TagEditor), and iterate 2 times /// One in this class, one in TagEditor class ? But here is quite easy! /*Cover *cover = fh.extractCover(); if (cover != NULL && !cover->byteArray().isEmpty()) { covers.insert(row, cover); }*/ } return (artistAlbumSet.size() == 1); }
QVariantMap QgsRemoveDuplicatesByAttributeAlgorithm::processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback ) { std::unique_ptr< QgsProcessingFeatureSource > source( parameterAsSource( parameters, QStringLiteral( "INPUT" ), context ) ); if ( !source ) throw QgsProcessingException( invalidSourceError( parameters, QStringLiteral( "INPUT" ) ) ); const QStringList fieldNames = parameterAsFields( parameters, QStringLiteral( "FIELDS" ), context ); QgsAttributeList attributes; for ( const QString &field : fieldNames ) { const int index = source->fields().lookupField( field ); if ( index < 0 ) feedback->reportError( QObject::tr( "Field %1 not found in INPUT layer, skipping" ).arg( field ) ); else attributes.append( index ); } if ( attributes.isEmpty() ) throw QgsProcessingException( QObject::tr( "No input fields found" ) ); QString noDupeSinkId; std::unique_ptr< QgsFeatureSink > noDupeSink( parameterAsSink( parameters, QStringLiteral( "OUTPUT" ), context, noDupeSinkId, source->fields(), source->wkbType(), source->sourceCrs() ) ); if ( !noDupeSink ) throw QgsProcessingException( invalidSinkError( parameters, QStringLiteral( "OUTPUT" ) ) ); QString dupeSinkId; std::unique_ptr< QgsFeatureSink > dupesSink( parameterAsSink( parameters, QStringLiteral( "DUPLICATES" ), context, dupeSinkId, source->fields(), source->wkbType(), source->sourceCrs() ) ); const long count = source->featureCount(); double step = count > 0 ? 100.0 / count : 1; int current = 0; long long keptCount = 0; long long discardedCount = 0; QSet< QVariantList > matched; QgsFeatureIterator it = source->getFeatures( QgsFeatureRequest(), QgsProcessingFeatureSource::FlagSkipGeometryValidityChecks ); QgsFeature f; QVariantList dupeKey; dupeKey.reserve( attributes.size() ); for ( int i : attributes ) { ( void )i; dupeKey.append( QVariant() ); } while ( it.nextFeature( f ) ) { if ( feedback->isCanceled() ) { break; } int i = 0; for ( int attr : attributes ) dupeKey[i++] = f.attribute( attr ); if ( matched.contains( dupeKey ) ) { // duplicate discardedCount++; if ( dupesSink ) dupesSink->addFeature( f, QgsFeatureSink::FastInsert ); } else { // not duplicate keptCount++; matched.insert( dupeKey ); noDupeSink->addFeature( f, QgsFeatureSink::FastInsert ); } feedback->setProgress( current * step ); current++; } QVariantMap outputs; outputs.insert( QStringLiteral( "RETAINED_COUNT" ), keptCount ); outputs.insert( QStringLiteral( "DUPLICATE_COUNT" ), discardedCount ); outputs.insert( QStringLiteral( "OUTPUT" ), noDupeSinkId ); if ( dupesSink ) outputs.insert( QStringLiteral( "DUPLICATES" ), dupeSinkId ); return outputs; }
bool NetworkMergerCreator::createMergers(const MatchSet& matchesIn, vector<Merger*>& mergers) const { LOG_TRACE("Creating mergers with " << className() << "..."); LOG_TRACE("Creating mergers for match set: " << matchesIn); QString matchesList = ""; if (hoot::Log::Trace == hoot::Log::getInstance().getLevel()) { for (MatchSet::const_iterator it = matchesIn.begin(); it != matchesIn.end(); ++it) { const NetworkMatch* nmi = dynamic_cast<const NetworkMatch*>(*it); if (nmi) { matchesList += nmi->getEdgeMatch()->getUid() + " "; } } } LOG_TRACE(matchesList.size()); LOG_TRACE(matchesList); MatchSet matches = matchesIn; LOG_VART(matches); bool result = false; assert(matches.size() > 0); const NetworkMatch* m = dynamic_cast<const NetworkMatch*>(*matches.begin()); if (m) { const bool matchOverlap = _containsOverlap(matches); LOG_VART(matchOverlap); if (!matchOverlap) { // create a merger that can merge multiple partial matches QSet<ConstEdgeMatchPtr> edgeMatches; int count = 0; set<pair<ElementId, ElementId>> pairs; foreach (const Match* itm, matches) { const NetworkMatch* nm = dynamic_cast<const NetworkMatch*>(itm); edgeMatches.insert(nm->getEdgeMatch()); set<pair<ElementId, ElementId>> p = nm->getMatchPairs(); pairs.insert(p.begin(), p.end()); count++; if (count % 100 == 0) { PROGRESS_INFO( "Added match " << count << " / " << matches.size() << " to partial network merger..."); } } if (!ConfigOptions().getHighwayMergeTagsOnly()) { mergers.push_back(new PartialNetworkMerger(pairs, edgeMatches, m->getNetworkDetails())); } else { // TODO: We need to allow for HighwayTagOnlyMerger to spawn off PartialNetworkMerger here, // I guess...but that's kind of nasty... (applies to the rest of the calls to // HighwayTagOnlyMerger in this class as well). mergers.push_back(new HighwayTagOnlyMerger(pairs)); } } else { // If one match completely contains the rest, use the larger match. This may need to be // reverted as we play with more data, but at this point it seems like a reasonable heuristic. if (const NetworkMatch* larger = _getLargestContainer(matches))
static const QSet<QString> &qscriptKeywords() { static QSet<QString> keywords; if (keywords.empty()) { keywords.insert(QLatin1String("Infinity")); keywords.insert(QLatin1String("NaN")); keywords.insert(QLatin1String("abstract")); keywords.insert(QLatin1String("boolean")); keywords.insert(QLatin1String("break")); keywords.insert(QLatin1String("byte")); keywords.insert(QLatin1String("case")); keywords.insert(QLatin1String("catch")); keywords.insert(QLatin1String("char")); keywords.insert(QLatin1String("class")); keywords.insert(QLatin1String("const")); keywords.insert(QLatin1String("constructor")); keywords.insert(QLatin1String("continue")); keywords.insert(QLatin1String("debugger")); keywords.insert(QLatin1String("default")); keywords.insert(QLatin1String("delete")); keywords.insert(QLatin1String("do")); keywords.insert(QLatin1String("double")); keywords.insert(QLatin1String("else")); keywords.insert(QLatin1String("enum")); keywords.insert(QLatin1String("export")); keywords.insert(QLatin1String("extends")); keywords.insert(QLatin1String("false")); keywords.insert(QLatin1String("final")); keywords.insert(QLatin1String("finally")); keywords.insert(QLatin1String("float")); keywords.insert(QLatin1String("for")); keywords.insert(QLatin1String("function")); keywords.insert(QLatin1String("goto")); keywords.insert(QLatin1String("if")); keywords.insert(QLatin1String("implements")); keywords.insert(QLatin1String("import")); keywords.insert(QLatin1String("in")); keywords.insert(QLatin1String("instanceof")); keywords.insert(QLatin1String("int")); keywords.insert(QLatin1String("interface")); keywords.insert(QLatin1String("long")); keywords.insert(QLatin1String("native")); keywords.insert(QLatin1String("new")); keywords.insert(QLatin1String("package")); keywords.insert(QLatin1String("private")); keywords.insert(QLatin1String("protected")); keywords.insert(QLatin1String("public")); keywords.insert(QLatin1String("return")); keywords.insert(QLatin1String("short")); keywords.insert(QLatin1String("static")); keywords.insert(QLatin1String("super")); keywords.insert(QLatin1String("switch")); keywords.insert(QLatin1String("synchronized")); keywords.insert(QLatin1String("this")); keywords.insert(QLatin1String("throw")); keywords.insert(QLatin1String("throws")); keywords.insert(QLatin1String("transient")); keywords.insert(QLatin1String("true")); keywords.insert(QLatin1String("try")); keywords.insert(QLatin1String("typeof")); keywords.insert(QLatin1String("undefined")); keywords.insert(QLatin1String("var")); keywords.insert(QLatin1String("void")); keywords.insert(QLatin1String("volatile")); keywords.insert(QLatin1String("while")); keywords.insert(QLatin1String("with")); // end } return keywords; }
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl) { qint64 total = 0; QList<SendCoinsRecipient> recipients = transaction.getRecipients(); std::vector<std::pair<CScript, int64_t> > vecSend; if(recipients.empty()) { return OK; } QSet<QString> setAddress; // Used to detect duplicates int nAddresses = 0; // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { // PaymentRequest... int64_t subtotal = 0; const payments::PaymentDetails& details = rcp.paymentRequest.getDetails(); for (int i = 0; i < details.outputs_size(); i++) { const payments::Output& out = details.outputs(i); if (out.amount() <= 0) continue; subtotal += out.amount(); const unsigned char* scriptStr = (const unsigned char*)out.script().data(); CScript scriptPubKey(scriptStr, scriptStr+out.script().size()); vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, out.amount())); } if (subtotal <= 0) { return InvalidAmount; } total += subtotal; } else { // User-entered bitcoin address / amount: if(!validateAddress(rcp.address)) { return InvalidAddress; } if(rcp.amount <= 0) { return InvalidAmount; } setAddress.insert(rcp.address); ++nAddresses; // stealth std::string sAddr = rcp.address.toStdString(); if (rcp.typeInd == AddressTableModel::AT_Stealth) { if ( (!TestNet() && (chainActive.Height() < BLOCK_STEALTH_START)) || (TestNet() && (chainActive.Height() < 200)) ) { emit message(tr("Send Coins"), tr("Stealth addresses not yet supported"), CClientUIInterface::MSG_ERROR); return InvalidAddress; } CStealthAddress sxAddr; if (sxAddr.SetEncoded(sAddr)) { ec_secret ephem_secret; ec_secret secretShared; ec_point pkSendTo; ec_point ephem_pubkey; if (GenerateRandomSecret(ephem_secret) != 0) { LogPrintf("GenerateRandomSecret failed.\n"); return InvalidAddress; }; if (StealthSecret(ephem_secret, sxAddr.scan_pubkey, sxAddr.spend_pubkey, secretShared, pkSendTo) != 0) { LogPrintf("Could not generate receiving public key.\n"); return InvalidAddress; }; CPubKey cpkTo(pkSendTo); if (!cpkTo.IsValid()) { LogPrintf("Invalid public key generated.\n"); return InvalidAddress; }; CKeyID ckidTo = cpkTo.GetID(); CBitcoinAddress addrTo(ckidTo); if (SecretToPublicKey(ephem_secret, ephem_pubkey) != 0) { LogPrintf("Could not generate ephem public key.\n"); return InvalidAddress; }; if (fDebug) { LogPrintf("Stealth send to generated pubkey %ui: %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str()); LogPrintf("hash %s\n", addrTo.ToString().c_str()); LogPrintf("ephem_pubkey %ui: %s\n", ephem_pubkey.size(), HexStr(ephem_pubkey).c_str()); }; CScript scriptPubKey; scriptPubKey.SetDestination(addrTo.Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); CScript scriptP = CScript() << OP_RETURN << ephem_pubkey; vecSend.push_back(make_pair(scriptP, 0)); continue; }; // else drop through to normal } CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(sAddr).Get()); vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, rcp.amount)); total += rcp.amount; } } if(setAddress.size() != nAddresses) { return DuplicateAddress; } qint64 nBalance = getBalance(coinControl); if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { transaction.setTransactionFee(nTransactionFee); return SendCoinsReturn(AmountWithFeeExceedsBalance); } { LOCK2(cs_main, wallet->cs_wallet); transaction.newPossibleKeyChange(wallet); int64_t nFeeRequired = 0; std::string strFailReason; CWalletTx *newTx = transaction.getTransaction(); CReserveKey *keyChange = transaction.getPossibleKeyChange(); // int nChangePos = -1; bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, /*nChangePos,*/ strFailReason, coinControl); /* std::map<int, std::string>::iterator it; for (it = mapStealthNarr.begin(); it != mapStealthNarr.end(); ++it) { int pos = it->first; if (nChangePos > -1 && it->first >= nChangePos) pos++; char key[64]; if (snprintf(key, sizeof(key), "n_%u", pos) < 1) { printf("CreateStealthTransaction(): Error creating narration key."); continue; }; wtx.mapValue[key] = it->second; }; */ transaction.setTransactionFee(nFeeRequired); if(!fCreated) { if((total + nFeeRequired) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance); } emit message(tr("Send Coins"), QString::fromStdString(strFailReason), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } } return SendCoinsReturn(OK); }
bool AppxEngine::installDependencies() { Q_D(AppxEngine); qCDebug(lcWinRtRunner) << __FUNCTION__; QSet<QString> toInstall; foreach (const QString &dependencyName, d->dependencies) { toInstall.insert(dependencyName); qCDebug(lcWinRtRunner).nospace() << "dependency to be installed: " << dependencyName; } if (toInstall.isEmpty()) return true; const QString extensionSdkDir = extensionSdkPath(); if (!QFile::exists(extensionSdkDir)) { qCWarning(lcWinRtRunner).nospace() << QString(QStringLiteral("The directory '%1' does not exist.")).arg( QDir::toNativeSeparators(extensionSdkDir)); return false; } qCDebug(lcWinRtRunner).nospace() << "looking for dependency packages in " << extensionSdkDir; QDirIterator dit(extensionSdkDir, QStringList() << QStringLiteral("*.appx"), QDir::Files, QDirIterator::Subdirectories); while (dit.hasNext()) { dit.next(); HRESULT hr; ComPtr<IStream> inputStream; hr = SHCreateStreamOnFileEx(wchar(dit.filePath()), STGM_READ | STGM_SHARE_EXCLUSIVE, 0, FALSE, NULL, &inputStream); CHECK_RESULT("Failed to create input stream for package in ExtensionSdkDir.", continue); ComPtr<IAppxPackageReader> packageReader; hr = d->packageFactory->CreatePackageReader(inputStream.Get(), &packageReader); CHECK_RESULT("Failed to create package reader for package in ExtensionSdkDir.", continue); ComPtr<IAppxManifestReader> manifestReader; hr = packageReader->GetManifest(&manifestReader); CHECK_RESULT("Failed to create manifest reader for package in ExtensionSdkDir.", continue); ComPtr<IAppxManifestPackageId> packageId; hr = manifestReader->GetPackageId(&packageId); CHECK_RESULT("Failed to retrieve package id for package in ExtensionSdkDir.", continue); LPWSTR sz; hr = packageId->GetName(&sz); CHECK_RESULT("Failed to retrieve name from package in ExtensionSdkDir.", continue); const QString name = QString::fromWCharArray(sz); CoTaskMemFree(sz); if (!toInstall.contains(name)) continue; APPX_PACKAGE_ARCHITECTURE arch; hr = packageId->GetArchitecture(&arch); CHECK_RESULT("Failed to retrieve architecture from package in ExtensionSdkDir.", continue); if (d->packageArchitecture != arch) continue; qCDebug(lcWinRtRunner).nospace() << "installing dependency " << name << " from " << dit.filePath(); if (!installPackage(manifestReader.Get(), dit.filePath())) { qCWarning(lcWinRtRunner) << "Failed to install package:" << name; return false; } } return true; }
void runMultipleRulesTest() { ImplicitTagRulesSqliteReader reader; reader.setAddTopTagOnly(false); reader.setAllowWordsInvolvedInMultipleRules(false); reader.open("test-files/io/ImplicitTagRulesSqliteReaderTest/rules.sqlite"); QSet<QString> words; QSet<QString> ruleWordsInvolved; bool wordsInvolvedInMultipleRules = false; Tags tags; words.insert("Mosque"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mosque")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("MOSQUE"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mosque")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("mosque"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mosque")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("Mustashfa"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("MUSTASHFA"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("mustashfa"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("mosque"); words.insert("Mustashfa"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(2, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mosque")); CPPUNIT_ASSERT(wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(tags.isEmpty()); words.clear(); words.insert("mosque2"); words.insert("Mustashfa"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("mosque 3"); words.insert("Mustashfa"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("alwhdt"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("alwhdt")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("Mustashfa"); words.insert("alwhdt"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(2, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(ruleWordsInvolved.contains("alwhdt")); CPPUNIT_ASSERT(wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(tags.isEmpty()); words.clear(); words.insert("Mustashfa alwhdt"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(1, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa alwhdt")); CPPUNIT_ASSERT(!wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(!tags.isEmpty()); words.clear(); words.insert("Mustashfa alwhdt"); words.insert("Mustashfa"); words.insert("alwhdt"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(3, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(ruleWordsInvolved.contains("alwhdt")); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa alwhdt")); CPPUNIT_ASSERT(wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(tags.isEmpty()); words.clear(); words.insert("MUSTASHFA ALWHDT"); words.insert("MUSTASHFA"); words.insert("ALWHDT"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(3, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(ruleWordsInvolved.contains("alwhdt")); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa alwhdt")); CPPUNIT_ASSERT(wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(tags.isEmpty()); words.clear(); words.insert("mustashfa alwhdt"); words.insert("mustashfa"); words.insert("alwhdt"); tags = reader.getImplicitTags(words, ruleWordsInvolved, wordsInvolvedInMultipleRules); CPPUNIT_ASSERT_EQUAL(3, ruleWordsInvolved.size()); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa")); CPPUNIT_ASSERT(ruleWordsInvolved.contains("alwhdt")); CPPUNIT_ASSERT(ruleWordsInvolved.contains("Mustashfa alwhdt")); CPPUNIT_ASSERT(wordsInvolvedInMultipleRules); CPPUNIT_ASSERT(tags.isEmpty()); words.clear(); reader.close(); }
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl) { qint64 total = 0; QList<SendCoinsRecipient> recipients = transaction.getRecipients(); std::vector<std::pair<CScript, int64_t> > vecSend; if(recipients.empty()) { return OK; } QSet<QString> setAddress; // Used to detect duplicates int nAddresses = 0; // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if (rcp.paymentRequest.IsInitialized()) { // PaymentRequest... int64_t subtotal = 0; const payments::PaymentDetails& details = rcp.paymentRequest.getDetails(); for (int i = 0; i < details.outputs_size(); i++) { const payments::Output& out = details.outputs(i); if (out.amount() <= 0) continue; subtotal += out.amount(); const unsigned char* scriptStr = (const unsigned char*)out.script().data(); CScript scriptPubKey(scriptStr, scriptStr+out.script().size()); vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, out.amount())); } if (subtotal <= 0) { return InvalidAmount; } total += subtotal; } else { // User-entered bitcoin address / amount: if(!validateAddress(rcp.address)) { return InvalidAddress; } if(rcp.amount <= 0) { return InvalidAmount; } setAddress.insert(rcp.address); ++nAddresses; CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(std::pair<CScript, int64_t>(scriptPubKey, rcp.amount)); total += rcp.amount; } } if(setAddress.size() != nAddresses) { return DuplicateAddress; } qint64 nBalance = getBalance(coinControl); if(total > nBalance) { return AmountExceedsBalance; } { LOCK2(cs_main, wallet->cs_wallet); transaction.newPossibleKeyChange(wallet); int64_t nFeeRequired = 0; std::string strFailReason; CWalletTx *newTx = transaction.getTransaction(); CReserveKey *keyChange = transaction.getPossibleKeyChange(); bool fCreated = wallet->CreateTransaction(vecSend, *newTx, *keyChange, nFeeRequired, strFailReason, coinControl); transaction.setTransactionFee(nFeeRequired); if(!fCreated) { if((total + nFeeRequired) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance); } emit message(tr("Send Coins"), QString::fromStdString(strFailReason), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } } return SendCoinsReturn(OK); }
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, int nSplitBlock, const CCoinControl *coinControl) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount <= 0) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } int64_t nBalance = 0; std::vector<COutput> vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) nBalance += out.tx->vout[out.i].nValue; if(total > nBalance) { return AmountExceedsBalance; } if((total + nTransactionFee) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64_t> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64_t nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nSplitBlock, coinControl); if(!fCreated) { if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); }
Kb::Kb(QObject *parent, const QString& path) : QThread(parent), devpath(path), cmdpath(path + "/cmd"), features("N/A"), firmware("N/A"), pollrate("N/A"), _currentProfile(0), _currentMode(0), _model(KeyMap::NO_MODEL), _layout(KeyMap::NO_LAYOUT), _hwProfile(0), prevProfile(0), prevMode(0), cmd(cmdpath), notifyNumber(1), _needsSave(false), hwLoading(true) { // Get the features, model, serial number, FW version (if available), and poll rate (if available) from /dev nodes QFile ftpath(path + "/features"), mpath(path + "/model"), spath(path + "/serial"), fwpath(path + "/fwversion"), ppath(path + "/pollrate"); if(ftpath.open(QIODevice::ReadOnly)){ features = ftpath.read(1000); features = features.trimmed(); ftpath.close(); // Read model from features (first word: vendor, second word: product) QStringList list = features.split(" "); if(list.length() < 2) return; _model = KeyMap::getModel(list[1]); if(_model == KeyMap::NO_MODEL) return; } else // Bail if features aren't readable return; if(mpath.open(QIODevice::ReadOnly)){ usbModel = mpath.read(100); usbModel = usbModel.remove("Corsair").remove("Gaming").remove("Keyboard").remove("Mouse").remove("Bootloader").trimmed(); mpath.close(); } if(usbModel == "") usbModel = "Keyboard"; if(spath.open(QIODevice::ReadOnly)){ usbSerial = spath.read(100); usbSerial = usbSerial.trimmed().toUpper(); spath.close(); } if(usbSerial == "") usbSerial = "Unknown-" + usbModel; if(features.contains("fwversion") && fwpath.open(QIODevice::ReadOnly)){ firmware = fwpath.read(100); firmware = QString::number(firmware.trimmed().toInt() / 100., 'f', 2); fwpath.close(); } if(features.contains("pollrate") && ppath.open(QIODevice::ReadOnly)){ pollrate = ppath.read(100); pollrate = pollrate.trimmed(); ppath.close(); } hwModeCount = (_model == KeyMap::K95) ? 3 : 1; // Open cmd in non-blocking mode so that it doesn't lock up if nothing is reading // (e.g. if the daemon crashed and didn't clean up the node) int fd = open(cmdpath.toLatin1().constData(), O_WRONLY | O_NONBLOCK); if(!cmd.open(fd, QIODevice::WriteOnly, QFileDevice::AutoCloseHandle)) return; // Find an available notification node (if none is found, take notify1) for(int i = 1; i < 10; i++){ QString notify = QString(path + "/notify%1").arg(i); if(!QFile::exists(notify)){ notifyNumber = i; notifyPath = notify; break; } } cmd.write(QString("notifyon %1\n").arg(notifyNumber).toLatin1()); cmd.flush(); cmd.write(QString("fps %1\n").arg(_frameRate).toLatin1()); cmd.write(QString("active\n@%1 get :hwprofileid").arg(notifyNumber).toLatin1()); for(int i = 0; i < hwModeCount; i++){ cmd.write(QString(" mode %1 get :hwid").arg(i + 1).toLatin1()); if(isMouse()) cmd.write(" :hwdpi :hwdpisel :hwlift :hwsnap"); } cmd.write("\n"); cmd.flush(); emit infoUpdated(); activeDevices.insert(this); // Start a separate thread to read from the notification node start(); }
WalletModel::SendCoinsReturn WalletModel::prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl) { CAmount total = 0; bool fSubtractFeeFromAmount = false; QList<SendCoinsRecipient> recipients = transaction.getRecipients(); std::vector<CRecipient> vecSend; if(recipients.empty()) { return OK; } QSet<QString> setAddress; // Used to detect duplicates int nAddresses = 0; // Pre-check input data for validity Q_FOREACH(const SendCoinsRecipient &rcp, recipients) { if (rcp.fSubtractFeeFromAmount) fSubtractFeeFromAmount = true; if (rcp.paymentRequest.IsInitialized()) { // PaymentRequest... CAmount subtotal = 0; const payments::PaymentDetails& details = rcp.paymentRequest.getDetails(); for (int i = 0; i < details.outputs_size(); i++) { const payments::Output& out = details.outputs(i); if (out.amount() <= 0) continue; subtotal += out.amount(); const unsigned char* scriptStr = (const unsigned char*)out.script().data(); CScript scriptPubKey(scriptStr, scriptStr+out.script().size()); CAmount nAmount = out.amount(); CRecipient recipient = {scriptPubKey, nAmount, rcp.fSubtractFeeFromAmount}; vecSend.push_back(recipient); } if (subtotal <= 0) { return InvalidAmount; } total += subtotal; } else { // User-entered bitcoin address / amount: if(!validateAddress(rcp.address)) { return InvalidAddress; } if(rcp.amount <= 0) { return InvalidAmount; } setAddress.insert(rcp.address); ++nAddresses; CScript scriptPubKey = GetScriptForDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); CRecipient recipient = {scriptPubKey, rcp.amount, rcp.fSubtractFeeFromAmount}; vecSend.push_back(recipient); total += rcp.amount; } } if(setAddress.size() != nAddresses) { return DuplicateAddress; } CAmount nBalance = getBalance(coinControl); if(total > nBalance) { return AmountExceedsBalance; } { LOCK2(cs_main, wallet->cs_wallet); transaction.newPossibleKeyChange(wallet); CAmount nFeeRequired = 0; int nChangePosRet = -1; std::string strFailReason; CWalletTx *newTx = transaction.getTransaction(); CReserveKey *keyChange = transaction.getPossibleKeyChange(); bool fCreated = wallet->CreateTransaction(vecSend, NULL, *newTx, *keyChange, nFeeRequired, nChangePosRet, strFailReason, coinControl); transaction.setTransactionFee(nFeeRequired); if (fSubtractFeeFromAmount && fCreated) transaction.reassignAmounts(nChangePosRet); if(!fCreated) { if(!fSubtractFeeFromAmount && (total + nFeeRequired) > nBalance) { return SendCoinsReturn(AmountWithFeeExceedsBalance); } Q_EMIT message(tr("Send Coins"), QString::fromStdString(strFailReason), CClientUIInterface::MSG_ERROR); return TransactionCreationFailed; } // reject absurdly high fee > 0.1 bitcoin if (nFeeRequired > 10000000) return AbsurdFee; } return SendCoinsReturn(OK); }
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients) { qint64 total = 0; QSet<QString> setAddress; QString hex; if(recipients.empty()) { return OK; } // Pre-check input data for validity foreach(const SendCoinsRecipient &rcp, recipients) { if(!validateAddress(rcp.address)) { return InvalidAddress; } setAddress.insert(rcp.address); if(rcp.amount < MIN_TXOUT_AMOUNT) { return InvalidAmount; } total += rcp.amount; } if(recipients.size() > setAddress.size()) { return DuplicateAddress; } if(total > getBalance()) { return AmountExceedsBalance; } if((total + nTransactionFee) > getBalance()) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee); } { LOCK2(cs_main, wallet->cs_wallet); // Sendmany std::vector<std::pair<CScript, int64> > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { CScript scriptPubKey; scriptPubKey.SetBitcoinAddress(rcp.address.toStdString()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); } CWalletTx wtx; CReserveKey keyChange(wallet); int64 nFeeRequired = 0; bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); if(!fCreated) { if((total + nFeeRequired) > wallet->GetBalance()) { return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired); } return TransactionCreationFailed; } if(!ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString())) { return Aborted; } if(!wallet->CommitTransaction(wtx, keyChange)) { return TransactionCommitFailed; } hex = QString::fromStdString(wtx.GetHash().GetHex()); }
int QgsPalLabeling::prepareLayer( QgsVectorLayer* layer, QSet<int>& attrIndices, QgsRenderContext& ctx ) { Q_ASSERT( mMapRenderer != NULL ); // start with a temporary settings class, find out labeling info QgsPalLayerSettings lyrTmp; lyrTmp.readFromLayer( layer ); if ( !lyrTmp.enabled ) return 0; // find out which field will be needed int fldIndex = layer->fieldNameIndex( lyrTmp.fieldName ); if ( fldIndex == -1 ) return 0; attrIndices.insert( fldIndex ); //add indices of data defined fields QMap< QgsPalLayerSettings::DataDefinedProperties, int >::const_iterator dIt = lyrTmp.dataDefinedProperties.constBegin(); for ( ; dIt != lyrTmp.dataDefinedProperties.constEnd(); ++dIt ) { attrIndices.insert( dIt.value() ); } // add layer settings to the pallabeling hashtable: <QgsVectorLayer*, QgsPalLayerSettings> mActiveLayers.insert( layer, lyrTmp ); // start using the reference to the layer in hashtable instead of local instance QgsPalLayerSettings& lyr = mActiveLayers[layer]; // how to place the labels Arrangement arrangement; switch ( lyr.placement ) { case QgsPalLayerSettings::AroundPoint: arrangement = P_POINT; break; case QgsPalLayerSettings::OverPoint: arrangement = P_POINT_OVER; break; case QgsPalLayerSettings::Line: arrangement = P_LINE; break; case QgsPalLayerSettings::Curved: arrangement = P_CURVED; break; case QgsPalLayerSettings::Horizontal: arrangement = P_HORIZ; break; case QgsPalLayerSettings::Free: arrangement = P_FREE; break; default: Q_ASSERT( "unsupported placement" && 0 ); return 0; } // create the pal layer double priority = 1 - lyr.priority / 10.0; // convert 0..10 --> 1..0 double min_scale = -1, max_scale = -1; if ( lyr.scaleMin != 0 && lyr.scaleMax != 0 ) { min_scale = lyr.scaleMin; max_scale = lyr.scaleMax; } Layer* l = mPal->addLayer( layer->id().toUtf8().data(), min_scale, max_scale, arrangement, METER, priority, lyr.obstacle, true, true ); if ( lyr.placementFlags ) l->setArrangementFlags( lyr.placementFlags ); // set label mode (label per feature is the default) l->setLabelMode( lyr.labelPerPart ? Layer::LabelPerFeaturePart : Layer::LabelPerFeature ); // set whether adjacent lines should be merged l->setMergeConnectedLines( lyr.mergeLines ); lyr.textFont.setPixelSize( lyr.sizeToPixel( lyr.textFont.pointSizeF(), ctx ) ); //raster and vector scale factors lyr.vectorScaleFactor = ctx.scaleFactor(); lyr.rasterCompressFactor = ctx.rasterScaleFactor(); // save the pal layer to our layer context (with some additional info) lyr.palLayer = l; lyr.fieldIndex = fldIndex; lyr.fontMetrics = new QFontMetricsF( lyr.textFont ); lyr.xform = mMapRenderer->coordinateTransform(); if ( mMapRenderer->hasCrsTransformEnabled() ) lyr.ct = new QgsCoordinateTransform( layer->crs(), mMapRenderer->destinationCrs() ); else lyr.ct = NULL; lyr.ptZero = lyr.xform->toMapCoordinates( 0, 0 ); lyr.ptOne = lyr.xform->toMapCoordinates( 1, 0 ); // rect for clipping lyr.extentGeom = QgsGeometry::fromRect( mMapRenderer->extent() ); return 1; // init successful }
void TestQgsWcsPublicServers::test( ) { QStringList versions; // It may happen that server supports 1.1.1, but does not accept 1.1 (http://zeus.pin.unifi.it/gi-wcs/http) versions << "" << "1.0.0" << "1.1.0"; // empty for default QStringList servers; // Some (first) coverages do not advertize any supportedCRS and sever gives // error both with native CRS (EPSG::561005) and EPSG:4326 // MOD* coverages work OK servers << "http://argon.geogr.uni-jena.de:8080/geoserver/ows"; servers << "http://demo.geonode.org/geoserver/wcs"; servers << "http://demo.mapserver.org/cgi-bin/wcs"; servers << "http://demo.opengeo.org/geoserver/wcs"; // geobrain.laits.gmu.edu servers are quite slow servers << "http://geobrain.laits.gmu.edu/cgi-bin/gbwcs-dem"; servers << "http://geobrain.laits.gmu.edu/cgi-bin/ows8/wcseo"; servers << "http://geobrain.laits.gmu.edu/cgi-bin/wcs110"; servers << "http://geobrain.laits.gmu.edu/cgi-bin/wcs-all"; servers << "http://iceds.ge.ucl.ac.uk/cgi-bin/icedswcs"; servers << "http://motherlode.ucar.edu:8080/thredds/wcs/fmrc/NCEP/DGEX/Alaska_12km/NCEP-DGEX-Alaska_12km_best.ncd"; servers << "http://navigator.state.or.us/ArcGIS/services/Framework/Imagery_Mosaic2009/ImageServer/WCSServer"; servers << "http://nsidc.org/cgi-bin/atlas_north"; servers << "http://sedac.ciesin.columbia.edu/geoserver/wcs"; // Big and slow //servers << "http://webmap.ornl.gov/ogcbroker/wcs"; servers << "http://ws.csiss.gmu.edu/cgi-bin/wcs-t"; // Big and slow //servers << "http://ws.laits.gmu.edu/cgi-bin/wcs-all"; // Currently very slow or down //servers << "http://www.sogeo.ch/geoserver/wcs"; // Slow and erroneous //servers << "http://zeus.pin.unifi.it/gi-wcs/http"; foreach ( QString server, servers ) { QStringList myServerLog; myServerLog << "server:" + server; QString myServerDirName = server; myServerDirName.replace( QRegExp( "[:/]+" ), "." ); myServerDirName.replace( QRegExp( "\\.$" ), "" ); QgsDebugMsg( "myServerDirName = " + myServerDirName ); QDir myServerDir( mCacheDir.absolutePath() + QDir::separator() + myServerDirName ); QString myServerLogPath = myServerDir.absolutePath() + QDir::separator() + "server.log"; if ( QFileInfo( myServerLogPath ).exists() ) { QgsDebugMsg( "cache exists " + myServerDir.absolutePath() ); continue; } if ( !myServerDir.exists() ) { mCacheDir.mkdir( myServerDirName ); } foreach ( QString version, versions ) { QgsDebugMsg( "server: " + server + " version: " + version ); QgsDataSourceURI myServerUri; myServerUri.setParam( "url", server ); if ( !version.isEmpty() ) { myServerUri.setParam( "version", version ); } QgsWcsCapabilities myCapabilities; myCapabilities.setUri( myServerUri ); if ( !myCapabilities.lastError().isEmpty() ) { QgsDebugMsg( myCapabilities.lastError() ); myServerLog << "error: (version: " + version + ") " + myCapabilities.lastError().replace( "\n", " " ); continue; } QVector<QgsWcsCoverageSummary> myCoverages; if ( !myCapabilities.supportedCoverages( myCoverages ) ) { QgsDebugMsg( "Cannot get list of coverages" ); myServerLog << "error: (version: " + version + ") Cannot get list of coverages"; continue; } int myCoverageCount = 0; int myStep = myCoverages.size() / mMaxCoverages; int myStepCount = -1; foreach ( QgsWcsCoverageSummary myCoverage, myCoverages ) { QgsDebugMsg( "coverage: " + myCoverage.identifier ); // Go in steps to get more success/errors if ( myStepCount == -1 || myStepCount > myStep ) { myStepCount = 0; } else { myStepCount++; continue; } myCoverageCount++; if ( myCoverageCount > mMaxCoverages ) break; QString myPath = myServerDir.absolutePath() + QDir::separator() + myCoverage.identifier; if ( !version.isEmpty() ) { myPath += "-" + version; } QString myLogPath = myPath + ".log"; if ( QFileInfo( myLogPath ).exists() ) { QMap<QString, QString> log = readLog( myLogPath ); if ( !log.value( "identifier" ).isEmpty() && log.value( "error" ).isEmpty() ) continue; } QStringList myLog; myLog << "identifier:" + myCoverage.identifier; myCapabilities.describeCoverage( myCoverage.identifier ); myCoverage = myCapabilities.coverage( myCoverage.identifier ); // get described QgsDataSourceURI myUri = myServerUri; myUri.setParam( "identifier", myCoverage.identifier ); if ( myCoverage.times.size() > 0 ) { myUri.setParam( "time", myCoverage.times.value( 0 ) ); } myLog << "version:" + version; myLog << "uri:" + myUri.encodedUri(); int myWidth = 100; int myHeight = 100; if ( myCoverage.hasSize ) { myHeight = static_cast<int>( qRound( 1.0 * myWidth * myCoverage.height / myCoverage.width ) ); } myLog << QString( "hasSize:%1" ).arg( myCoverage.hasSize ); QgsRasterLayer * myLayer = new QgsRasterLayer( myUri.encodedUri(), myCoverage.identifier, "wcs", true ); if ( myLayer->isValid() ) { int myBandCount = myLayer->dataProvider()->bandCount(); myLog << "bandCount:" + QString::number( myBandCount ); if ( myBandCount > 0 ) { myLog << "srcType:" + QString::number( myLayer->dataProvider()->srcDataType( 1 ) ); QgsRasterBandStats myStats = myLayer->dataProvider()->bandStatistics( 1, QgsRasterBandStats::All, QgsRectangle(), myWidth * myHeight ); myLog << "min:" + QString::number( myStats.minimumValue ); myLog << "max:" + QString::number( myStats.maximumValue ); } QgsMapRenderer myMapRenderer; QList<QgsMapLayer *> myLayersList; myLayersList.append( myLayer ); QgsMapLayerRegistry::instance()->addMapLayers( myLayersList, false ); QMap<QString, QgsMapLayer*> myLayersMap = QgsMapLayerRegistry::instance()->mapLayers(); myMapRenderer.setLayerSet( myLayersMap.keys() ); myMapRenderer.setExtent( myLayer->extent() ); QImage myImage( myWidth, myHeight, QImage::Format_ARGB32_Premultiplied ); myImage.fill( 0 ); myMapRenderer.setOutputSize( QSize( myWidth, myHeight ), myImage.logicalDpiX() ); QPainter myPainter( &myImage ); myMapRenderer.render( &myPainter ); // Save rendered image QString myPngPath = myPath + ".png"; QgsDebugMsg( "myPngPath = " + myPngPath ); myImage.save( myPngPath ); // Verify data QSet<QString> myValues; // cannot be QSet<double> void *myData = myLayer->dataProvider()->readBlock( 1, myLayer->extent(), myWidth, myHeight ); if ( myData ) { int myType = myLayer->dataProvider()->dataType( 1 ); for ( int row = 0; row < myHeight; row++ ) { for ( int col = 0; col < myWidth; col++ ) { double value = myLayer->dataProvider()->readValue( myData, myType, row * myWidth + col ); QString valueStr = QString::number( value ); if ( !myValues.contains( valueStr ) ) myValues.insert( valueStr ); } } free( myData ); } QgsDebugMsg( QString( "%1 values" ).arg( myValues.size() ) ); myLog << QString( "valuesCount:%1" ).arg( myValues.size() ); // Verify image colors QSet<QRgb> myColors; for ( int row = 0; row < myHeight; row++ ) { for ( int col = 0; col < myWidth; col++ ) { QRgb color = myImage.pixel( col, row ); if ( !myColors.contains( color ) ) myColors.insert( color ); } } QgsDebugMsg( QString( "%1 colors" ).arg( myColors.size() ) ); myLog << QString( "colorsCount:%1" ).arg( myColors.size() ); } else { QgsDebugMsg( "Layer is not valid" ); myLog << "error:Layer is not valid"; } QFile myLogFile( myLogPath ); myLogFile.open( QIODevice::WriteOnly | QIODevice::Text ); QTextStream myStream( &myLogFile ); myStream << myLog.join( "\n" ); myLogFile.close(); QgsMapLayerRegistry::instance()->removeAllMapLayers(); }
static int evaluate(const QString &fileName, const QString &in_pwd, const QString &out_pwd, bool cumulative, ProFileGlobals *option, QMakeParser *parser, QMakeVfs *vfs, int level) { static QSet<QString> visited; if (visited.contains(fileName)) return 0; visited.insert(fileName); ProFileEvaluator visitor(option, parser, vfs, &evalHandler); #ifdef PROEVALUATOR_CUMULATIVE visitor.setCumulative(cumulative); #endif visitor.setOutputDir(out_pwd); ProFile *pro; if (!(pro = parser->parsedProFile(fileName))) { if (!QFile::exists(fileName)) { qCritical("Input file %s does not exist.", qPrintable(fileName)); return 3; } return 2; } if (!visitor.accept(pro)) { pro->deref(); return 2; } if (visitor.templateType() == ProFileEvaluator::TT_Subdirs) { QStringList subdirs = visitor.values(QLatin1String("SUBDIRS")); subdirs.removeDuplicates(); foreach (const QString &subDirVar, subdirs) { QString realDir; const QString subDirKey = subDirVar + QLatin1String(".subdir"); const QString subDirFileKey = subDirVar + QLatin1String(".file"); if (visitor.contains(subDirKey)) realDir = QFileInfo(visitor.value(subDirKey)).filePath(); else if (visitor.contains(subDirFileKey)) realDir = QFileInfo(visitor.value(subDirFileKey)).filePath(); else realDir = subDirVar; QFileInfo info(realDir); if (!info.isAbsolute()) info.setFile(in_pwd + QLatin1Char('/') + realDir); if (info.isDir()) info.setFile(QString::fromLatin1("%1/%2.pro").arg(info.filePath(), info.fileName())); if (!info.exists()) { qDebug() << "Could not find sub dir" << info.filePath(); continue; } QString inFile = QDir::cleanPath(info.absoluteFilePath()), inPwd = QDir::cleanPath(info.path()), outPwd = QDir::cleanPath(QDir(out_pwd).absoluteFilePath( QDir(in_pwd).relativeFilePath(info.path()))); int nlevel = level; if (nlevel >= 0) { printf("%sReading %s%s\n", QByteArray().fill(' ', nlevel).constData(), qPrintable(inFile), (inPwd == outPwd) ? "" : qPrintable(QString(QLatin1String(" [") + outPwd + QLatin1Char(']')))); fflush(stdout); nlevel++; } evaluate(inFile, inPwd, outPwd, cumulative, option, parser, vfs, nlevel); }
bool QDeclarativeImportsPrivate::importExtension(const QString &absoluteFilePath, const QString &uri, QDeclarativeImportDatabase *database, QDeclarativeDirComponents* components, QList<QDeclarativeError> *errors) { QFile file(absoluteFilePath); QString filecontent; if (!QDeclarative_isFileCaseCorrect(absoluteFilePath)) { if (errors) { QDeclarativeError error; error.setDescription(QDeclarativeImportDatabase::tr("cannot load module \"%1\": File name case mismatch for \"%2\"").arg(uri).arg(absoluteFilePath)); errors->prepend(error); } return false; } else if (file.open(QFile::ReadOnly)) { filecontent = QString::fromUtf8(file.readAll()); if (qmlImportTrace()) qDebug().nospace() << "QDeclarativeImports(" << qPrintable(base.toString()) << "::importExtension: " << "loaded " << absoluteFilePath; } else { if (errors) { QDeclarativeError error; error.setDescription(QDeclarativeImportDatabase::tr("module \"%1\" definition \"%2\" not readable").arg(uri).arg(absoluteFilePath)); errors->prepend(error); } return false; } QDir dir = QFileInfo(file).dir(); QUrl url = QUrl::fromLocalFile(absoluteFilePath); QDeclarativeDirParser qmldirParser; qmldirParser.setSource(filecontent); qmldirParser.setUrl(url); // propagate any errors reported by the parser back up to the typeloader. if (qmldirParser.parse()) { if (errors) { for (int i = 0; i < qmldirParser.errors().size(); ++i) { errors->prepend(qmldirParser.errors().at(i)); } } return false; } if (! qmlDirFilesForWhichPluginsHaveBeenLoaded.contains(absoluteFilePath)) { qmlDirFilesForWhichPluginsHaveBeenLoaded.insert(absoluteFilePath); foreach (const QDeclarativeDirParser::Plugin &plugin, qmldirParser.plugins()) { QString resolvedFilePath = database->resolvePlugin(dir, plugin.path, plugin.name); #if defined(QT_LIBINFIX) && defined(Q_OS_SYMBIAN) if (resolvedFilePath.isEmpty()) { // In case of libinfixed build, attempt to load libinfixed version, too. QString infixedPluginName = plugin.name + QLatin1String(QT_LIBINFIX); resolvedFilePath = database->resolvePlugin(dir, plugin.path, infixedPluginName); } #endif if (!resolvedFilePath.isEmpty()) { if (!database->importPlugin(resolvedFilePath, uri, errors)) { if (errors) { // XXX TODO: should we leave the import plugin error alone? // Here, we pop it off the top and coalesce it into this error's message. // The reason is that the lower level may add url and line/column numbering information. QDeclarativeError poppedError = errors->takeFirst(); QDeclarativeError error; error.setDescription(QDeclarativeImportDatabase::tr("plugin cannot be loaded for module \"%1\": %2").arg(uri).arg(poppedError.description())); error.setUrl(url); errors->prepend(error); } return false; } } else { if (errors) { QDeclarativeError error; error.setDescription(QDeclarativeImportDatabase::tr("module \"%1\" plugin \"%2\" not found").arg(uri).arg(plugin.name)); error.setUrl(url); errors->prepend(error); } return false; } } }