Beispiel #1
0
/*!
 Returns a QVariant representing the Json document.

 The returned variant will be a QVariantList if the document is
 a QJsonArray and a QVariantMap if the document is a QJsonObject.

 \sa fromVariant(), QJsonValue::toVariant()
 */
QVariant QJsonDocument::toVariant() const
{
    if (!d)
        return QVariant();

    if (d->header->root()->isArray())
        return QJsonArray(d, static_cast<QJsonPrivate::Array *>(d->header->root())).toVariantList();
    else
        return QJsonObject(d, static_cast<QJsonPrivate::Object *>(d->header->root())).toVariantMap();
}
Beispiel #2
0
//------------------------------------------------------------------------------
// Name: array
//------------------------------------------------------------------------------
QJsonArray QJsonDocument::array() const {

	if(!isEmpty()) {
		if(QJsonArray *const array = root_->toArray()) {
			return *array;
		}
	}

	return QJsonArray();
}
Beispiel #3
0
void search::findinfile(){

    if(document->isEmpty()) {
        QFile file(":/city_data");
        if(file.open(QIODevice::ReadOnly)){
            QString citydata = file.readAll();
            //qDebug()<<citydata;
            QJsonParseError json_error;
            *document = QJsonDocument::fromJson(citydata.toUtf8(),&json_error);
            if(json_error.error != QJsonParseError::NoError) {
                qDebug()<<"json error"<<json_error.errorString();
                return;
            }
        }
        file.close();
    }
    //QString data = "[{\"s\":[true,1,5]},{\"s\":[true,1,5]}]";
    //qt 的 json不能解析{a:"xxx"}这种,只能{"a":"xxx"}这种key为字符串的json
    QJsonObject ob;
    QString n,p,pc,pv,fl;
    QJsonArray arr;
    if((!oldkey.isEmpty())&&(key.indexOf(oldkey)>-1 ))//继续输入时使用之前的结果,但减少不可以,因为tmp是不断更新的
    {
        arr = tmp;
        //qDebug()<<"arr = tmp";
    }
    else {
         arr = document->array();
         //qDebug()<<"arr = document->array()";
    }
    tmp = QJsonArray();//清空,准备储存新的结果
    for(int i=0;i<arr.count();i++)
    {
        ob = arr.at(i).toObject();
        n = ob.value("n").toString();
        p = ob.value("p").toString();//p和pc可以随便用
        pc = ob.value("pc").toString();
        pv = ob.value("pv").toString();
        fl = ob.value("fl").toString();
        p = n + p + pc + pv + fl;//p和pc可以随便用
        if(p.indexOf(key)!=-1)
        {
            //qDebug()<<"Found:"<<p;
            tmp +=arr.at(i);
            QListWidgetItem *item;
            item=new QListWidgetItem;
            item->setText(n + "-" + pv);
            item->setToolTip(ob.value("ac").toString());
            ui->listWidget->addItem(item);
        }
        //qDebug()<<"url:"<<ob.value("n");
    }

    oldkey = key;//备份当前搜索词
}
QJsonArray
libertined_list_app_ids(char const* container_id)
{
  SessionBus session;
  auto path = call(session.bus, "list_app_ids", QVariantList{QVariant(container_id)});

  if (!waitForFinish(session.bus, path))
  {
    return QJsonArray();
  }

  auto error = lastError(session.bus, path);
  if (!error.isEmpty())
  {
    qWarning() << "error:" << error;
    return QJsonArray();
  }

  return QJsonDocument::fromJson(result(session.bus, path).toLatin1()).array();
}
QJsonObject Plotline::serialize() const{
    QJsonObject plotline = QJsonObject();

    QJsonArray jCharacters = QJsonArray();
    for (Character *c : mCharacters)
        jCharacters.append(c->id().toString());

    QJsonArray jScenes = QJsonArray();
    for (Scene *s : mScenes)
        jScenes.append(s->id().toString());

    plotline[J_CHARACTERS] = jCharacters;
    plotline[J_SCENES] = jScenes;
    plotline[J_BRIEF] = mBrief;
    plotline[J_SYNOPSIS] = mSynopsis;
    plotline[J_COLOR] = mColor.name();
    plotline[JSON_ID] = id().toString();

    return plotline;
}
Beispiel #6
0
/*!
    Returns \c true if the \a other document is equal to this document.
 */
bool QJsonDocument::operator==(const QJsonDocument &other) const
{
   if (d == other.d) {
      return true;
   }

   if (!d || !other.d) {
      return false;
   }

   if (d->header->root()->isArray() != other.d->header->root()->isArray()) {
      return false;
   }

   if (d->header->root()->isObject())
      return QJsonObject(d, static_cast<QJsonPrivate::Object *>(d->header->root()))
             == QJsonObject(other.d, static_cast<QJsonPrivate::Object *>(other.d->header->root()));
   else
      return QJsonArray(d, static_cast<QJsonPrivate::Array *>(d->header->root()))
             == QJsonArray(other.d, static_cast<QJsonPrivate::Array *>(other.d->header->root()));
}
Beispiel #7
0
Cache::Cache(const QDir &cacheDir) : m_dir(cacheDir)
{
	m_cacheMetadataFilename = m_dir.absoluteFilePath(".cache.json");
	FS::ensureExists(m_dir);
	m_dir.refresh();
	if (m_dir.exists(m_cacheMetadataFilename)) {
		readCacheFile();
	} else {
		Json::write(QJsonArray(), m_cacheMetadataFilename); // ensure that there's a file
															// available for reading
	}
}
static void appendToCacheFile(const QJsonObject& object)
{
    QJsonDocument jsonDocument;
    ReadResult::Tag result = readMetaDataFromCacheFile(jsonDocument);
    if (result == ReadResult::Error)
        return;
    if (result == ReadResult::Empty)
        jsonDocument.setArray(QJsonArray());

    QJsonArray array = jsonDocument.array();
    array.append(object);
    writeToCacheFile(array);
}
Beispiel #9
0
void Map::updateDataProvince()
{
    QJsonObject postData;
    postData.insert("type", "get_all");
    postData.insert("player", mPlayer);
    postData.insert("cls", "province");
    postData.insert("id", "all");
    postData.insert("atts", QJsonArray({mStripe0, mStripe1}));


    QNetworkRequest request(mUrl);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    mManager->post(request, QJsonDocument(postData).toJson());
}
Beispiel #10
0
void UsrData::saveHistoryBundle()
{
//  auto lambda = [&]()
//    {
      QString file_path = QString(history_path+"/%1.json").arg(current_history_bundle_index);
      QFile file(file_path);
      if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
          return;
        }
      QTextStream out(&file);

      ///max num of messages allowed in each file.
      QJsonObject history_bundle_json_obj;
      if(latest_history_json_array.count() < max_bundle_capacity)
        {
          history_bundle_json_obj.insert("full", false);
          history_bundle_json_obj.insert("history", latest_history_json_array);

          QJsonDocument active_history_json_doc;
          active_history_json_doc.setObject(history_bundle_json_obj);
          out << active_history_json_doc.toJson();
        }
      else
        {
          history_bundle_json_obj.insert("full", true);
          history_bundle_json_obj.insert("history", latest_history_json_array);

          history_bundle_list.append(history_bundle_json_obj.value("history").toArray());

          QJsonDocument active_history_json_doc;
          active_history_json_doc.setObject(history_bundle_json_obj);
          out << active_history_json_doc.toJson();

    //      for(int i = 0; i < current_history_json_array.count(); i++)
    //        {
    //          current_history_json_array.removeFirst();
    //        }
          latest_history_json_array = QJsonArray();

          current_history_bundle_index ++;
          makeHistoryBundle(current_history_bundle_index);
        }

      file.flush();
      file.close();
//    };

//  QtConcurrent::run(lambda);
}
Beispiel #11
0
CommentsModel* Entry::commentsModel()
{
    if (_commentsModel && _commentsModel->entryId() == _id)
        return _commentsModel;

    delete _commentsModel;
    _commentsModel = new CommentsModel(this);
    _commentsModel->init(_commentsData, _commentsCount);
    _commentsData = QJsonArray();

    Q_TEST(connect(_commentsModel,    SIGNAL(totalCountChanged(int)),   this, SLOT(_setCommentsCount(int))));

    return _commentsModel;
}
Beispiel #12
0
/*!
    Returns \c true if the value is equal to \a other.
 */
bool QJsonValue::operator==(const QJsonValue &other) const
{
    if (t != other.t)
        return false;

    switch (t) {
    case Undefined:
    case Null:
        break;
    case Bool:
        return b == other.b;
    case Double:
        return dbl == other.dbl;
    case String:
        return toString() == other.toString();
    case Array:
        if (base == other.base)
            return true;
        if (!base)
            return !other.base->length;
        if (!other.base)
            return !base->length;
        return QJsonArray(d, static_cast<QJsonPrivate::Array *>(base))
                == QJsonArray(other.d, static_cast<QJsonPrivate::Array *>(other.base));
    case Object:
        if (base == other.base)
            return true;
        if (!base)
            return !other.base->length;
        if (!other.base)
            return !base->length;
        return QJsonObject(d, static_cast<QJsonPrivate::Object *>(base))
                == QJsonObject(other.d, static_cast<QJsonPrivate::Object *>(other.base));
    }
    return true;
}
Beispiel #13
0
void Session::Request::fetchProfileData() {
//    QNetworkRequest request = createRequest(ProfileDataUrl());
//    QNetworkReply *r = _manager->get(request);
//    connect(r, &QNetworkReply::finished, this, &Session::Request::Request::onProfileData);

    QJsonObject object;
    object.insert("name", "Novynn_GGG");
    object.insert("avatar_url", "");
    object.insert("messages", 0);
    object.insert("badges", QJsonArray());

    _accountName = object.value("name").toString();

    QJsonDocument temp(object);
    emit profileData(temp.toJson());
}
Beispiel #14
0
/*!
    Converts the value to a QVariant.

    The QJsonValue types will be converted as follows:

    \value Null     QVariant()
    \value Bool     QVariant::Bool
    \value Double   QVariant::Double
    \value String   QVariant::String
    \value Array    QVariantList
    \value Object   QVariantMap
    \value Undefined QVariant()

    \sa fromVariant()
 */
QVariant QJsonValue::toVariant() const
{
    switch (t) {
    case Bool:
        return b;
    case Double:
        return dbl;
    case String:
        return toString();
    case Array:
        return QJsonArray(d, static_cast<QJsonPrivate::Array *>(base)).toVariantList();
    case Object:
        return QJsonObject(d, static_cast<QJsonPrivate::Object *>(base)).toVariantMap();
    case Null:
    case Undefined:
        break;
    }
    return QVariant();
}
Beispiel #15
0
QJsonObject JsonSaver::saveBuildingType(const BuildingType& buildingtype)
{
    QJsonObject res;
    res.insert("name", QString::fromStdString(buildingtype.name));
    res.insert("size", saveSizeU(buildingtype.size));
    res.insert("recipes", QJsonArray());

    QJsonArray requirements;
    int i = 0;
    for(const auto& p : buildingtype.requirements)
    {
        QJsonObject o;
        o.insert("name", QString::fromStdString(ResourcesHandler::const_instance().get(p.first)));
        o.insert("amount", (double)p.second);
        requirements.insert(i++, o);
    }
    res.insert("requirements", requirements);

    return res;
}
Beispiel #16
0
void jsonHandler::write_xdataModel(QString sport, QStandardItemModel *model)
{
    QJsonArray item_xdata,intArray,value_array;
    QJsonObject xdataObj,item_array;
    int offset;;
    int xdataCol;
    if(sport == settings::isSwim)
    {
        offset = 3;
        xdataCol = 1;
    }
    else
    {
        offset = 2;
        xdataCol = 0;
    }

    xdataObj.insert("NAME",xData.value("NAME"));
    xdataObj.insert("UNITS",listToJson(&xdataUnits));
    xdataObj.insert("VALUES",listToJson(&xdataValues));

    for(int i = 0; i < model->rowCount(); ++i)
    {
        item_array.insert("SECS",QJsonValue::fromVariant(model->data(model->index(i,xdataCol,QModelIndex()))));
        item_array.insert("KM",QJsonValue::fromVariant(model->data(model->index(i,xdataCol+1,QModelIndex()))));

        for(int x = 0; x < xdataValues.count(); ++x)
        {
            value_array.insert(x,QJsonValue::fromVariant(model->data(model->index(i,x+offset,QModelIndex()))));
        }

        item_array["VALUES"] = value_array;
        intArray.insert(i,item_array);
        item_array = QJsonObject();
        value_array = QJsonArray();
    }

    xdataObj.insert("SAMPLES",intArray);
    item_xdata.insert(0,xdataObj);
    activityItem["XDATA"] = item_xdata;
}
Beispiel #17
0
void LoginHandler::guestLogin(const QString &username)
{
	if(m_server->identityManager() && m_server->identityManager()->isAuthorizedOnly()) {
		sendError("noGuest", "Guest logins not allowed");
		return;
	}

	m_client->setUsername(username);
	m_state = WAIT_FOR_LOGIN;
	
	protocol::ServerReply identReply;
	identReply.type = protocol::ServerReply::RESULT;
	identReply.message = "Guest login OK!";
	identReply.reply["state"] = "identOk";
	identReply.reply["flags"] = QJsonArray();
	identReply.reply["ident"] = m_client->username();
	identReply.reply["guest"] = true;
	send(identReply);

	announceServerInfo();
}
Beispiel #18
0
QJsonObject MediaViewModel::toJson(MediaViewQuery &query)
{
    QJsonObject obj;
    QJsonArray arr;

    while (query.mediaQuery->next())
    {
        arr.append(Media::toJson(query.mediaQuery.data()));
    }
    obj.insert(TABLE_Media, arr);

    arr = QJsonArray();

    while (query.tagQuery->next())
    {
        arr.append(Tag::toJson(query.tagQuery.data()));
    }
    obj.insert(TABLE_Tags, arr);

    return obj;
}
Beispiel #19
0
KNMusicPlaylistModel::KNMusicPlaylistModel(QThread *workingThread,
                                           QObject *parent) :
    KNMusicModel(parent),
    m_searcher(new KNMusicSearcher),
    m_analysisQueue(new KNMusicAnalysisQueue),
    m_title(QString()),
    m_filePath(QString()),
    m_contentData(QJsonArray()),
    m_built(false),
    m_changed(false)
{
    //When the row count changed, this model should be marked to be changed.
    connect(this, &KNMusicPlaylistModel::rowCountChanged,
            this, &KNMusicPlaylistModel::onActionModelChanged);
    //When there's a data changed, this model should be marked to be changed
    //as well.
    connect(this, &KNMusicPlaylistModel::dataChanged,
            this, &KNMusicPlaylistModel::onActionModelChanged);

    //Move the searcher to working thread.
    m_searcher->moveToThread(workingThread);
    //Link the require add signal to searcher.
    connect(this, &KNMusicPlaylistModel::requireAnalysisFiles,
            m_searcher, &KNMusicSearcher::analysisPaths,
            Qt::QueuedConnection);

    //Move the analysis queue to wokring thread.
    m_analysisQueue->moveToThread(workingThread);
    //Link the searcher with the analysis queue.
    connect(m_searcher, &KNMusicSearcher::findFile,
            m_analysisQueue, &KNMusicAnalysisQueue::addFile,
            Qt::QueuedConnection);
    connect(m_analysisQueue, &KNMusicAnalysisQueue::analysisComplete,
            this, &KNMusicPlaylistModel::onActionAnalysisComplete,
            Qt::QueuedConnection);
}
Beispiel #20
0
#include "couchdb.h"
#include "QJsonObject"
#include "QJsonArray"
#include "QJsonDocument"
#include "QJsonValue"
#include "QVariant"
#include "QVariantList"

Couchdb::Couchdb(QObject* parent) : QObject(parent)
{

}

QJsonArray Couchdb::documents = QJsonArray();

void Couchdb::getAllDocuments(const QString &url, const QString &db)
{
    manager = new QNetworkAccessManager(this);

    connect(manager, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished(QNetworkReply*)));

    QString finalUrl(QString("%1/%2/_design/entries/_view/all").arg(url).arg(db));
    QNetworkRequest request = QNetworkRequest(QUrl(finalUrl));
    request.setRawHeader("User-Agent", "Mozilla Firefox");

    qDebug() << "Making a GET http request to " << finalUrl;


    manager->get(request);
}
Beispiel #21
0
void Calendar::updateData()
{
    if (m_days == 0 || m_weeks == 0) {
        return;
    }

    m_dayList.clear();
    m_weekList = QJsonArray();

    int totalDays = m_days * m_weeks;

    int daysBeforeCurrentMonth = 0;
    int daysAfterCurrentMonth = 0;

    QDate firstDay(m_displayedDate.year(), m_displayedDate.month(), 1);

    // If the first day is the same as the starting day then we add a complete row before it.
    if (m_firstDayOfWeek < firstDay.dayOfWeek()) {
        daysBeforeCurrentMonth = firstDay.dayOfWeek() - m_firstDayOfWeek;
    } else {
        daysBeforeCurrentMonth = days() - (m_firstDayOfWeek - firstDay.dayOfWeek());
    }

    int daysThusFar = daysBeforeCurrentMonth + m_displayedDate.daysInMonth();
    if (daysThusFar < totalDays) {
        daysAfterCurrentMonth = totalDays - daysThusFar;
    }

    if (daysBeforeCurrentMonth > 0) {
        QDate previousMonth = m_displayedDate.addMonths(-1);
        //QDate previousMonth(m_displayedDate.year(), m_displayedDate.month() - 1, 1);
        for (int i = 0; i < daysBeforeCurrentMonth; i++) {
            DayData day;
            day.isCurrent = false;
            day.dayNumber = previousMonth.daysInMonth() - (daysBeforeCurrentMonth - (i + 1));
            day.monthNumber = previousMonth.month();
            day.yearNumber = previousMonth.year();
            //      day.containsEventItems = false;
            m_dayList << day;
        }
    }

    for (int i = 0; i < m_displayedDate.daysInMonth(); i++) {
        DayData day;
        day.isCurrent = true;
        day.dayNumber = i + 1; // +1 to go form 0 based index to 1 based calendar dates
        //  day.containsEventItems = m_dayHelper->containsEventItems(i + 1);
        day.monthNumber = m_displayedDate.month();
        day.yearNumber = m_displayedDate.year();
        m_dayList << day;

    }

    if (daysAfterCurrentMonth > 0) {
        for (int i = 0; i < daysAfterCurrentMonth; i++) {
            DayData day;
            day.isCurrent = false;
            day.dayNumber = i + 1; // +1 to go form 0 based index to 1 based calendar dates
            //   day.containsEventItems = false;
            day.monthNumber = m_displayedDate.addMonths(1).month();
            day.yearNumber = m_displayedDate.addMonths(1).year();
            m_dayList << day;
        }
    }
    const int numOfDaysInCalendar = m_dayList.count();

    // Week numbers are always counted from Mondays
    // so find which index is Monday
    int mondayOffset = 0;
    if (!m_dayList.isEmpty()) {
        const DayData &data = m_dayList.at(0);
        QDate firstDay(data.yearNumber, data.monthNumber, data.dayNumber);
        // If the first day is not already Monday, get offset for Monday
        if (firstDay.dayOfWeek() != 1) {
            mondayOffset = 8 - firstDay.dayOfWeek();
        }
    }

    // Fill weeksModel with the week numbers
    for (int i = mondayOffset; i < numOfDaysInCalendar; i += 7) {
        const DayData &data = m_dayList.at(i);
        m_weekList.append(QDate(data.yearNumber, data.monthNumber, data.dayNumber).weekNumber());
    }
    emit weeksModelChanged();
    m_daysModel->update();

//    qDebug() << "---------------------------------------------------------------";
//    qDebug() << "Date obj: " << m_displayedDate;
//    qDebug() << "Month: " << m_displayedDate.month();
//    qDebug() << "m_days: " << m_days;
//    qDebug() << "m_weeks: " << m_weeks;
//    qDebug() << "Days before this month: " << daysBeforeCurrentMonth;
//    qDebug() << "Days after this month: " << daysAfterCurrentMonth;
//    qDebug() << "Days in current month: " << m_displayedDate.daysInMonth();
//    qDebug() << "m_dayList size: " << m_dayList.count();
//    qDebug() << "---------------------------------------------------------------";
}
Beispiel #22
0
void LoginHandler::expectLoginOk(const protocol::ServerReply &msg)
{
	if(msg.type == protocol::ServerReply::LOGIN) {
		// We can still get session list updates here. They are safe to ignore.
		return;
	}

	if(msg.reply["state"] == "join" || msg.reply["state"] == "host") {
		m_loggedInSessionId = msg.reply["join"].toObject()["id"].toString();
		m_userid = msg.reply["join"].toObject()["user"].toInt();
		m_server->loginSuccess();

		// If in host mode, send initial session settings
		if(m_mode==HOST) {
			protocol::ServerCommand conf;
			conf.cmd = "sessionconf";

			if(!m_title.isEmpty())
				conf.kwargs["title"] = m_title;

			if(!m_sessionPassword.isEmpty())
				conf.kwargs["password"] = m_sessionPassword;

			if(m_maxusers>0)
				conf.kwargs["max-users"] = m_maxusers;

			if(m_requestPersistent)
				conf.kwargs["persistent"] = true;

			if(m_preserveChat)
				conf.kwargs["preserve-chat"] = true;

			m_server->sendMessage(protocol::MessagePtr(new protocol::Command(userId(), conf)));

			uint16_t lockflags = 0;

			if(!m_allowdrawing)
				lockflags |= protocol::SessionACL::LOCK_DEFAULT;

			if(m_layerctrllock)
				lockflags |= protocol::SessionACL::LOCK_LAYERCTRL;

			if(lockflags)
				m_server->sendMessage(protocol::MessagePtr(new protocol::SessionACL(userId(), lockflags)));

			if(!m_announceUrl.isEmpty()) {
				protocol::ServerCommand cmd;
				cmd.cmd = "announce-session";
				cmd.args = QJsonArray() << m_announceUrl;
				m_server->sendMessage(protocol::MessagePtr(new protocol::Command(userId(), cmd)));
			}

			m_server->sendSnapshotMessages(m_initialState);
		}

		delete _selectorDialog;
		delete _passwordDialog;
		delete _certDialog;

	} else {
		// Unexpected response
		qWarning() << "Login error. Unexpected response while waiting for OK:" << msg.reply;
		failLogin(tr("Incompatible server"));
	}
}
Beispiel #23
0
void jsonHandler::init_xdataModel(QStandardItemModel *model)
{
    QStringList xdataList = settings::get_jsonTags("xdata");

    QJsonArray itemArray;
    QJsonObject item_xdata = activityItem["XDATA"].toArray().at(0).toObject();
    this->fill_qmap(&xData,&item_xdata);

    itemArray = item_xdata[xdataList.at(2)].toArray();
    this->fill_list(&itemArray,&xdataUnits);

    itemArray = QJsonArray();
    itemArray = item_xdata[xdataList.at(1)].toArray();
    this->fill_list(&itemArray,&xdataValues);

    itemArray = QJsonArray();
    itemArray = item_xdata[xdataList.at(3)].toArray();
    QJsonObject obj_xdata = itemArray.at(0).toObject();

    model->setRowCount(itemArray.count());
    model->setColumnCount((obj_xdata.keys().count()+xdataValues.count()));


    for(int i = 0; i < itemArray.count(); ++i)
    {
        obj_xdata = itemArray.at(i).toObject();
        QJsonArray arrValues = obj_xdata[xdataList.at(1)].toArray();
        model->setData(model->index(i,0,QModelIndex()),obj_xdata["SECS"].toInt());
        model->setData(model->index(i,1,QModelIndex()),obj_xdata["KM"].toDouble());
        for(int x = 0; x < arrValues.count(); ++x)
        {
            model->setData(model->index(i,x+2,QModelIndex()),arrValues.at(x).toVariant());
        }
    }

    /*
    if(sport == settings::isSwim)
    {
        for(int i = 0; i < itemArray.count(); ++i)
        {
            obj_xdata = itemArray.at(i).toObject();
            QJsonArray arrValues = obj_xdata[xdataList.at(1)].toArray();
            model->setData(model->index(i,0,QModelIndex()),obj_xdata["SECS"].toInt());
            model->setData(model->index(i,1,QModelIndex()),obj_xdata["KM"].toDouble());
            model->setData(model->index(i,2,QModelIndex()),arrValues.at(0).toInt());
            model->setData(model->index(i,3,QModelIndex()),arrValues.at(1).toDouble());
            model->setData(model->index(i,4,QModelIndex()),arrValues.at(2).toInt());
        }
    }
    if(sport == settings::isBike)
    {
        for(int i = 0; i < itemArray.count(); ++i)
        {
            obj_xdata = itemArray.at(i).toObject();
            QJsonArray arrValues = obj_xdata[xdataList.at(1)].toArray();
            model->setData(model->index(i,0,QModelIndex()),obj_xdata["SECS"].toDouble());
            model->setData(model->index(i,1,QModelIndex()),obj_xdata["KM"].toInt());
            model->setData(model->index(i,2,QModelIndex()),arrValues.at(0).toInt());
            model->setData(model->index(i,3,QModelIndex()),arrValues.at(1).toInt());
        }
    }
    if(sport == settings::isRun)
    {
        for(int i = 0; i < itemArray.count(); ++i)
        {
            obj_xdata = itemArray.at(i).toObject();
            QJsonArray arrValues = obj_xdata[xdataList.at(1)].toArray();
            model->setData(model->index(i,0,QModelIndex()),obj_xdata["SECS"].toInt());
            model->setData(model->index(i,1,QModelIndex()),obj_xdata["KM"].toInt());
            model->setData(model->index(i,2,QModelIndex()),arrValues.at(0).toInt());
            model->setData(model->index(i,3,QModelIndex()),arrValues.at(1).toInt());
            model->setData(model->index(i,4,QModelIndex()),arrValues.at(2).toInt());
            model->setData(model->index(i,5,QModelIndex()),arrValues.at(3).toDouble());
        }
    }
    */
}
/** Processes all message received on the update 0MQ socket */
void QApplicationLauncher::subscribeMessageReceived(QList<QByteArray> messageList)
{
    QByteArray topic;

    topic = messageList.at(0);
    m_rx.ParseFromArray(messageList.at(1).data(), messageList.at(1).size());

#ifdef QT_DEBUG
    std::string s;
    gpb::TextFormat::PrintToString(m_rx, &s);
    DEBUG_TAG(3, m_commandIdentity, "launcher update" << topic << QString::fromStdString(s))
#endif

    if (m_rx.type() == pb::MT_LAUNCHER_FULL_UPDATE) //value update
    {
        m_launchers = QJsonValue(QJsonArray()); // clear old value
        Service::updateValue(m_rx, &m_launchers, "launcher", "launcher"); // launcher protobuf value, launcher temp path
        emit launchersChanged(m_launchers);

        if (m_subscribeSocketState != Service::Up)
        {
            m_subscribeSocketState = Service::Up;
            updateState(Service::Connected);
        }

        updateSync();

        if (m_rx.has_pparams())
        {
            pb::ProtocolParameters pparams = m_rx.pparams();
            startSubscribeHeartbeat(pparams.keepalive_timer() * 2);  // wait double the time of the hearbeat interval
        }
    }
    else if (m_rx.type() == pb::MT_LAUNCHER_INCREMENTAL_UPDATE){
        Service::updateValue(m_rx, &m_launchers, "launcher", "launcher"); // launcher protobuf value, launcher temp path
        emit launchersChanged(m_launchers);

        refreshSubscribeHeartbeat();
    }
    else if (m_rx.type() == pb::MT_PING)
    {
        if (m_subscribeSocketState == Service::Up)
        {
            refreshSubscribeHeartbeat();
        }
        else
        {
            updateState(Service::Connecting);
            unsubscribe("launcher");  // clean up previous subscription
            subscribe("launcher");    // trigger a fresh subscribe -> full update
        }
    }
    else if (m_rx.type() == pb::MT_LAUNCHER_ERROR)
    {
        QString errorString;

        for (int i = 0; i < m_rx.note_size(); ++i)
        {
            errorString.append(QString::fromStdString(m_rx.note(i)) + "\n");
        }

        m_subscribeSocketState = Service::Down;
        updateState(Service::Error, Service::CommandError, errorString);

#ifdef QT_DEBUG
        DEBUG_TAG(1, m_commandIdentity, "proto error on subscribe" << errorString)
#endif
    }
/** process block hash list **/
void blockchain_network::process_block_hash_list(){
    //Get first block hash
    QByteArray http_request = QByteArray();
    QByteArray http_head = generate_http_head();
    QByteArray http_body = QByteArray();

    QJsonObject request_jsonobj = QJsonObject();
    request_jsonobj.insert(QString("jsonrpc"), QJsonValue(QString("1.0")));
    request_jsonobj.insert(QString("id"), QJsonValue(QString("1.0")));
    request_jsonobj.insert(QString("method"), QJsonValue(QString("getblockhash")));

    QJsonArray request_jsonarray = QJsonArray();
    request_jsonarray.insert(0, QJsonValue(current_block_index));

    request_jsonobj.insert(QString("params"), QJsonValue(request_jsonarray));

    QJsonDocument request_jsondoc = QJsonDocument(request_jsonobj);
    http_body.append(request_jsondoc.toJson());

    QString http_head_modified = QString::fromUtf8(http_head);
    http_head_modified = http_head_modified.arg(http_body.length());
    http_head = http_head_modified.toUtf8();

    //Combine head + body
    http_request.append(http_head);
    http_request.append(http_body);

    //write to blockchain network for the highest block count
    blockchain_tcp->write(http_request);

    //wait for response from blockchain
    if(blockchain_tcp->waitForReadyRead()){
        qDebug() << "response from blockchain";
        QByteArray blockchain_response = blockchain_tcp->readAll();
        qDebug() << blockchain_response;
        QString blockchain_response_string = QString::fromUtf8(blockchain_response);
        QString blockchain_response_body = blockchain_response_string.split(QString("\r\n\r\n")).at(1);
        blockchain_response_body.replace(QString("\r\n"), QString(""));

        /* extract blockhash */
        QJsonDocument blockchain_response_jsondoc = QJsonDocument::fromJson(blockchain_response_body.toUtf8());
        QJsonObject blockchain_response_jsonobj = blockchain_response_jsondoc.object();

        //extract blockhash from the "result"
        QJsonValue blockhash_jsonvalue = blockchain_response_jsonobj.value("result");
        QString blockhash_string = blockhash_jsonvalue.toString();

        qDebug() << blockhash_string;

        //Is there a next block?
        if(current_block_index < total_block_count){
            //yes, there is a next block, check it on the next round of processing by incrementing current block index
            current_block_index = current_block_index + 1;
        }else{
            //no there is not a next block hash to retrieve
            qDebug() << "got all the block hashes";

            //Move on to the next process
            process_network_switch = 2;
        }

        //keep processing
        emit keep_processing();

    }else{
        qDebug() << "TIMED OUT";
    }
}
Beispiel #26
0
 void EtherIPC::getAccounts() {
     fAccountList.clear();
     if ( !queueRequest(RequestIPC(GetAccountRefs, "personal_listAccounts", QJsonArray())) ) {
         return bail();
     }
 }
Beispiel #27
0
void KNMusicPlaylistListItem::clearPlaylistContent()
{
    m_playlistContent=QJsonArray();
}
Beispiel #28
0
        JsonArrayWrapper::JsonArrayWrapper(const QJsonValue &val)
            : QJsonArray(val.isArray() ? val.toArray() : QJsonArray({val}))
        {

        }
Beispiel #29
0
//------------------------------------------------------------------------------
// Name: operator=
// Desc: assignment operator
//------------------------------------------------------------------------------
QJsonArray &QJsonArray::operator=(const QJsonArray &other) {
	QJsonArray(other).swap(*this);
	return *this;
}
Beispiel #30
0
/** Load the research stats */
bool loadResearch(QString filename)
{
	WzConfig ini(filename, WzConfig::ReadOnlyAndRequired);
	QStringList list = ini.childGroups();
	PLAYER_RESEARCH dummy;
	memset(&dummy, 0, sizeof(dummy));
	QVector<QStringList> preResearch;
	preResearch.resize(list.size());
	for (int inc = 0; inc < list.size(); ++inc)
	{
		// HACK FIXME: the code assumes we have empty PLAYER_RESEARCH entries to throw around
		for (int j = 0; j < MAX_PLAYERS; j++)
		{
			asPlayerResList[j].push_back(dummy);
		}

		ini.beginGroup(list[inc]);
		RESEARCH research;
		research.index = inc;
		research.name = ini.value("name").toString();
		research.id = list[inc];

		//check the name hasn't been used already
		ASSERT_OR_RETURN(false, checkResearchName(&research, inc), "Research name '%s' used already", getName(&research));

		research.ref = REF_RESEARCH_START + inc;

		research.results = ini.json("results", QJsonArray());

		//set subGroup icon
		QString subGroup = ini.value("subgroupIconID", "").toString();
		if (subGroup.compare("") != 0)
		{
			research.subGroup = setIconID(subGroup.toUtf8().data(), getName(&research));
		}
		else
		{
			research.subGroup = NO_RESEARCH_ICON;
		}

		//set key topic
		unsigned int keyTopic = ini.value("keyTopic", 0).toUInt();
		ASSERT(keyTopic <= 1, "Invalid keyTopic for research topic - '%s' ", getName(&research));
		if (keyTopic <= 1)
		{
			research.keyTopic = ini.value("keyTopic", 0).toUInt();
		}
		else
		{
			research.keyTopic = 0;
		}

		//set tech code
		UBYTE techCode = ini.value("techCode", 0).toUInt();
		ASSERT(techCode <= 1, "Invalid tech code for research topic - '%s' ", getName(&research));
		if (techCode == 0)
		{
			research.techCode = TC_MAJOR;
		}
		else
		{
			research.techCode = TC_MINOR;
		}

		//set the iconID
		QString iconID = ini.value("iconID", "").toString();
		if (iconID.compare("") != 0)
		{
			research.iconID = setIconID(iconID.toUtf8().data(), getName(&research));
		}
		else
		{
			research.iconID = NO_RESEARCH_ICON;
		}

		//get the IMDs used in the interface
		QString statID = ini.value("statID", "").toString();
		research.psStat = NULL;
		if (statID.compare("") != 0)
		{
			//try find the structure stat with given name
			research.psStat = getCompStatsFromName(statID);
			ASSERT_OR_RETURN(false, research.psStat, "Could not find stats for %s research %s", statID.toUtf8().constData(), getName(&research));
		}

		QString imdName = ini.value("imdName", "").toString();
		if (imdName.compare("") != 0)
		{
			research.pIMD = modelGet(imdName);
			ASSERT(research.pIMD != NULL, "Cannot find the research PIE '%s' for record '%s'", imdName.toUtf8().data(), getName(&research));
		}

		QString imdName2 = ini.value("imdName2", "").toString();
		if (imdName2.compare("") != 0)
		{
			research.pIMD2 = modelGet(imdName2);
			ASSERT(research.pIMD2 != NULL, "Cannot find the 2nd research '%s' PIE for record '%s'", imdName2.toUtf8().data(), getName(&research));
		}

		QString msgName = ini.value("msgName", "").toString();
		if (msgName.compare("") != 0)
		{
			//check its a major tech code
			ASSERT(research.techCode == TC_MAJOR, "This research should not have a message associated with it, '%s' the message will be ignored!", getName(&research));
			if (research.techCode == TC_MAJOR)
			{
				research.pViewData = getViewData(msgName.toUtf8().data());
			}
		}

		//set the researchPoints
		unsigned int resPoints = ini.value("researchPoints", 0).toUInt();
		ASSERT_OR_RETURN(false, resPoints <= UWORD_MAX, "Research Points too high for research topic - '%s' ", getName(&research));
		research.researchPoints = resPoints;

		//set the research power
		unsigned int resPower = ini.value("researchPower", 0).toUInt();
		ASSERT_OR_RETURN(false, resPower <= UWORD_MAX, "Research Power too high for research topic - '%s' ", getName(&research));
		research.researchPower = resPower;

		//rememeber research pre-requisites for futher checking
		preResearch[inc] = ini.value("requiredResearch").toStringList();

		//set components results
		QStringList compResults = ini.value("resultComponents").toStringList();
		for (int j = 0; j < compResults.size(); j++)
		{
			QString compID = compResults[j].trimmed();
			COMPONENT_STATS *pComp = getCompStatsFromName(compID);
			if (pComp != NULL)
			{
				research.componentResults.push_back(pComp);
			}
			else
			{
				ASSERT(false, "Invalid item '%s' in list of result components of research '%s' ", compID.toUtf8().constData(), getName(&research));
			}
		}

		//set replaced components
		QStringList replacedComp = ini.value("replacedComponents").toStringList();
		for (int j = 0; j < replacedComp.size(); j++)
		{
			//read pair of components oldComponent:newComponent
			QStringList pair = replacedComp[j].split(':');
			ASSERT(pair.size() == 2, "Invalid item '%s' in list of replaced components of research '%s'. Required format: 'oldItem:newItem, item1:item2'", replacedComp[j].toUtf8().constData(), getName(&research));
			if (pair.size() != 2)
			{
				continue; //skip invalid entries
			}
			QString oldCompID = pair[0].trimmed();
			QString newCompID = pair[1].trimmed();
			COMPONENT_STATS *oldComp = getCompStatsFromName(oldCompID);
			if (oldComp == NULL)
			{
				ASSERT(false, "Invalid item '%s' in list of replaced components of research '%s'. Wrong component code.", oldCompID.toUtf8().constData(), getName(&research));
				continue;
			}
			COMPONENT_STATS *newComp = getCompStatsFromName(newCompID);
			if (newComp == NULL)
			{
				ASSERT(false, "Invalid item '%s' in list of replaced components of research '%s'. Wrong component code.", newCompID.toUtf8().constData(), getName(&research));
				continue;
			}
			RES_COMP_REPLACEMENT replItem;
			replItem.pOldComponent = oldComp;
			replItem.pNewComponent = newComp;
			research.componentReplacement.push_back(replItem);
		}

		//set redundant components
		QStringList redComp = ini.value("redComponents").toStringList();
		for (int j = 0; j < redComp.size(); j++)
		{
			QString compID = redComp[j].trimmed();
			COMPONENT_STATS *pComp = getCompStatsFromName(compID);
			if (pComp == NULL)
			{
				ASSERT(false, "Invalid item '%s' in list of redundant components of research '%s' ", compID.toUtf8().constData(), getName(&research));
			}
			else
			{
				research.pRedArtefacts.push_back(pComp);
			}
		}

		//set result structures
		QStringList resStruct = ini.value("resultStructures").toStringList();
		for (int j = 0; j < resStruct.size(); j++)
		{
			QString strucID = resStruct[j].trimmed();
			int structIndex = getStructStatFromName(strucID.toUtf8().data());
			ASSERT(structIndex >= 0, "Invalid item '%s' in list of result structures of research '%s' ", strucID.toUtf8().constData(), getName(&research));
			if (structIndex >= 0)
			{
				research.pStructureResults.push_back(structIndex);
			}
		}

		//set required structures
		QStringList reqStruct = ini.value("requiredStructures").toStringList();
		for (int j = 0; j < reqStruct.size(); j++)
		{
			QString strucID = reqStruct[j].trimmed();
			int structIndex = getStructStatFromName(strucID.toUtf8().data());
			ASSERT(structIndex >= 0, "Invalid item '%s' in list of required structures of research '%s' ", strucID.toUtf8().constData(), getName(&research));
			if (structIndex >= 0)
			{
				research.pStructList.push_back(structIndex);
			}
		}

		//set redundant structures
		QStringList redStruct = ini.value("redStructures").toStringList();
		for (int j = 0; j < redStruct.size(); j++)
		{
			QString strucID = redStruct[j].trimmed();
			int structIndex = getStructStatFromName(strucID.toUtf8().data());
			ASSERT(structIndex >= 0, "Invalid item '%s' in list of redundant structures of research '%s' ", strucID.toUtf8().constData(), getName(&research));
			if (structIndex >= 0)
			{
				research.pRedStructs.push_back(structIndex);
			}
		}

		asResearch.push_back(research);
		ini.endGroup();
	}

	//Load and check research pre-requisites (need do it AFTER loading research items)
	for (int inc = 0; inc < asResearch.size(); inc++)
	{
		QStringList preRes = preResearch[inc];
		for (int j = 0; j < preRes.size(); j++)
		{
			QString resID = preRes[j].trimmed();
			RESEARCH *preResItem = getResearch(resID.toUtf8().constData());
			ASSERT(preResItem != NULL, "Invalid item '%s' in list of pre-requisites of research '%s' ", resID.toUtf8().constData(), getName(&asResearch[inc]));
			if (preResItem != NULL)
			{
				asResearch[inc].pPRList.push_back(preResItem->index);
			}
		}
	}

	return true;
}