void Twitter::onDataReceived() { QNetworkReply* reply = qobject_cast<QNetworkReply*>(sender()); QString response; bool success = false; if (reply) { if (reply->error() == QNetworkReply::NoError) { int available = reply->bytesAvailable(); if (available > 0) { int bufSize = sizeof(char) * available + sizeof(char); QByteArray buffer(bufSize, 0); reply->read(buffer.data(), available); response = QString(buffer); success = true; } } else { response = QString("Error: ") + reply->errorString() + QString(" status:") + reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toString(); emit tweetParseComplete(false, "We can't connect to the internet"); } reply->deleteLater(); } if (success ) { if (response != "[]") { if (_refreshing) { _tweetList.clear(); emit itemsChanged(bb::cascades::DataModelChangeType::Init); } bb::data::JsonDataAccess jda; QVariant jsonva = jda.loadFromBuffer(response); QVariantMap map = jsonva.toMap(); QVariantList results = map.value("results").toList(); //okay let's get the news items int numTweets = 0; foreach (QVariant v, results) { QVariantMap map = v.toMap(); Tweet *tweet = new Tweet(); tweet->parse(v); QVariant q = QVariant::fromValue(tweet); _tweetList.append(q); //to go from a QVariant back to a Tweet* item: Tweet *Tweet = q.value<Tweet*>(); QVariantList path; path.append(_tweetList.indexOf(q)); emit itemAdded (path); numTweets++; } if (numTweets > 0) { emit tweetParseComplete(true, "Parsed successfully"); } else { if (_tweetList.count() == 0) { emit tweetParseComplete(false, "No Tweets yet"); } } } }
void QnxQtVersion::fromMap(const QVariantMap &map) { BaseQtVersion::fromMap(map); setSdpPath(QDir::fromNativeSeparators(map.value(QLatin1String(SDP_PATH_KEY)).toString())); }
void QgsAmsLegendFetcher::handleFinished() { // Parse result QJsonParseError err; QJsonDocument doc = QJsonDocument::fromJson( mQueryReply, &err ); if ( doc.isNull() ) { emit error( QStringLiteral( "Parsing error:" ).arg( err.errorString() ) ); } QVariantMap queryResults = doc.object().toVariantMap(); QgsDataSourceUri dataSource( mProvider->dataSourceUri() ); QVector< QPair<QString, QImage> > legendEntries; const QVariantList layersList = queryResults.value( QStringLiteral( "layers" ) ).toList(); for ( const QVariant &result : layersList ) { QVariantMap queryResultMap = result.toMap(); QString layerId = queryResultMap[QStringLiteral( "layerId" )].toString(); if ( layerId != dataSource.param( QStringLiteral( "layer" ) ) && !mProvider->subLayers().contains( layerId ) ) { continue; } const QVariantList legendSymbols = queryResultMap[QStringLiteral( "legend" )].toList(); for ( const QVariant &legendEntry : legendSymbols ) { QVariantMap legendEntryMap = legendEntry.toMap(); QString label = legendEntryMap[QStringLiteral( "label" )].toString(); if ( label.isEmpty() && legendSymbols.size() == 1 ) label = queryResultMap[QStringLiteral( "layerName" )].toString(); QByteArray imageData = QByteArray::fromBase64( legendEntryMap[QStringLiteral( "imageData" )].toByteArray() ); legendEntries.append( qMakePair( label, QImage::fromData( imageData ) ) ); } } if ( !legendEntries.isEmpty() ) { int padding = 5; int vpadding = 1; int imageSize = 20; int textWidth = 175; typedef QPair<QString, QImage> LegendEntry_t; QSize maxImageSize( 0, 0 ); for ( const LegendEntry_t &legendEntry : qgis::as_const( legendEntries ) ) { maxImageSize.setWidth( std::max( maxImageSize.width(), legendEntry.second.width() ) ); maxImageSize.setHeight( std::max( maxImageSize.height(), legendEntry.second.height() ) ); } double scaleFactor = maxImageSize.width() == 0 || maxImageSize.height() == 0 ? 1.0 : std::min( 1., std::min( double( imageSize ) / maxImageSize.width(), double( imageSize ) / maxImageSize.height() ) ); mLegendImage = QImage( imageSize + padding + textWidth, vpadding + legendEntries.size() * ( imageSize + vpadding ), QImage::Format_ARGB32 ); mLegendImage.fill( Qt::transparent ); QPainter painter( &mLegendImage ); int i = 0; for ( const LegendEntry_t &legendEntry : qgis::as_const( legendEntries ) ) { QImage symbol = legendEntry.second.scaled( legendEntry.second.width() * scaleFactor, legendEntry.second.height() * scaleFactor, Qt::KeepAspectRatio, Qt::SmoothTransformation ); painter.drawImage( 0, vpadding + i * ( imageSize + vpadding ) + ( imageSize - symbol.height() ), symbol ); painter.drawText( imageSize + padding, vpadding + i * ( imageSize + vpadding ), textWidth, imageSize, Qt::AlignLeft | Qt::AlignVCenter, legendEntry.first ); ++i; } } emit finish( mLegendImage ); }
bool CategoryServer::handleRequest(QHttpRequest *request, QHttpResponse *response) { const QStringList parts = request->path().split("/", QString::SkipEmptyParts); if ((parts.isEmpty()) || (parts.size() > 2) || (parts.first() != "categories")) { return false; } if (parts.size() == 1) { if (request->method() == QHttpRequest::HTTP_GET) { writeResponse(response, QHttpResponse::STATUS_OK, QtJson::Json::serialize(Qdl::getCategories())); return true; } if (request->method() == QHttpRequest::HTTP_POST) { const QVariantMap properties = QtJson::Json::parse(request->body()).toMap(); const QString name = properties.value("name").toString(); const QString path = properties.value("path").toString(); if ((name.isEmpty()) || (path.isEmpty()) || (!Qdl::addCategory(name, path))) { writeResponse(response, QHttpResponse::STATUS_BAD_REQUEST); } else { writeResponse(response, QHttpResponse::STATUS_CREATED); } return true; } writeResponse(response, QHttpResponse::STATUS_METHOD_NOT_ALLOWED); return true; } if (request->method() == QHttpRequest::HTTP_GET) { const QVariantMap category = Qdl::getCategory(parts.at(1)); if (category.isEmpty()) { return false; } writeResponse(response, QHttpResponse::STATUS_OK, QtJson::Json::serialize(category)); return true; } if (request->method() == QHttpRequest::HTTP_PUT) { const QVariantMap properties = QtJson::Json::parse(request->body()).toMap(); const QString path = properties.value("path").toString(); if ((path.isEmpty()) || (!Qdl::addCategory(parts.at(1), path))) { writeResponse(response, QHttpResponse::STATUS_BAD_REQUEST); } else { writeResponse(response, QHttpResponse::STATUS_OK); } return true; } if (request->method() == QHttpRequest::HTTP_DELETE) { const QVariantMap properties = QtJson::Json::parse(request->body()).toMap(); const QString name = properties.value("name").toString(); if ((name.isEmpty()) || (!Qdl::removeCategory(name))) { writeResponse(response, QHttpResponse::STATUS_BAD_REQUEST); } else { writeResponse(response, QHttpResponse::STATUS_OK); } return true; } writeResponse(response, QHttpResponse::STATUS_METHOD_NOT_ALLOWED); return true; }
WebKitPreviewAccount::WebKitPreviewAccount(const QVariantMap &data, qutim_sdk_0_3::Protocol *protocol) : Account(data.value(QLatin1String("UID")).toString(), protocol), m_data(data) { }
QgsFeatureSink *QgsProcessingUtils::createFeatureSink( QString &destination, QgsProcessingContext &context, const QgsFields &fields, QgsWkbTypes::Type geometryType, const QgsCoordinateReferenceSystem &crs, const QVariantMap &createOptions, QgsFeatureSink::SinkFlags sinkFlags ) { QVariantMap options = createOptions; if ( !options.contains( QStringLiteral( "fileEncoding" ) ) ) { // no destination encoding specified, use default options.insert( QStringLiteral( "fileEncoding" ), context.defaultEncoding().isEmpty() ? QStringLiteral( "system" ) : context.defaultEncoding() ); } if ( destination.isEmpty() || destination.startsWith( QLatin1String( "memory:" ) ) ) { // strip "memory:" from start of destination if ( destination.startsWith( QLatin1String( "memory:" ) ) ) destination = destination.mid( 7 ); if ( destination.isEmpty() ) destination = QStringLiteral( "output" ); // memory provider cannot be used with QgsVectorLayerImport - so create layer manually std::unique_ptr< QgsVectorLayer > layer( QgsMemoryProviderUtils::createMemoryLayer( destination, fields, geometryType, crs ) ); if ( !layer || !layer->isValid() ) { throw QgsProcessingException( QObject::tr( "Could not create memory layer" ) ); } // update destination to layer ID destination = layer->id(); // this is a factory, so we need to return a proxy std::unique_ptr< QgsProcessingFeatureSink > sink( new QgsProcessingFeatureSink( layer->dataProvider(), destination, context ) ); context.temporaryLayerStore()->addMapLayer( layer.release() ); return sink.release(); } else { QString providerKey; QString uri; QString layerName; QString format; bool useWriter = false; parseDestinationString( destination, providerKey, uri, layerName, format, options, useWriter ); QgsFields newFields = fields; if ( useWriter && providerKey == QLatin1String( "ogr" ) ) { // use QgsVectorFileWriter for OGR destinations instead of QgsVectorLayerImport, as that allows // us to use any OGR format which supports feature addition QString finalFileName; std::unique_ptr< QgsVectorFileWriter > writer = qgis::make_unique< QgsVectorFileWriter >( destination, options.value( QStringLiteral( "fileEncoding" ) ).toString(), newFields, geometryType, crs, format, QgsVectorFileWriter::defaultDatasetOptions( format ), QgsVectorFileWriter::defaultLayerOptions( format ), &finalFileName, QgsVectorFileWriter::NoSymbology, sinkFlags ); if ( writer->hasError() ) { throw QgsProcessingException( QObject::tr( "Could not create layer %1: %2" ).arg( destination, writer->errorMessage() ) ); } destination = finalFileName; return new QgsProcessingFeatureSink( writer.release(), destination, context, true ); } else { //create empty layer std::unique_ptr< QgsVectorLayerExporter > exporter( new QgsVectorLayerExporter( uri, providerKey, newFields, geometryType, crs, true, options, sinkFlags ) ); if ( exporter->errorCode() ) { throw QgsProcessingException( QObject::tr( "Could not create layer %1: %2" ).arg( destination, exporter->errorMessage() ) ); } // use destination string as layer name (eg "postgis:..." ) if ( !layerName.isEmpty() ) uri += QStringLiteral( "|layername=%1" ).arg( layerName ); std::unique_ptr< QgsVectorLayer > layer( new QgsVectorLayer( uri, destination, providerKey ) ); // update destination to layer ID destination = layer->id(); context.temporaryLayerStore()->addMapLayer( layer.release() ); return new QgsProcessingFeatureSink( exporter.release(), destination, context, true ); } } return nullptr; }
AssignmentClient::AssignmentClient(int &argc, char **argv) : QCoreApplication(argc, argv), _assignmentServerHostname(DEFAULT_ASSIGNMENT_SERVER_HOSTNAME), _localASPortSharedMem(NULL) { LogUtils::init(); setOrganizationName("High Fidelity"); setOrganizationDomain("highfidelity.io"); setApplicationName("assignment-client"); QSettings::setDefaultFormat(QSettings::IniFormat); // setup a shutdown event listener to handle SIGTERM or WM_CLOSE for us #ifdef _WIN32 installNativeEventFilter(&ShutdownEventListener::getInstance()); #else ShutdownEventListener::getInstance(); #endif // set the logging target to the the CHILD_TARGET_NAME LogHandler::getInstance().setTargetName(ASSIGNMENT_CLIENT_TARGET_NAME); const QVariantMap argumentVariantMap = HifiConfigVariantMap::mergeCLParametersWithJSONConfig(arguments()); const QString ASSIGNMENT_TYPE_OVERRIDE_OPTION = "t"; const QString ASSIGNMENT_POOL_OPTION = "pool"; const QString ASSIGNMENT_WALLET_DESTINATION_ID_OPTION = "wallet"; const QString CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION = "a"; const QString CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION = "p"; Assignment::Type requestAssignmentType = Assignment::AllTypes; // check for an assignment type passed on the command line or in the config if (argumentVariantMap.contains(ASSIGNMENT_TYPE_OVERRIDE_OPTION)) { requestAssignmentType = (Assignment::Type) argumentVariantMap.value(ASSIGNMENT_TYPE_OVERRIDE_OPTION).toInt(); } QString assignmentPool; // check for an assignment pool passed on the command line or in the config if (argumentVariantMap.contains(ASSIGNMENT_POOL_OPTION)) { assignmentPool = argumentVariantMap.value(ASSIGNMENT_POOL_OPTION).toString(); } // setup our _requestAssignment member variable from the passed arguments _requestAssignment = Assignment(Assignment::RequestCommand, requestAssignmentType, assignmentPool); // check for a wallet UUID on the command line or in the config // this would represent where the user running AC wants funds sent to if (argumentVariantMap.contains(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION)) { QUuid walletUUID = argumentVariantMap.value(ASSIGNMENT_WALLET_DESTINATION_ID_OPTION).toString(); qDebug() << "The destination wallet UUID for credits is" << uuidStringWithoutCurlyBraces(walletUUID); _requestAssignment.setWalletUUID(walletUUID); } // create a NodeList as an unassigned client NodeList* nodeList = NodeList::createInstance(NodeType::Unassigned); quint16 assignmentServerPort = DEFAULT_DOMAIN_SERVER_PORT; // check for an overriden assignment server hostname if (argumentVariantMap.contains(CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION)) { // change the hostname for our assignment server _assignmentServerHostname = argumentVariantMap.value(CUSTOM_ASSIGNMENT_SERVER_HOSTNAME_OPTION).toString(); } // check for an overriden assignment server port if (argumentVariantMap.contains(CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION)) { assignmentServerPort = argumentVariantMap.value(CUSTOM_ASSIGNMENT_SERVER_PORT_OPTION).toString().toUInt(); } _assignmentServerSocket = HifiSockAddr(_assignmentServerHostname, assignmentServerPort, true); nodeList->setAssignmentServerSocket(_assignmentServerSocket); qDebug() << "Assignment server socket is" << _assignmentServerSocket; // call a timer function every ASSIGNMENT_REQUEST_INTERVAL_MSECS to ask for assignment, if required qDebug() << "Waiting for assignment -" << _requestAssignment; QTimer* timer = new QTimer(this); connect(timer, SIGNAL(timeout()), SLOT(sendAssignmentRequest())); timer->start(ASSIGNMENT_REQUEST_INTERVAL_MSECS); // connect our readPendingDatagrams method to the readyRead() signal of the socket connect(&nodeList->getNodeSocket(), &QUdpSocket::readyRead, this, &AssignmentClient::readPendingDatagrams); // connections to AccountManager for authentication connect(&AccountManager::getInstance(), &AccountManager::authRequired, this, &AssignmentClient::handleAuthenticationRequest); // Create Singleton objects on main thread NetworkAccessManager::getInstance(); SoundCache::getInstance(); }
void ScriptEngine::resolve( const Tomahawk::query_ptr& query ) { qDebug() << Q_FUNC_INFO << query->toString(); QString eval = QString( "resolve( '%1', '%2', '%3', '%4' );" ) .arg( query->id().replace( "'", "\\'" ) ) .arg( query->artist().replace( "'", "\\'" ) ) .arg( query->album().replace( "'", "\\'" ) ) .arg( query->track().replace( "'", "\\'" ) ); QList< Tomahawk::result_ptr > results; QVariantMap m = mainFrame()->evaluateJavaScript( eval ).toMap(); qDebug() << "JavaScript Result:" << m; const QString qid = query->id(); const QVariantList reslist = m.value( "results" ).toList(); foreach( const QVariant& rv, reslist ) { QVariantMap m = rv.toMap(); qDebug() << "RES" << m; Tomahawk::result_ptr rp( new Tomahawk::Result() ); Tomahawk::artist_ptr ap = Tomahawk::Artist::get( 0, m.value( "artist" ).toString() ); rp->setArtist( ap ); rp->setAlbum( Tomahawk::Album::get( 0, m.value( "album" ).toString(), ap ) ); rp->setTrack( m.value( "track" ).toString() ); rp->setBitrate( m.value( "bitrate" ).toUInt() ); rp->setUrl( m.value( "url" ).toString() ); rp->setSize( m.value( "size" ).toUInt() ); rp->setScore( m.value( "score" ).toFloat() * ( (float)m_parent->weight() / 100.0 ) ); rp->setRID( uuid() ); rp->setFriendlySource( m_parent->name() ); if ( m.contains( "year" ) ) { QVariantMap attr; attr[ "releaseyear" ] = m.value( "year" ); rp->setAttributes( attr ); } rp->setDuration( m.value( "duration", 0 ).toUInt() ); if ( rp->duration() <= 0 && m.contains( "durationString" ) ) { QTime time = QTime::fromString( m.value( "durationString" ).toString(), "hh:mm:ss" ); rp->setDuration( time.secsTo( QTime( 0, 0 ) ) * -1 ); } rp->setMimetype( m.value( "mimetype" ).toString() ); if ( rp->mimetype().isEmpty() ) { rp->setMimetype( TomahawkUtils::extensionToMimetype( m.value( "extension" ).toString() ) ); Q_ASSERT( !rp->mimetype().isEmpty() ); } results << rp; }
void BlackBerryDeviceConfiguration::fromMap(const QVariantMap &map) { RemoteLinux::LinuxDevice::fromMap(map); m_debugToken = map.value(QLatin1String(Constants::QNX_DEBUG_TOKEN_KEY)).toString(); }
void VLongPollClient::onDataReceived() { QNetworkReply *reply = qobject_cast<QNetworkReply *>(sender()); reply->deleteLater(); QByteArray rawData = reply->readAll(); debug() << Q_FUNC_INFO << rawData; QVariantMap data = Json::parse(rawData).toMap(); if (data.contains("failed")) { requestServer(); return; } else if (data.isEmpty() || reply->error() != QNetworkReply::NoError) { if (m_connection->connectionState() == Connected) QTimer::singleShot(1000, this, SLOT(requestServer())); return; } QVariantList updates = data.value("updates").toList(); for (int i = 0; i < updates.size(); i++) { QVariantList update = updates.at(i).toList(); int updateType = update.value(0, -1).toInt(); switch (updateType) { case MessageAdded: { MessageFlags flags(update.value(2).toInt()); if (flags & MessageOutbox) continue; QString id = update.value(3).toString(); QString messageId = update.value(1).toString(); QString subject = update.value(5).toString(); QString text = update.value(6).toString(); VContact *contact = m_connection->account()->getContact(id, true); qutim_sdk_0_3::Message message; message.setChatUnit(contact); message.setProperty("subject", subject); message.setText(unescape(text)); message.setProperty("mid",messageId); //message.setProperty("html",text); message.setTime(QDateTime::currentDateTime()); message.setIncoming(true); ChatSession *s = ChatLayer::get(contact, true); s->appendMessage(message); connect(s,SIGNAL(unreadChanged(qutim_sdk_0_3::MessageList)),SLOT(onUnreadChanged(qutim_sdk_0_3::MessageList))); m_unread_mess[s].append(message); contact->setChatState(ChatStateActive); break; } case UserOnline: case UserOffline: { // WTF? Why VKontakte sends minus as first char of id? QString id = update.value(1).toString().mid(1); VContact *contact = m_connection->account()->getContact(id, false); if (contact) contact->setOnline(updateType == UserOnline); break; } } } if (m_connection->connectionState() == Connected) requestData(data.value("ts").toString()); }
void RemoteComponent::handleCommand(QHttpRequest* request, QHttpResponse* response) { QVariantMap queryMap = QueryToMap(request->url()); QVariantMap headerMap = HeaderToMap(request->headers()); QString identifier = headerMap["x-plex-client-identifier"].toString(); response->addHeader("Access-Control-Allow-Origin", "*"); response->addHeader("X-Plex-Client-Identifier", SettingsComponent::Get().value(SETTINGS_SECTION_WEBCLIENT, "clientID").toByteArray()); // handle CORS requests here if ((request->method() == qhttp::EHTTP_OPTIONS) && headerMap.contains("access-control-request-method")) { response->addHeader("Content-Type", "text/plain"); response->addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD"); response->addHeader("Access-Control-Max-Age", "1209600"); response->addHeader("Connection", "close"); if (headerMap.contains("access-control-request-headers")) { response->addHeader("Access-Control-Allow-Headers", headerMap.value("access-control-request-headers").toByteArray()); } response->setStatusCode(qhttp::ESTATUS_OK); response->end(); return; } // we want to handle the subscription events in the host // since we are going to handle the updating later. // if (request->url().path() == "/player/timeline/subscribe") { handleSubscription(request, response, false); return; } else if (request->url().path() == "/player/timeline/unsubscribe") { subscriberRemove(request->headers()["x-plex-client-identifier"]); response->setStatusCode(qhttp::ESTATUS_OK); response->end(); return; } else if ((request->url().path() == "/player/timeline/poll")) { QMutexLocker lk(&m_subscriberLock); if (!m_subscriberMap.contains(identifier)) { lk.unlock(); handleSubscription(request, response, true); lk.relock(); } RemotePollSubscriber *subscriber = (RemotePollSubscriber *)m_subscriberMap[identifier]; if (subscriber) { subscriber->reSubscribe(); subscriber->setHTTPResponse(response); // if we don't have to wait, just ship the update right away // otherwise, this will wait until next update if (! (queryMap.contains("wait") && (queryMap["wait"].toList()[0].toInt() == 1))) { subscriber->sendUpdate(); } } return; } // handle commandID if (!headerMap.contains("x-plex-client-identifier") || !queryMap.contains("commandID")) { QLOG_WARN() << "Can't find a X-Plex-Client-Identifier header"; response->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE); response->end(); return; } quint64 commandId = 0; { QMutexLocker lk(&m_responseLock); commandId = ++m_commandId; m_responseMap[commandId] = response; connect(response, &QHttpResponse::done, this, &RemoteComponent::responseDone); } { QMutexLocker lk(&m_subscriberLock); if (!m_subscriberMap.contains(identifier)) { QLOG_WARN() << "Failed to lock up subscriber" << identifier; response->setStatusCode(qhttp::ESTATUS_NOT_ACCEPTABLE); response->end(); return; } RemoteSubscriber* subscriber = m_subscriberMap[identifier]; subscriber->setCommandId(m_commandId, queryMap["commandID"].toList()[0].toInt()); } QVariantMap arg = { { "method", request->methodString() }, { "headers", headerMap }, { "path", request->url().path() }, { "query", queryMap }, { "commandID", m_commandId} }; emit commandReceived(arg); }
void IRunConfigurationAspect::fromMap(const QVariantMap &map) { m_projectSettings->fromMap(map); m_useGlobalSettings = map.value(m_id.toString() + QLatin1String(".UseGlobalSettings"), true).toBool(); }
void SoundCloudSearchPlugin::fetchMore(const QVariantMap ¶ms) { request()->get(params.value("path").toString()); }
static bool commentLessThan(const QVariantMap &a, const QVariantMap &b) { return a.value("cid").toInt() < b.value("cid").toInt(); }
void IosSimulator::fromMap(const QVariantMap &map) { IDevice::fromMap(map); m_simulatorPath = Utils::FileName::fromString(map.value(QLatin1String(SIMULATOR_PATH_KEY)) .toString()); }
pPartition createPartition( struct udev_device* device ) { struct udev_list_entry* entries = udev_device_get_properties_list_entry( device ); struct udev_list_entry* entry = 0; pPartition partition; QVariantMap properties; udev_list_entry_foreach( entry, entries ) { const QString name = udev_list_entry_get_name( entry ); const QString value = QString::fromLocal8Bit( udev_device_get_property_value( device, name.toLocal8Bit().constData() ) ); properties[ name ] = value; } if ( properties.contains( "UDISKS_PARTITION_TYPE" ) ) { properties[ "UDISKS_PARTITION_TYPE" ] = properties[ "UDISKS_PARTITION_TYPE" ].toString().toLongLong( 0, 16 ); } const QString devName = QFileInfo( properties[ "DEVNAME" ].toString() ).fileName(); QDBusMessage question = QDBusMessage::createMethodCall( "org.freedesktop.UDisks", QString( "/org/freedesktop/UDisks/devices/%1" ).arg( devName ), "org.freedesktop.DBus.Properties", "Get" ); question << "org.freedesktop.UDisks.Device" << "DeviceMountPaths"; QDBusMessage answer = QDBusConnection::systemBus().call( question, QDBus::Block, 1 ); QStringList mountPoints; foreach ( const QVariant& variant, answer.arguments() ) { const QStringList values = variant.value<QDBusVariant>().variant().toStringList(); if ( !values.isEmpty() ) { mountPoints << values; } } if ( pPartition::isWBFSPartition( properties[ "DEVNAME" ].toString() ) ) { properties[ "UDISKS_PARTITION_TYPE" ] = 0x25; properties[ "ID_FS_TYPE" ] = pPartition::fileSystemIdToString( 0x25 ); } qint64 total = properties.value( "UDISKS_PARTITION_SIZE", -1 ).toLongLong(); qint64 free = -1; if ( !mountPoints.isEmpty() ) { struct statfs stats; if ( statfs( qPrintable( mountPoints.first() ), &stats ) == 0 ) { /*const qint64 total = stats.f_blocks *stats.f_bsize; partition.used = total -( stats.f_bfree *stats.f_bsize ); partition.free = partition.total -partition.used;*/ total = stats.f_blocks *stats.f_bsize; free = stats.f_bfree *stats.f_bsize; } properties[ "UDISKS_PARTITION_MOUNT_POINTS" ] = mountPoints; } properties[ "REMOVABLE" ] = "0"; // Check removable attr struct udev_device* parent = 0; if ( properties[ "DEVTYPE" ] == "partition" ) { parent = udev_device_get_parent( device ); } else if ( properties[ "DEVTYPE" ] == "disk" ) { parent = device; // disk without partitions } if ( parent != 0 ) { const char* value = udev_device_get_sysattr_value( parent, "removable" ); if ( value ) { properties[ "REMOVABLE" ] = QString::fromLocal8Bit( value ); } } partition.setProperties( properties ); partition.updateSizes( total, free ); return partition; }
TrackInfo MprisPlayer::convertInfo(const QVariantMap &map) { TrackInfo info; bool ok; if (m_version == 1) { info.album = map.value("album").toString(); info.artist = map.value("artist").toString(); info.title = map.value("title").toString(); info.location = QUrl::fromEncoded(map.value("location").toString().toLatin1()); info.trackNumber = map.value("tracknumber").toInt(&ok); if (!ok) info.trackNumber = -1; info.time = map.value("time").toLongLong(&ok); if (!ok) info.time = -1; } else if (m_version == 2) { info.album = map.value("xesam:album").toString(); info.artist = map.value("xesam:artist").toString(); info.title = map.value("xesam:title").toString(); info.location = QUrl::fromEncoded(map.value("xesam:url").toString().toLatin1()); info.trackNumber = map.value("xesam:trackNumber").toInt(&ok); if (!ok) info.trackNumber = -1; info.time = map.value("mpris:length").toLongLong(&ok) / 1000000; if (!ok) info.time = -1; } return info; }
void AvatarData::setPositionFromVariantMap(QVariantMap positionMap) { _position = glm::vec3(positionMap.value("x").toFloat(), positionMap.value("y").toFloat(), positionMap.value("z").toFloat()); }
Satellite::Satellite(const QString& identifier, const QVariantMap& map) : initialized(false), visible(true), newlyAdded(false), orbitValid(false), hintColor(0.0,0.0,0.0), lastUpdated(), pSatWrapper(NULL) { // return initialized if the mandatory fields are not present if (identifier.isEmpty()) return; if (!map.contains("name") || !map.contains("tle1") || !map.contains("tle2")) return; font.setPixelSize(16); id = identifier; name = map.value("name").toString(); if (name.isEmpty()) return; if (map.contains("description")) description = map.value("description").toString(); if (map.contains("visible")) visible = map.value("visible").toBool(); if (map.contains("orbitVisible")) orbitVisible = map.value("orbitVisible").toBool(); if (map.contains("hintColor")) { if (map.value("hintColor").toList().count() == 3) { hintColor[0] = map.value("hintColor").toList().at(0).toDouble(); hintColor[1] = map.value("hintColor").toList().at(1).toDouble(); hintColor[2] = map.value("hintColor").toList().at(2).toDouble(); } } if (map.contains("orbitColor")) { if (map.value("orbitColor").toList().count() == 3) { orbitColorNormal[0] = map.value("orbitColor").toList().at(0).toDouble(); orbitColorNormal[1] = map.value("orbitColor").toList().at(1).toDouble(); orbitColorNormal[2] = map.value("orbitColor").toList().at(2).toDouble(); } } else { orbitColorNormal = hintColor; } // Set the night color of orbit lines to red with the // intensity of the average of the RGB for the day color. float orbitColorBrightness = (orbitColorNormal[0] + orbitColorNormal[1] + orbitColorNormal[2])/3; orbitColorNight[0] = orbitColorBrightness; orbitColorNight[1] = 0; orbitColorNight[2] = 0; if (StelApp::getInstance().getVisionModeNight()) orbitColor = &orbitColorNight; else orbitColor = &orbitColorNormal; if (map.contains("comms")) { foreach(const QVariant &comm, map.value("comms").toList()) { QVariantMap commMap = comm.toMap(); commLink c; if (commMap.contains("frequency")) c.frequency = commMap.value("frequency").toDouble(); if (commMap.contains("modulation")) c.modulation = commMap.value("modulation").toString(); if (commMap.contains("description")) c.description = commMap.value("description").toString(); comms.append(c); } }
void AvatarData::setHandPositionFromVariantMap(QVariantMap handPositionMap) { _handPosition = glm::vec3(handPositionMap.value("x").toFloat(), handPositionMap.value("y").toFloat(), handPositionMap.value("z").toFloat()); }
Galaxy::Galaxy(const QVariantMap& map) : initialized(false), visible(true) { // return initialized if the mandatory fields are not present if (!map.contains("designation")) return; if (map.contains("visible")) visible = map.value("visible").toBool(); designation = map.value("designation").toString(); parallax = map.value("parallax").toFloat(); period = map.value("period").toDouble(); bperiod = map.value("bperiod").toDouble(); frequency = map.value("frequency").toDouble(); pfrequency = map.value("pfrequency").toDouble(); pderivative = map.value("pderivative").toDouble(); dmeasure = map.value("dmeasure").toDouble(); eccentricity = map.value("eccentricity").toDouble(); RA = StelUtils::getDecAngle(map.value("RA").toString()); DE = StelUtils::getDecAngle(map.value("DE").toString()); w50 = map.value("w50").toFloat(); s400 = map.value("s400").toFloat(); s600 = map.value("s600").toFloat(); s1400 = map.value("s1400").toFloat(); distance = map.value("distance").toFloat(); notes = map.value("notes").toString(); // If barycentric period not set then calculate it if (period==0 && frequency>0) { period = 1/frequency; } // If barycentric period derivative not set then calculate it if (pderivative==0) { pderivative = getP1(period, pfrequency); } initialized = true; }
void BLocalDocumentDriver::restoreState(const QByteArray &state) { QVariantMap m = BeQt::deserialize(state).toMap(); d_func()->fileDialogState = m.value("file_dialog_state").toByteArray(); d_func()->fileDialogGeometry = m.value("file_dialog_geometry").toByteArray(); }
bool GenericBuildConfiguration::fromMap(const QVariantMap &map) { m_buildDirectory = map.value(QLatin1String(BUILD_DIRECTORY_KEY), target()->project()->projectDirectory()).toString(); return BuildConfiguration::fromMap(map); }
void QmlJSOutlineWidget::restoreSettings(const QVariantMap &map) { bool showBindings = map.value(QString::fromLatin1("QmlJSOutline.ShowBindings"), true).toBool(); m_showBindingsAction->setChecked(showBindings); }
bool BTRecvQueryDialogWidget::constructDialog(const QVariantMap ¶meters) { mLoader = new HbDocumentLoader(); bool ok = false; mLoader->load(DOCML_BT_RECV_QUERY_DIALOG, &ok); if(ok) { mDialog = qobject_cast<HbDialog*>(mLoader->findWidget("receiveAuthorizationDialog")); mHeading = qobject_cast<HbLabel*>(mLoader->findWidget("receiveAuthorizationHeading")); mDeviceName = qobject_cast<HbLabel*>(mLoader->findWidget("deviceName")); mDeviceType = qobject_cast<HbLabel*>(mLoader->findWidget("deviceType")); mDeviceIcon = qobject_cast<HbLabel*>(mLoader->findWidget("deviceIcon")); int classOfDevice = parameters.value(QString::number(TBluetoothDeviceDialog::EDeviceClass)).toDouble(); HbIcon icon = getBadgedDeviceTypeIcon(classOfDevice); mDeviceIcon->setIcon(icon); mDeviceName->setPlainText(parameters.value(QString::number(TBluetoothDeviceDialog::EDeviceName)).toString()); mDeviceType->setPlainText(getDeviceTypeString(classOfDevice)); mYesAction = qobject_cast<HbAction*>(mLoader->findObject("yesAction")); mNoAction = qobject_cast<HbAction*>(mLoader->findObject("noAction")); mAuthorizeUser = qobject_cast<HbCheckBox*>(mLoader->findWidget("authorizeUser")); int dialogType = parameters.value(QString::number(TBluetoothDialogParams::EDialogTitle)).toInt(); switch(dialogType) { case TBluetoothDialogParams::EReceive: { mHeading->setPlainText(hbTrId("txt_bt_title_receive_messages_from")); }break; case TBluetoothDialogParams::EReceiveFromPairedDevice: { mHeading->setPlainText(hbTrId("txt_bt_title_receive_messages_from_paired_device")); mAuthorizeUser->setCheckState(Qt::Checked); }break; case TBluetoothDialogParams::EConnect: { mHeading->setPlainText(hbTrId("txt_bt_title_connect_to")); mAuthorizeUser->setCheckState(Qt::Checked); }break; case TBluetoothDialogParams::EPairingRequest: mHeading->setPlainText(hbTrId("txt_bt_title_pair_with")); mAuthorizeUser->setCheckState(Qt::Checked); break; default: break; } mDialog->setHeadingWidget(mHeading); } mDialog->setBackgroundFaded(false); mDialog->setDismissPolicy(HbPopup::NoDismiss); mDialog->setTimeout(HbPopup::NoTimeout); connect(mYesAction, SIGNAL(triggered()), this, SLOT(yesClicked())); connect(mNoAction, SIGNAL(triggered()), this, SLOT(noClicked())); connect(mAuthorizeUser, SIGNAL(clicked(bool)), this, SLOT(checkBoxStateChanged(bool))); return true; }
/** * FASTQ format specification: http://maq.sourceforge.net/fastq.shtml */ static void load(IOAdapter* io, const U2DbiRef& dbiRef, const QVariantMap& hints, QList<GObject*>& objects, U2OpStatus& os, int gapSize, int predictedSize, QString& writeLockReason, QMap<QString, QString>& skippedLines) { DbiOperationsBlock opBlock(dbiRef, os); CHECK_OP(os, ); Q_UNUSED(opBlock); writeLockReason.clear(); bool merge = gapSize!=-1; QByteArray sequence; QByteArray qualityScores; QStringList headers; QSet<QString> uniqueNames; QVector<U2Region> mergedMapping; QByteArray gapSequence((merge ? gapSize : 0), 0); sequence.reserve(predictedSize); qualityScores.reserve(predictedSize); // for lower case annotations GObjectReference sequenceRef; qint64 sequenceStart = 0; U2SequenceImporter seqImporter(hints, true); const QString folder = hints.value(DocumentFormat::DBI_FOLDER_HINT, U2ObjectDbi::ROOT_FOLDER).toString(); int seqNumber = 0; int progressUpNum = 0; const int objectsCountLimit = hints.contains(DocumentReadingMode_MaxObjectsInDoc) ? hints[DocumentReadingMode_MaxObjectsInDoc].toInt() : -1; const bool settingsMakeUniqueName = !hints.value(DocumentReadingMode_DontMakeUniqueNames, false).toBool(); while (!os.isCoR()) { U2OpStatus2Log warningOs; //read header QString sequenceName = readSequenceName(warningOs, io, '@'); // check for eof while trying to read another FASTQ block if (io->isEof()) { if (io->hasError()) { os.setError(io->errorString()); } break; } if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ continue; } if(sequenceName.isEmpty()){ sequenceName = "Sequence"; } if ((merge == false) || (seqNumber == 0)) { QString objName = sequenceName; if (settingsMakeUniqueName) { objName = (merge) ? "Sequence" : TextUtils::variate(sequenceName, "_", uniqueNames); objName.squeeze(); uniqueNames.insert(objName); } seqImporter.startSequence(warningOs, dbiRef, folder, objName, false); if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ U2OpStatusImpl seqOs; seqImporter.finalizeSequenceAndValidate(seqOs); continue; } } //read sequence if (merge && sequence.length() > 0) { seqImporter.addDefaultSymbolsBlock(gapSize, warningOs); sequenceStart += sequence.length(); sequenceStart+=gapSize; if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ U2OpStatusImpl seqOs; seqImporter.finalizeSequenceAndValidate(seqOs); continue; } } sequence.clear(); readSequence(warningOs, io, sequence); if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ U2OpStatusImpl seqOs; seqImporter.finalizeSequenceAndValidate(seqOs); continue; } MemoryLocker lSequence(os, qCeil(sequence.size()/(1000*1000))); CHECK_OP_BREAK(os); Q_UNUSED(lSequence); seqImporter.addBlock(sequence.data(),sequence.length(), warningOs); if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ U2OpStatusImpl seqOs; seqImporter.finalizeSequenceAndValidate(seqOs); continue; } QString qualSequenceName = readSequenceName(warningOs, io, '+'); if (!qualSequenceName.isEmpty()) { if (sequenceName != qualSequenceName){ warningOs.setError(U2::FastqFormat::tr("Sequence name differs from quality scores name: %1 and %2").arg(sequenceName).arg(qualSequenceName)); } if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ U2OpStatusImpl seqOs; seqImporter.finalizeSequenceAndValidate(seqOs); continue; } } // read qualities qualityScores.clear(); readQuality(warningOs, io, qualityScores, sequence.size()); if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ U2OpStatusImpl seqOs; seqImporter.finalizeSequenceAndValidate(seqOs); continue; } if(sequence.length() != qualityScores.length()){ warningOs.setError(U2::FastqFormat::tr("Bad quality scores: inconsistent size.")); } if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ U2OpStatusImpl seqOs; seqImporter.finalizeSequenceAndValidate(seqOs); continue; } seqNumber++; progressUpNum++; if (merge) { headers.append(sequenceName); mergedMapping.append(U2Region(sequenceStart, sequence.length() )); } else { if (objectsCountLimit > 0 && objects.size() >= objectsCountLimit) { os.setError(FastqFormat::tr("File \"%1\" contains too many sequences to be displayed. " "However, you can process these data using instruments from the menu <i>Tools -> NGS data analysis</i> " "or pipelines built with Workflow Designer.") .arg(io->getURL().getURLString())); break; } U2Sequence u2seq = seqImporter.finalizeSequenceAndValidate(warningOs); if(errorLoggingBreak(warningOs, skippedLines, sequenceName)){ continue; } sequenceRef = GObjectReference(io->getURL().getURLString(), u2seq.visualName, GObjectTypes::SEQUENCE, U2EntityRef(dbiRef, u2seq.id)); U2SequenceObject* seqObj = new U2SequenceObject(u2seq.visualName, U2EntityRef(dbiRef, u2seq.id)); CHECK_EXT_BREAK(seqObj != NULL, os.setError("U2SequenceObject is NULL")); seqObj->setQuality(DNAQuality(qualityScores)); objects << seqObj; U1AnnotationUtils::addAnnotations(objects, seqImporter.getCaseAnnotations(), sequenceRef, NULL, hints); } if (PROGRESS_UPDATE_STEP == progressUpNum) { progressUpNum = 0; os.setProgress(io->getProgress()); } } CHECK_OP_EXT(os, qDeleteAll(objects); objects.clear(), ); bool emptyObjects = objects.isEmpty(); CHECK_EXT(!emptyObjects || merge, os.setError(Document::tr("Document is empty.")), ); SAFE_POINT(headers.size() == mergedMapping.size(), "headers <-> regions mapping failed!", ); if (!merge) { return; } U2Sequence u2seq = seqImporter.finalizeSequenceAndValidate(os); CHECK_OP(os,); sequenceRef = GObjectReference(io->getURL().getURLString(), u2seq.visualName, GObjectTypes::SEQUENCE, U2EntityRef(dbiRef, u2seq.id)); U1AnnotationUtils::addAnnotations(objects, seqImporter.getCaseAnnotations(), sequenceRef, NULL, hints); objects << new U2SequenceObject(u2seq.visualName, U2EntityRef(dbiRef, u2seq.id)); objects << DocumentFormatUtils::addAnnotationsForMergedU2Sequence(sequenceRef, dbiRef, headers, mergedMapping, hints); if (headers.size() > 1) { writeLockReason = QObject::tr("Document sequences were merged"); } }
void Updater::onNetworkReply(QNetworkReply *reply) { if (reply != m_reply) { // Reply not for the latest request. Ignore it. reply->deleteLater(); setBusy(false); return; } m_reply = NULL; if (reply->error() == QNetworkReply::OperationCanceledError) { // Operation was canceled by us, ignore this error. reply->deleteLater(); setBusy(false); return; } if (reply->error() != QNetworkReply::NoError) { qWarning() << reply->errorString(); emit error(reply->errorString()); reply->deleteLater(); setBusy(false); return; } const QVariantList releases = parseJson(reply->readAll()); reply->deleteLater(); if (releases.isEmpty()) { setBusy(false); return; } int k = 0; QVariantMap release = releases.at(0).toMap(); while (release.value("prerelease").toBool() || release.value("draft").toBool() || (release.value("tag_name").toString().contains("-") && !release.value("tag_name").toString().endsWith("-" + m_variant))) { release = releases.at(++k).toMap(); } const QString name = release.value("tag_name").toString(); const QString title = release.value("name").toString(); const QString changeLog = release.value("body").toString(); const int version = parseVersion(name); if (version < 0) { emit error(tr("Couldn't parse release version")); setBusy(false); return; } m_numericLatestVersion = parseVersion(name); if (m_latestRelease) delete m_latestRelease; m_latestRelease = new Release(name, title, changeLog, this); emit latestReleaseChanged(); if (!m_latestReleaseValid) { m_latestReleaseValid = true; emit latestReleaseValidChanged(); } setUpdateAvailable(m_numericCurrentVersion < m_numericLatestVersion); setBusy(false); }
bool StarMgr::checkAndLoadCatalog(const QVariantMap& catDesc) { const bool checked = catDesc.value("checked").toBool(); QString catalogFileName = catDesc.value("fileName").toString(); // See if it is an absolute path, else prepend default path if (!(StelFileMgr::isAbsolute(catalogFileName))) catalogFileName = "stars/default/"+catalogFileName; QString catalogFilePath = StelFileMgr::findFile(catalogFileName); if (catalogFilePath.isEmpty()) { // The file is supposed to be checked, but we can't find it if (checked) { qWarning() << QString("Warning: could not find star catalog %1").arg(QDir::toNativeSeparators(catalogFileName)); setCheckFlag(catDesc.value("id").toString(), false); } return false; } // Possibly fixes crash on Vista if (!StelFileMgr::isReadable(catalogFilePath)) { qWarning() << QString("Warning: User does not have permissions to read catalog %1").arg(QDir::toNativeSeparators(catalogFilePath)); return false; } if (!checked) { // The file is not checked but we found it, maybe from a previous download/version qWarning() << "Found file " << QDir::toNativeSeparators(catalogFilePath) << ", checking md5sum.."; QFile fic(catalogFilePath); if(fic.open(QIODevice::ReadOnly | QIODevice::Unbuffered)) { // Compute the MD5 sum QCryptographicHash md5Hash(QCryptographicHash::Md5); const qint64 cat_sz = fic.size(); qint64 maxStarBufMd5 = qMin(cat_sz, 9223372036854775807LL); uchar *cat = maxStarBufMd5 ? fic.map(0, maxStarBufMd5) : NULL; if (!cat) { // The OS was not able to map the file, revert to slower not mmap based method static const qint64 maxStarBufMd5 = 1024*1024*8; char* mmd5buf = (char*)malloc(maxStarBufMd5); while (!fic.atEnd()) { qint64 sz = fic.read(mmd5buf, maxStarBufMd5); md5Hash.addData(mmd5buf, sz); } free(mmd5buf); } else { md5Hash.addData((const char*)cat, cat_sz); fic.unmap(cat); } fic.close(); if (md5Hash.result().toHex()!=catDesc.value("checksum").toByteArray()) { qWarning() << "Error: File " << QDir::toNativeSeparators(catalogFileName) << " is corrupt, MD5 mismatch! Found " << md5Hash.result().toHex() << " expected " << catDesc.value("checksum").toByteArray(); fic.remove(); return false; } qWarning() << "MD5 sum correct!"; setCheckFlag(catDesc.value("id").toString(), true); } } ZoneArray* z = ZoneArray::create(catalogFilePath, true); if (z) { if (z->level<gridLevels.size()) { qWarning() << QDir::toNativeSeparators(catalogFileName) << ", " << z->level << ": duplicate level"; delete z; return true; } Q_ASSERT(z->level==maxGeodesicGridLevel+1); Q_ASSERT(z->level==gridLevels.size()); ++maxGeodesicGridLevel; gridLevels.append(z); } return true; }
QByteArray ActionHandler::getActionData(const QByteArray actionId, const QString &format) const { const QVariantMap dataMap = m_actionData.value(actionId); return format == "?" ? QStringList(dataMap.keys()).join("\n").toUtf8() + '\n' : dataMap.value(format).toByteArray(); }
QString ToolChainFactory::idFromMap(const QVariantMap &data) { return data.value(QLatin1String(ID_KEY)).toString(); }