Exemplo n.º 1
0
//when getBusStopMessage(const QString&) download finishes
void ArrivalsLogic::onBusStopMessageReceived() {
    QList<QJsonDocument> document = makeDocument(reply_busStopMessage);
    if (document.empty()) { return; } //nothing to do

    QJsonArray versionArray = document.begin()->array();
    if (versionArray.begin() + 2 < versionArray.end() ) {
        double serverTime = (*(versionArray.begin() + 2 )).toDouble();
        QMultiMap<int,QString> messages;
        for (QList<QJsonDocument>::const_iterator iter = document.begin() + 1; iter < document.end(); ++iter) {
            if (iter->array().begin() + 4 < iter->array().end()) {
                int priority = (*(iter->array().begin() + 1)).toDouble();
                QString text = (*(iter->array().begin() + 2)).toString();
                double startTime = (*(iter->array().begin() + 3)).toDouble();
                double expireTime = (*(iter->array().begin() + 4)).toDouble();
                if (startTime <= serverTime && expireTime >= serverTime) {
                    messages.insert(priority, text);
                }
            }
            else {
                qDebug() << "The array doesn't contain 4 elements.";
                break;
            }
        }
        fillCurrentStopMessages(messages);
    }
    else return;
}
Exemplo n.º 2
0
bool Parser::parseSearchResults(QByteArray &data, Trains &trainsContainer, QString &error)
{
    QDateTime datetime;

    CreateJsonFileForTest(data,"test_SearchReply.json");


    QJsonDocument responce;
    responce = QJsonDocument::fromJson(data);
    if (responce.isObject()) {
        QJsonObject jsonobject = responce.object();

         QJsonArray jsonTrains = jsonobject["value"].toArray();
         QJsonObject jsonTrain;
         for(auto it = jsonTrains.begin();it != jsonTrains.end();++it)
         {
             jsonTrain = it->toObject();
             QString trainNumber = jsonTrain["num"].toString();
             Train train(trainNumber);
             train.travelTime = jsonTrain["travel_time"].toString();

             datetime.setTime_t((jsonTrain["from"].toObject())["date"].toInt());
             train.dateDeparture = datetime;
             datetime.setTime_t((jsonTrain["till"].toObject())["date"].toInt());
             train.dateArrival = datetime;

             train.stationDeparture = (jsonTrain["from"].toObject())["station"].toString();
             train.stationArrival = (jsonTrain["till"].toObject())["station"].toString();

             QJsonArray ticketTypes = jsonTrain["types"].toArray();
             QJsonObject ticketType;
             for(auto it2 = ticketTypes.begin(); it2!=ticketTypes.end();++it2)
             {
                 ticketType = it2->toObject();
                 train.freePlaces.push_back(FreePlaces(ticketType["letter"].toString(),ticketType["places"].toInt()));
            // tempstr = tempstr + ticketType["letter"].toString()+ "    "+ QString::number(ticketType["places"].toInt()) + ",    ";
             }
             //qDebug()<<tempstr;
             trainsContainer.insert(trainNumber,train);
         }

        if (jsonobject["error"].toBool()){
            error = jsonobject["value"].toString();
            //qDebug()<<error;
            CreateJsonFileForTest(data,"test_SearchErrorReply.json");
            return false;
        }


    }

    return true;
}
Exemplo n.º 3
0
/**
 * Do the actual work of createFAQ()
 */
QByteArray SnippetCreator::createQuestions(const QJsonObject& joAPI) const
{
    QJsonArray jaQuestions = joAPI.value("questions").toArray();
    Template tQuestions("./Templates/Questions.html");

    tQuestions.setValue("StyleSheet", "http://localhost:8080/Templates/FAQs.css");

    // for each question
    for(QJsonArray::Iterator itq = jaQuestions.begin(); itq != jaQuestions.end(); ++itq)
    {
        // the question itself
        QJsonObject joQuestion = (*itq).toObject();
        Template tQuestion("./Templates/Question.html");
        tQuestion.setValue("Title", joQuestion.value("question").toString());

        // users
        QJsonArray users = joQuestion.value("users").toArray();
        for(QJsonArray::Iterator itu = users.begin(); itu != users.end(); ++itu)
        {
            QJsonObject joUser = (*itu).toObject();
            Template tInterestedUser("./Templates/InterestedUser.html");
            tInterestedUser.setValue("User", createUser(joUser));
            tQuestion.addValue("InterestedUser", tInterestedUser.toHTML());
        }

        // answers
        QJsonArray joAnswers = joQuestion.value("answers").toArray();
        if(joAnswers.isEmpty())
        {
            Template tAnswer("./Templates/Answer.html");
            tAnswer.setValue("Title", "Not answered!");
            tQuestion.addValue("Answer", tAnswer.toHTML());
        }
        else {
            for(QJsonArray::Iterator ita = joAnswers.begin(); ita != joAnswers.end(); ++ita)
            {
                QJsonObject joAnswer = (*ita).toObject();
                QString link  = joAnswer.value("link") .toString();
                QString title = joAnswer.value("title").toString();
                if(title.isEmpty())
                    title = "Link";

                Template tAnswer("./Templates/Answer.html");
                tAnswer.setValue("Title", title);                // format answer
                tAnswer.setValue("Link",  link);
                tQuestion.addValue("Answer", tAnswer.toHTML());  // add to the question
            }
        }
        tQuestions.addValue("Question", tQuestion.toHTML());     // add the question
    }
    return tQuestions.toHTML();
}
Exemplo n.º 4
0
/**
 * Convert FAQs content into HTML
 * @param jaAPIs    - json array representing the content of the FAQs of an API
 * @return          - an json document containing corresponding HTML
 */
QJsonDocument SnippetCreator::createFAQs(const QJsonArray& jaAPIs) const
{
    QJsonObject joDocPage;
    Settings* settings = Settings::getInstance();

    // stylesheet
    joDocPage.insert("style", QObject::tr("http://%1:%2/Templates/faqs.css")
                                        .arg(settings->getServerIP())
                                        .arg(settings->getServerPort()));

    // FAQs -> HTML
    QJsonArray jaFAQs;
    for(QJsonArray::ConstIterator it = jaAPIs.begin(); it != jaAPIs.end(); ++it)
    {
        QJsonObject joAPI = (*it).toObject();
        QJsonObject joFAQ;
        joFAQ.insert("apisig", joAPI.value("apisig").toString());

        QString html = QString(createFAQ(joAPI));
        joFAQ.insert("html",   html);
        jaFAQs.append(joFAQ);
    }

    joDocPage.insert("apis", jaFAQs);

    qDebug() << joDocPage;
    return QJsonDocument(joDocPage);
}
Exemplo n.º 5
0
void ShellUI::reloadConfig()
{
    m_properties.clear();
    qDeleteAll(m_bindings);
    m_bindings.clear();

    QJsonObject object;
    if (m_config.contains(QStringLiteral("Shell"))) {
        object = m_config[QStringLiteral("Shell")].toObject();
    } else {
        QJsonParseError err;
        QJsonDocument doc = QJsonDocument::fromJson(defaultShell, &err);
        if (err.error != QJsonParseError::NoError) {
            qDebug() << "Cannot parse the default shell config" << err.errorString();
        }
        object = doc.object();
        m_config[QStringLiteral("Shell")] = object;
    }
    QJsonObject properties = object[QStringLiteral("properties")].toObject();
    for (auto i = properties.constBegin(); i != properties.constEnd(); ++i) {
        setProperty(qPrintable(i.key()), i.value().toVariant());
        m_properties << i.key();
    }

    QJsonArray bindings = object[QStringLiteral("bindings")].toArray();
    for (auto i = bindings.begin(); i != bindings.end(); ++i) {
        const QJsonObject &binding = (*i).toObject();
        if (!parseBinding(binding)) {
            qDebug() << "Cannot parse binding" << binding;
        }
    }

    foreach (UiScreen *screen, m_screens) {
        loadScreen(screen);
    }
Exemplo n.º 6
0
void MainWindow::m_updateMessages(QJsonArray messages)
{
    qDebug("MainWindow::m_updateMessages");

    unsigned int count = messages.count();
    m_messagesReceived += count;

    qDebug("MainWindow::m_updateMessages count: %d", count);

    QJsonArray::iterator iter = messages.end();
    for ( ; iter >= messages.begin(); --iter)
    {
        qDebug("m_updateMessages isObject: %d", (*iter).isObject());

        qDebug("m_updateMessages type: 0x%x", (*iter).type());

        QJsonObject jMessage = (*iter).toObject();

        QJsonDocument doc(jMessage);
        qDebug("m_updateMessages doc: %s", doc.toJson().toStdString().c_str());

        QJsonValue message = jMessage["message"];
        qDebug("MainWindow::m_updateMessages message: %s", message.toString().toStdString().c_str());

        QString prevText = ui->messageView->toPlainText();
        prevText += message.toString() + "\r\n";
        ui->messageView->setPlainText(prevText);
    }

}
Exemplo n.º 7
0
bool Parser::parseCoachesSearchResults(QByteArray &data, Train &train,QString coachType)
{

    CreateJsonFileForTest(data,"test_SearchCoachesReply.json");

    QJsonDocument responce;
    responce = QJsonDocument::fromJson(data);
    if (responce.isObject()) {
        QJsonObject jsonobject = responce.object();

         //QJsonObject jsonValue = jsonobject["value"].toObject();
         //QJsonArray jsonCoaches = jsonValue["coaches"].toArray();
         QJsonArray jsonCoaches = jsonobject["coaches"].toArray();
         QJsonObject jsonCoach;
         for(auto it = jsonCoaches.begin();it != jsonCoaches.end();++it)
         {
             jsonCoach = it->toObject();
             int number = jsonCoach["num"].toInt();
             Coach coach(number);
             coach.coachTypeID = QString::number(jsonCoach["coach_type_id"].toInt());
             coach.placesNumber = jsonCoach["places_cnt"].toInt();
             coach.coachClass = coachType;
             //qDebug()<<coachType;
             train.coaches.insert(number,coach);

          }
         return true;
    }
    return false;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QVector<float> JsonFilterParametersReader::readArray(const QString name, QVector<float> value)
{
    BOOST_ASSERT(m_CurrentFilterIndex.isEmpty() == false);
    if (m_CurrentFilterIndex.contains(name) == false)
    {
        return value;
    }

    if (m_CurrentFilterIndex.value(name).isArray())
    {
        QJsonArray jsonArray = m_CurrentFilterIndex.value(name).toArray();
        QVector<float> vector;
        for (QJsonArray::iterator iter = jsonArray.begin(); iter != jsonArray.end(); ++iter)
        {
            if ((*iter).isDouble())
            {
                double val = (*iter).toDouble();
                if (val >= std::numeric_limits<float>().min() && val <= std::numeric_limits<float>().max())
                {
                    vector.push_back(static_cast<float>(val));
                }
            }
        }
        return vector;
    }

    return value;
}
Exemplo n.º 9
0
void YoutubeDL::fetchAvailableFormats(QString url)
{
    QVector<MediaFormat> formats;
    QJsonObject jsonObject = createJsonObject(url);
    QJsonArray jsonFormats = jsonObject["formats"].toArray();
    QJsonArray::iterator i;

    for (i = jsonFormats.begin(); i != jsonFormats.end(); ++i) {
        QJsonValue value = *i;
        QJsonObject formatObject = value.toObject();
        MediaFormat format;
        format.setFormatId(formatObject["format_id"].toString());
        format.setFormat(formatObject["format"].toString());
        format.setExtension(formatObject["ext"].toString());
        format.setNote(formatObject["format_note"].toString());
        if (formatObject.contains("height") && !formatObject["height"].isNull()) {
            QString resolution = QString::number(formatObject["width"].toDouble()) + "x"
                    + QString::number(formatObject["height"].toDouble());
            format.setResolution(resolution);
        }
        format.setVcodec(formatObject["vcodec"].toString().trimmed());
        format.setAcodec(formatObject["acodec"].toString().trimmed());
        formats.append(format);
    }
    this->formats = formats;
}
Exemplo n.º 10
0
QVector<QString> ToStrVector(const QJsonArray& arr)
{
	QVector<QString> vec; vec.reserve(arr.size());
	std::transform(arr.begin(), arr.end(), std::back_inserter(vec), [](const QJsonValue& value) {
		return value.toString();
	});
	return vec;
}
void sampledetailwidget::queryPatientTypeSuccess(const QJsonArray & result) {
    patient_type->clear();
    QJsonArray::const_iterator iter = result.begin();
    for(; iter != result.end(); ++iter) {
        QString tmp = (*iter).toString();
        patient_type->addItem(tmp);
    }
}
void sampledetailwidget::querySampleResourceTypeSuccess(const QJsonArray & result) {
    sample_resource_box->clear();
    QJsonArray::const_iterator iter = result.begin();
    for(; iter != result.end(); ++iter) {
        QString tmp = (*iter).toString();
        sample_resource_box->addItem(tmp);
    }
}
Exemplo n.º 13
0
bool FieldsModel::readOffLineFields()
{
    QFile wntlist(FIELDS_FILENAME);
    if (wntlist.exists())                              //Если есть файл с данными, читаем из него
    {

        if(!wntlist.open(QIODevice::ReadOnly))
        {
            qDebug() << "Couldn`t open fieldsfile ";
            return false;
        } else
        {

            QByteArray saveData = wntlist.readAll();
            wntlist.close();
            QJsonDocument loadDoc(QJsonDocument::fromJson(saveData));
            QJsonArray result = loadDoc.array();
            qDebug() << "Releases in Json " <<result;
            if (result.size()>0)
            {
                emit beginInsertRows(QModelIndex(), rowCount(), rowCount()+result.size()-1);
                for (QJsonArray::const_iterator iter = result.begin();iter!= result.end(); ++iter)
                {

                    const QJsonObject o = (*iter).toObject();
                    QJsonArray options = o["options"].toArray();
                    QStringList i_options;
                    for (int i=0; i<options.size();i++)
                    {
                        i_options << options.at(i).toString();
                    }
                    bool i_isDropdown;
                    if (o["type"].toString()=="dropdown")
                        i_isDropdown = true;
                    else i_isDropdown = false;


                    m_Fields << Fields(o["name"].toString(),
                            i_options,
                            o["id"].toInt(),
                            o["position"].toInt(),
                            o["type"].toString(),
                            o["public"].toBool(),
                            o["lines"].toInt(),
                            i_isDropdown);
                }

                emit endInsertRows();
            }
            O1Requestor::instance().setIsOffline(true);            // Признак того что работаем в оффлайне
            emit isOfflineChanged();
            return true;
        }
    }
    return false;
}
Exemplo n.º 14
0
void QEnginioOperationShared::operationFinished(QSharedPointer<QRestOperationShared> aSelf)
{    
    QSharedPointer<QEnginioRequestShared> enginioRequest;
    QSharedPointer<QEnginioCollectionShared> enginioCollection;

    enginioRequest=qSharedPointerCast<QEnginioRequestShared>(request());
    enginioCollection = enginioRequest->enginioCollection();

    iResultObjects.clear();

    // TODO: cleanup
    if (iJsonObject.contains(QtCloudServicesConstants::results)) {
        QJsonArray jsonObjects;
        QJsonArray::const_iterator i;
        jsonObjects = iJsonObject.value(QtCloudServicesConstants::results).toArray();

        for (i = jsonObjects.begin(); i != jsonObjects.end(); ++i) {
            if (!(*i).isObject()) {
                continue;
            }

            if (!enginioCollection) {
                QJsonObject  jsonObject = (*i).toObject();
                qDebug() << "---- NEED RESOLVE (PER OBJECT)..." // TODO
                         << jsonObject.value(QtCloudServicesConstants::objectType);

                continue;
            }

            QSharedPointer<QEnginioObjectShared> obj;
            obj = enginioCollection->fromJsonObject(enginioCollection,(*i).toObject());

            QEnginioObject x;
            x.object()->d_func()->setSharedInstance(obj);

            iResultObjects.push_back(x);
        }
    } else if (!iJsonObject.isEmpty()) {
        if (!enginioCollection) {
            qDebug() << "---- NEED RESOLVE (PER OBJECT)..." // TODO
                     << iJsonObject.value(QtCloudServicesConstants::objectType);
        } else {
            //iResultObjects.push_back(enginioCollection.fromJsonObject(iJsonObject));

            QSharedPointer<QEnginioObjectShared> obj;
            obj = enginioCollection->fromJsonObject(enginioCollection,iJsonObject);

            QEnginioObject x;
            x.object()->d_func()->setSharedInstance(obj);

            iResultObjects.push_back(x);
        }
    }

    QRestOperationShared::operationFinished(aSelf);
}
Exemplo n.º 15
0
Arquivo: Json.cpp Projeto: xtuer/Qt
QStringList Json::getStringList(const QString &path, const QJsonObject &fromNode) const {
    QStringList result;
    QJsonArray array = getJsonValue(path, fromNode).toArray();

    for (QJsonArray::const_iterator iter = array.begin(); iter != array.end(); ++iter) {
        QJsonValue value = *iter;
        result << value.toString();
    }

    return result;
}
Exemplo n.º 16
0
bool DataFormat::setFormatInfo(const QString& path, const QString connector) {
    QFile file;
    file.setFileName(path);
    if (file.open(QIODevice::ReadOnly)) {
        QString settings = file.readAll();
        QJsonDocument doc = QJsonDocument::fromJson(settings.toUtf8());
        if ( !doc.isNull()){
            InternalDatabaseConnection sqlPublic;
            QJsonObject obj = doc.object();
            QJsonValue formats = obj.value("Formats");
            if ( formats.isArray()){
                InternalDatabaseConnection db("BEGIN TRANSACTION");
                QJsonArray arrFormats = formats.toArray();
                for(auto iter = arrFormats.begin(); iter != arrFormats.end(); ++iter) {
                    auto jsonValue  = *iter;
                    if ( jsonValue.isObject()) {
                        QJsonObject objv = jsonValue.toObject();
                        QString code = objv.value("code").toString(sUNDEF);
                        QString name = objv.value("name").toString(sUNDEF);
                        QString desc = objv.value("description").toString(sUNDEF);
                        QString type = objv.value("type").toString(sUNDEF);
                        QString ext = objv.value("extension").toString(sUNDEF);
                        QString datatp = objv.value("datatypes").toString(sUNDEF);
                        QString fileparts = objv.value("parts").toString(sUNDEF);
                        quint64 ilwtype = itUNKNOWN;
                        QStringList parts = datatp.split(",");
                        for(QString tp : parts)
                            ilwtype |= IlwisObject::name2Type(tp);
                        QString rw = objv.value("readwrite").toString("r");
                        QString extt = objv.value("extendedtype").toString(sUNDEF);
                        quint64 exttypes = itUNKNOWN;
                        parts = extt.split(",");
                        for(QString tp : parts)
                            exttypes |= IlwisObject::name2Type(tp);

                        QString parms = QString("'%1','%2','%3','%4','%5',%6,'%7','%8',%9,'%10'").arg(code.toLower(),name,desc, ext,type).arg(ilwtype).arg(connector).arg(rw).arg(exttypes).arg(fileparts);
                        QString stmt = QString("INSERT INTO dataformats VALUES(%1)").arg(parms);
                        bool ok = sqlPublic.exec(stmt);
                        if (!ok) {
                            return kernel()->issues()->logSql(sqlPublic.lastError());
                        }
                    }

                }
                db.exec("COMMIT TRANSACTION");
                return true;
            }
        }

    }
    return false;
}
Exemplo n.º 17
0
void StatusChecker::statusDownloadFinished()
{
	QLOG_DEBUG() << "Finished loading status JSON.";

	QByteArray data;
	{
		ByteArrayDownloadPtr dl = std::dynamic_pointer_cast<ByteArrayDownload>(m_statusNetJob->first());
		data = dl->m_data;
		m_statusNetJob.reset();
	}

	QJsonParseError jsonError;
	QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonError);

	if (jsonError.error != QJsonParseError::NoError)
	{
		fail("Error parsing status JSON:" + jsonError.errorString());
		return;
	}

	if (!jsonDoc.isArray())
	{
		fail("Error parsing status JSON: JSON root is not an array");
		return;
	}

	QJsonArray root = jsonDoc.array();

	for(auto status = root.begin(); status != root.end(); ++status)
	{
		QVariantMap map = (*status).toObject().toVariantMap();

		for (QVariantMap::const_iterator iter = map.begin(); iter != map.end(); ++iter)
		{
			QString key = iter.key();
			QVariant value = iter.value();

			if(value.type() == QVariant::Type::String)
			{
				m_statusEntries.insert(key, value.toString());
				//QLOG_DEBUG() << "Status JSON object: " << key << m_statusEntries[key];
			}
			else
			{
				fail("Malformed status JSON: expected status type to be a string.");
				return;
			}
		}
	}

	succeed();
}
Exemplo n.º 18
0
/**
 * Create the related users section of a profile page
 */
QByteArray SnippetCreator::createRelatedUsers(const QJsonObject& joProfile) const
{
    Template tUsers("./Templates/RelatedUsers.html");
    QJsonArray jaUsers = joProfile.value("relatedusers").toArray();
    for(QJsonArray::Iterator it = jaUsers.begin(); it != jaUsers.end(); ++it)
    {
        QJsonObject joUser = (*it).toObject();
        Template tRelatedUser("./Templates/RelatedUser.html");
        tRelatedUser.setValue("User", createUser(joUser));
        tUsers.addValue("RelatedUser", tRelatedUser.toHTML());
    }
    return tUsers.toHTML();
}
Exemplo n.º 19
0
std::vector<CSSEnvironment>
CRestWorker::get_environments(int& http_code,
                              int& err_code,
                              int& network_error) {
  std::vector<CSSEnvironment> lst_res;
  QJsonDocument doc = get_request_json_document("environments", http_code, err_code, network_error);  
  QJsonArray arr = doc.array();
  for (auto i = arr.begin(); i != arr.end(); ++i) {
    if (i->isNull() || !i->isObject()) continue;
    lst_res.push_back(CSSEnvironment(i->toObject()));
  }
  return lst_res;
}
QList<QSharedPointer<SongView> > DaoYoutubeCollection::searchSongs(QString s, QString accessToken) {
    QList<QSharedPointer<SongView> > songs;
    //QJsonObject j = getJsonObject(QUrl("http://api.deezer.com/editorial/0/charts&limit=5000"));
    QJsonObject j = mNetworkWorker.getJsonObject(QUrl("https://www.googleapis.com/youtube/v3/search?part=snippet&q="+s+"&type=video&access_token="+accessToken));
 qDebug()<<"ttps://www.googleapis.com/youtube/v3/search?part=snippet&q="+s+"&type=video&access_token="+accessToken;
    QJsonArray a = j["items"].toArray();
    QJsonArray::iterator  it;

    for (it=a.begin();it!=a.end();it++)
    {
        songs.append(getSongFromJson((*it).toObject()));
    }
    return songs;
}
QList<QSharedPointer<SongView> > DaoYoutubeCollection::searchSongsByAlbum(QString idAlbum, QString accessToken)
{
    QList<QSharedPointer<SongView> > songs;
    QJsonObject j = mNetworkWorker.getJsonObject(QUrl("http://api.deezer.com/album/"+idAlbum+"/tracks"));
    QJsonArray a = j["data"].toArray();
    QJsonArray::iterator  it;

    for (it=a.begin();it!=a.end();it++)
    {
        QString id = QString::number((*it).toObject().value("id").toInt());
        songs.append(getSongFromId(id,accessToken));
    }
    return songs;

}
Exemplo n.º 22
0
/**
 * Create the interested APIs section of a profile page
 */
QByteArray SnippetCreator::createInterestedAPIs(const QJsonObject& joProfile) const
{
    Template tAPIs("./Templates/InterestedAPIs.html");
    QJsonArray jaAPIs = joProfile.value("apis").toArray();
    for(QJsonArray::Iterator it = jaAPIs.begin(); it != jaAPIs.end(); ++it)
    {
        QJsonObject joAPI = (*it).toObject();
        QString apiSig = joAPI.value("apisig").toString();

        Template tAPI("./Templates/API.html");
        tAPI.setValue("Signature", apiSig);
        tAPI.setValue("Questions", createQuestions(joAPI));

        tAPIs.addValue("API", tAPI.toHTML());
    }
    return tAPIs.toHTML();
}
Exemplo n.º 23
0
void MindMap::readFromData(QJsonObject& obj)
{
     clear();

    QJsonArray rootListJson = obj["roots"].toArray();

    for(auto it = rootListJson.begin(); it!=rootListJson.end(); ++it)
    {
        QJsonObject root = it->toObject();
        Node* node=new Node();
        addItem(node);
        node->readFromData(root);

        node->setPos(node->getX(),node->getY());
        m_roots.append(node);
    }
}
Exemplo n.º 24
0
void RankClassifier::LoadMLP() {
  QFile file( ":/data/rank_classifier.json" );
  bool opened = file.open( QIODevice::ReadOnly | QIODevice::Text );
  assert( opened );

  QByteArray jsonData = file.readAll();
  QJsonParseError error;
  QJsonObject jsonLayers = QJsonDocument::fromJson( jsonData, &error ).object();
  assert( error.error == QJsonParseError::NoError );

  for( QJsonValueRef jsonLayerRef : jsonLayers ) {
    QJsonObject jsonLayer = jsonLayerRef.toObject();
    MLP::Layer layer;

    // type
    QString type = jsonLayer["type"].toString();
    if( type == "SOFTMAX" ) {
      layer.type = MLP::LAYER_SOFTMAX;
    } else if( type == "SIGMOID" ) {
      layer.type = MLP::LAYER_SIGMOID;
    } else if( type == "RECTIFIER" ) {
      layer.type = MLP::LAYER_RECTIFIER;
    } else {
      assert( "Unknown layer type" );
    }

    // biases
    layer.biases = JsonArrayToVector( jsonLayer[ "biases" ] );

    // weight matrix
    QJsonArray rows = jsonLayer[ "weights" ].toArray();
    std::transform( rows.begin(), rows.end(), std::back_inserter( layer.weights ), []( QJsonValueRef ref ) {
      return JsonArrayToVector( ref );
    });

    DBG( "Load layer: %d biases | %dx%d weights (type %d)",
        layer.biases.size(),
        layer.weights.size(),
        layer.weights.front().size(),
        layer.type);

    mMLP.AddLayer( layer );
  }
}
Exemplo n.º 25
0
QMap<QString, Bookmark*> BookmarkManager::load() {
    QMap<QString, Bookmark*> bookmarks;
    QString settingsLocation = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/bookmarks.json";
    QScopedPointer<QFile> file(new QFile(settingsLocation));

    if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "Unable to open bookmarks " << settingsLocation;

        file.reset(new QFile(QLatin1Literal("/usr/share/sailfish-browser/content/bookmarks.json")));
        if (!file->open(QIODevice::ReadOnly | QIODevice::Text)) {
            qWarning() << "Unable to open bookmarks defaults";
            return bookmarks;
        }
    }

    QJsonDocument doc = QJsonDocument::fromJson(file->readAll());
    if (doc.isArray()) {
        QJsonArray array = doc.array();
        QJsonArray::iterator i;
        QRegularExpression jollaUrl("^http[s]?://(together.)?jolla.com");
        for (i=array.begin(); i != array.end(); ++i) {
            if ((*i).isObject()) {
                QJsonObject obj = (*i).toObject();
                QString url = obj.value("url").toString();
                QString favicon = obj.value("favicon").toString();
                if (url.contains(jollaUrl) ||
                        url.startsWith("http://m.youtube.com/playlist?list=PLQgR2jhO_J0y8YSSvVd-Mg9LM88W0aIpD")) {
                    favicon = "image://theme/icon-m-service-jolla";
                }

                Bookmark* m = new Bookmark(obj.value("title").toString(),
                                           url,
                                           favicon,
                                           obj.value("hasTouchIcon").toBool());
                bookmarks.insert(url, m);
            }
        }
    } else {
        qWarning() << "Bookmarks.json should be an array of items";
    }
    file->close();
    return bookmarks;
}
Exemplo n.º 26
0
void MedNUSContentManager::initLessonList(QJsonDocument jsonResponse)
{
    //Receive Stuff from Network I/O
    QJsonArray *lessonArray = new QJsonArray(jsonResponse.array());
    QJsonArray::ConstIterator curLesson = lessonArray->begin();

    while(curLesson!=lessonArray->end()) {
        QJsonObject fileItem = (*curLesson).toObject();
        QString desc = fileItem["lesson_desc"].toString();
        QString owner = fileItem["lesson_owner_domain"].toString() + "\\" + fileItem["lesson_owner"].toString();
        QStringList content = fileItem["file_list"].toString().split(QRegExp("[{}\",]"),
                                                                     QString::SplitBehavior::SkipEmptyParts);
        //Account for NULL cases
        if(content.size() == 1 && content[0] =="NULL")
            content.clear();

        emit callAddLesson(fileItem["lesson_title"].toString(), desc, owner, content, "");

        curLesson++;
    }

    QStringList content;
    content.push_back("/mednus/lesson1/videos/Skull Anatomy (1 of 5)- Superior, Posterior and Lateral Views -- Head and Neck Anatomy 101.mp4");
    content.push_back("/mednus/lesson1/videos/Osteology of the Skull- 12 Newborn Skull.mp4");
    content.push_back("/mednus/lesson1/pdf/Functional anatomy of skull.pdf");
    content.push_back("/mednus/lesson1/models/model2");
    content.push_back("/mednus/lesson1/quiz/Quiz - The Skull.qiz");
    emit callAddLesson("Functional Anatomy of the Skull","Professor Gopal","Anatomy Department",content, "/mednus/lesson1/story");

    QStringList content2;
    content2.push_back("/mednus/lesson2/pdf/axial_lecture_2.pdf");
    content2.push_back("/mednus/lesson2/videos/Osteology of the Skull- 7 The Face (1).mp4");
    content2.push_back("/mednus/lesson1/models/model1");
    emit callAddLesson("Osteology of the Skull","A/Professor Tan","Anatomy Department",content2, "");

    content2.clear();
    content2.push_back("/mednus/lesson2/pdf/axial_lecture_2.pdf");
    content.push_back("/mednus/lesson1/pdf/Functional anatomy of skull.pdf");
    content2.push_back("/mednus/lesson1/videos/Osteology of the Skull- 12 Newborn Skull.mp4");
    emit callAddLesson("Skull Osteology II","A/Professor Tan","Anatomy Department",content2, "");
    //openLastView(content);
}
Exemplo n.º 27
0
void WeatherRequest::replyFinished(QNetworkReply *reply)
{
    m_items.clear();
    QByteArray ba = reply->readAll();
    reply->deleteLater();
    if(ba.isEmpty())
        return;

    QJsonObject jobj = QJsonDocument::fromJson(ba).object();
    if(jobj.contains("list"))
    {
        QJsonValue value = jobj.take("list");
        if(value.isArray())
        {
            QJsonArray array = value.toArray();
            QJsonArray::iterator it = array.begin();
            for(;it != array.end(); it++)
            {
                if((*it).isObject())
                {
                    QJsonObject obj = (*it).toObject();
                    QStringList keys = m_maps.keys();
                    QStringList::iterator keyIt = keys.begin();
                    WeatherItem item;
                    for(; keyIt != keys.end(); keyIt++)
                    {
                        m_maps[*keyIt]->readData(item,obj.take(*keyIt));
                    }
                    m_items.append(item);
                }
            }
        }
    }
    if(m_items.count() == 7)
    {
        emit refreshData(m_items);
    }
    if(!m_timer->isActive())
    {
        m_timer->start();
    }
}
QList<QSharedPointer<SongView> > DaoYoutubeCollection::searchSongsByPlaylist(QString playlistId,QString accessToken)
{
    QList<QSharedPointer<SongView> > songs;
    QJsonArray a;

    QJsonObject j = mNetworkWorker.getJsonObject(QUrl("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId="+playlistId+"&access_token="+accessToken));
    qDebug()<<"https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId="+playlistId+"&access_token="+accessToken;

    a = j["items"].toArray();

    QJsonArray::iterator  it;

    for (it=a.begin();it!=a.end();it++)
    {

        QString id = (*it).toObject()["snippet"].toObject()["resourceId"].toObject()["videoId"].toString();
        songs.append(getSongFromId(id,accessToken));
    }
    return songs;
}
// -----------------------------------------------------------------------------
//
// -----------------------------------------------------------------------------
QVector<QString> JsonFilterParametersReader::readStrings(const QString name, QVector<QString> value)
{
    BOOST_ASSERT(m_CurrentFilterIndex.isEmpty() == false);
    if (m_CurrentFilterIndex.contains(name) == false)
    {
        return value;
    }

    QJsonArray jsonArray = m_CurrentFilterIndex.value(name).toArray();
    QVector<QString> vector;
    for (QJsonArray::iterator iter = jsonArray.begin(); iter != jsonArray.end(); ++iter)
    {
        if ((*iter).isString())
        {
            QString str = (*iter).toString();
            vector.push_back(str);
        }
    }

    return vector;
}
Exemplo n.º 30
0
bool Parser::parseStations(QByteArray &data, QMap<QString,QString> &stations)
{
    CreateJsonFileForTest(data,"test_StationReply.json");

    QJsonDocument responce;
    responce = QJsonDocument::fromJson(data);
    if (responce.isObject()) {
        QJsonObject jsonobject = responce.object();
         QJsonArray jsonStations = jsonobject["value"].toArray();
         QJsonObject station;
         for(auto it2 = jsonStations.begin();it2 != jsonStations.end();++it2)
         {
             station = it2->toObject();
             stations.insert(station["title"].toString(), station["station_id"].toString());
             //stations.insert(station["title"].toString(), QString::number(station["station_id"].toInt()));
            // qDebug()<<"-- :  "<< station["title"].toString()<<" "<<station["station_id"].toString();
         }
        return true;
    }
    return false;
}