Esempio n. 1
0
static QVariant fcnToReal( const QVariantList& values, QgsFeature* , QgsExpression* parent )
{
  return QVariant( getDoubleValue( values.at( 0 ), parent ) );
}
Esempio n. 2
0
ConnSettingsValue *IAPConfPrivate::variantToValue(const QVariant &variant)
{
    // Convert variant to ConnSettingsValue
    ConnSettingsValue *value = conn_settings_value_new();
    if (value == 0) {
        qWarning("IAPConf: Unable to create new ConnSettingsValue");
        return 0;
    }

    switch(variant.type()) {
        
    case QVariant::Invalid:
        value->type = CONN_SETTINGS_VALUE_INVALID;
        break;
    
    case QVariant::String: {
        char *valueStr = strdup(QSTRING_TO_CONST_CSTR(variant.toString()));
        value->type = CONN_SETTINGS_VALUE_STRING;
        value->value.string_val = valueStr;
        break;
    }
    
    case QVariant::Int:
        value->type = CONN_SETTINGS_VALUE_INT;
        value->value.int_val = variant.toInt();
        break;
    
    case QMetaType::Float:
    case QVariant::Double:
        value->type = CONN_SETTINGS_VALUE_DOUBLE;
        value->value.double_val = variant.toDouble();
        break;
    
    case QVariant::Bool:
        value->type = CONN_SETTINGS_VALUE_BOOL;
        value->value.bool_val = variant.toBool() ? 1 : 0;
        break;
    
    case QVariant::ByteArray: {
        QByteArray array = variant.toByteArray();
        value->type = CONN_SETTINGS_VALUE_BYTE_ARRAY;
        value->value.byte_array.len = array.size();
        value->value.byte_array.val = (unsigned char *)malloc(array.size());
        memcpy(value->value.byte_array.val, array.constData(), array.size());
        break;
    }
    
    case QVariant::List: {
        QVariantList list = variant.toList();
        ConnSettingsValue **list_val = (ConnSettingsValue **)malloc(
            (list.size() + 1) * sizeof(ConnSettingsValue *));

        for (int idx = 0; idx < list.size(); idx++) {
            list_val[idx] = variantToValue(list.at(idx));
        }
        list_val[list.size()] = 0;

        value->type = CONN_SETTINGS_VALUE_LIST;
        value->value.list_val = list_val;
        break;
    }
    
    default:
        qWarning("IAPConf: Can not handle QVariant of type %d",
                 variant.type());
        conn_settings_value_destroy(value);
        return 0;
    }

    return value;
}
Esempio n. 3
0
void Card::on_invoked(const bb::system::InvokeRequest& request)
{
    qDebug() << "==== Card::onInvoked() START ====";

    emit load_configuration();

    QVariantMap metadata    = request.metadata();
    QString source          = request.source().installId() + " - " + request.source().groupId();
    QString listId          = QString::number(request.listId());
    QString action          = request.action();
    QString target          = request.target();
    QString uri             = request.uri().toString();
    QString data            = QString::fromUtf8(request.data());

    qDebug() << "==== Card::onInvoked(): action: " << action << data << ", uri: " << uri;

    if(action == "bb.action.VIEW")
    {
        JsonDataAccess jda;
        QVariantMap objectMap   = (jda.loadFromBuffer(data)).toMap();
        QVariantMap itemMap     = objectMap["attributes"].toMap();
        QString messageID1      = itemMap["messageid"].toString();
        QString sourceID1       = itemMap["sourceId"].toString();

        QString itemsFromJSON   = Utilities::get_string_from_file("data/hub_items.json");

        QVariantList itemsFromJSONList = jda.loadFromBuffer(itemsFromJSON).toList();

        qDebug() << "**** Card::onInvoked: itemsFromJSONList: " << itemsFromJSONList.size() << ", sourceId1: " << sourceID1 << ", messageID1: " << messageID1;

        for(int index = 0; index < itemsFromJSONList.size(); index++)
        {
            QVariantMap attributes    = itemsFromJSONList.at(index).toMap();
            QString pageName          = attributes["thePage"].toString();
            QString theData           = attributes["theData"].toString();
            QString sourceID2         = attributes["sourceId"].toString();

            qDebug() << "**** Card::onInvoked: thePage" << pageName << ", theData: " << theData << ", sourceId2: " << sourceID2;

            if (sourceID2 == messageID1 || sourceID2 == sourceID1)
            {
                InvokeRequest request2;
                request2.setTarget("com.nemory.Insta10HeadlessService");
                request2.setAction("bb.action.MARKREAD");
                request2.setMimeType("hub/item");
                request2.setUri(QUrl("pim:"));

                QByteArray bytes;
                jda.saveToBuffer(objectMap, &bytes);
                request2.setData(bytes);

                InvokeTargetReply *reply = _invoke_manager->invoke(request2);

                if (!reply)
                {
                    qDebug() << "**** FAILED Card::onInvoked: " << reply->errorCode();
                    reply->deleteLater();
                }

                QmlDocument *pageDocument  = QmlDocument::create("asset:///pages/" + pageName).parent(this);
                _page = pageDocument->createRootObject<Page>();
                _page->setProperty("is_card", true);
                //_page->setActionBarVisibility((getSetting("backButton", "false") == "false") ? ChromeVisibility::Hidden : ChromeVisibility::Default);
                _navigation_pane->push(_page);
                Application::instance()->setScene(_navigation_pane);

                emit initialize_card();

                emit opened_item(attributes, theData);

                break;
            }
        }

        jda.deleteLater();
    }
    else if(action == "bb.action.COMPOSE")
    {

    }
    else if(action == "bb.action.SHARE")
    {

        startHeadless();
    }
    else
    {
        startHeadless();
    }
}
Esempio n. 4
0
void QxPreferences::restore(QSettings* settings, int selection)
{
	blockSignals(true);
	settings->beginGroup("preferences");
	
	Ref<ViewMetrics, Owner> editorDefaults = Edit::defaultMetrics();
	Ref<ViewMetrics, Owner> terminalDefaults = QxVideoTerminal::defaultMetrics();
	
	if ((selection & Editor) != 0) {
		settings->beginGroup("editor");
		setFontFamily(editor_->font_, settings->value("font"), editorDefaults->font_);
		editor_->fontSize_->setValue(settings->value("fontSize", editorDefaults->font_.pixelSize()).toInt());
		editor_->fontAntialiasing_->setChecked(settings->value("fontAntialiasing", editorDefaults->fontAntialiasing_).toBool());
		editor_->subpixelAntialiasing_->setChecked(!settings->value("speedOverQuality", !editorDefaults->subpixelAntialiasing_).toBool());
		editor_->lineSpacing_->setValue(settings->value("lineSpacing", editorDefaults->lineSpacing_).toInt());
		editor_->showLineNumbers_->setChecked(settings->value("showLineNumbers", editorDefaults->showLineNumbers_).toBool());
		editor_->showWhitespace_->setChecked(settings->value("showWhitespace", editorDefaults->showWhitespace_).toBool());
		editor_->autoIndent_->setChecked(settings->value("autoIndent", true).toBool());
		{
			bool on = settings->value("tabIndentMode", true).toBool();
			if (on)
				editor_->tabIndentMode_->setChecked(true);
			else
				editor_->spaceIndentMode_->setChecked(true);
		}
		editor_->tabWidth_->setValue(settings->value("tabWidth", editorDefaults->tabWidth_).toInt());
		editor_->indentWidth_->setValue(settings->value("indentWidth", editorDefaults->tabWidth_).toInt());
		settings->endGroup();
	}
	
	if ((selection & Terminal) != 0) {
		settings->beginGroup("terminal");
		setFontFamily(terminal_->font_, settings->value("font"), terminalDefaults->font_);
		terminal_->fontSize_->setValue(settings->value("fontSize", terminalDefaults->font_.pixelSize()).toInt());
		terminal_->fontAntialiasing_->setChecked(settings->value("fontAntialiasing", terminalDefaults->fontAntialiasing_).toBool());
		terminal_->subpixelAntialiasing_->setChecked(!settings->value("speedOverQuality", !terminalDefaults->subpixelAntialiasing_).toBool());
		terminal_->lineSpacing_->setValue(settings->value("lineSpacing", terminalDefaults->lineSpacing_).toInt());
		terminal_->endlessLogging_->setChecked(settings->value("endlessLogging", true).toBool());
		terminal_->numberOfLines_->setValue(settings->value("numberOfLines", terminal_->numberOfLines_->maximum()).toInt());
		{
			Ref<Palette> palette = paletteManager_->paletteByName(settings->value("palette", "Default").toString());
			for (int i = 0, n = paletteIndices_.length(); i < n; ++i)
				if (paletteManager_->paletteByIndex(paletteIndices_.at(i)) == palette)
					terminal_->palette_->setCurrentIndex(i);
		}
		{
			QString title = settings->value("title", "$FG").toString();
			int titleIndex = terminal_->title_->findText(title);
			if (titleIndex != -1) terminal_->title_->setCurrentIndex(titleIndex);
			else terminal_->title_->setEditText(title);
		}
		settings->endGroup();
	}
	
	if ((selection & Printing) != 0) {
		settings->beginGroup("printing");
		setFontFamily(printing_->font_, settings->value("font"), editorDefaults->font_);
		printing_->fontSize_->setValue(settings->value("fontSize", 10).toInt());
		printing_->fontAntialiasing_->setChecked(settings->value("fontAntialiasing", editorDefaults->fontAntialiasing_).toBool());
		printing_->lineSpacing_->setValue(settings->value("lineSpacing", 1).toInt());
		printing_->showLineNumbers_->setChecked(settings->value("showLineNumbers", editorDefaults->showLineNumbers_).toBool());
		printing_->showWhitespace_->setChecked(settings->value("showWhitespace", false).toBool());
		printing_->pageHeader_->setChecked(settings->value("printingPageHeader", true).toBool());
		printing_->pageBorder_->setChecked(settings->value("printingPageBorder", true).toBool());
		settings->endGroup();
	}
	
	if ((selection & Theme) != 0) {
		settings->beginGroup("theme");
		if (settings->contains("activeTheme"))
			themesView_->setCurrentIndex(themesView_->model()->index(themeManager_->themeIndex(settings->value("activeTheme").toString()), 0));
		else
			themesView_->setCurrentIndex(themesView_->model()->index(themeManager_->defaultThemeIndex(), 0));
		settings->endGroup();
	}
	
	if ((selection & Commands) != 0) {
		settings->beginGroup("commands");
		{
			QVariantList list = settings->value("commands", QVariantList()).toList();
			commandsList_->clear();
			for (int i = 0; i < list.size(); ++i) {
				QxCommand* cmd = new QxCommand(parent());
				connect(cmd, SIGNAL(triggered(QxCommand*)), this, SIGNAL(commandTriggered(QxCommand*)));
				QAction* action = new QAction(parent());
				// parentWidget()->addAction(action);
				cmd->assignAction(action);
				QVariantList al = list.at(i).toList();
				cmd->restore(list.at(i).toList());
				cmd->updateAction();
				commandsList_->append(cmd);
			}
			// commands_->view_->resizeColumnToContents(0);
		}
		settings->endGroup();
	}
Esempio n. 5
0
QVariant FeedsViewModel::data(const QVariantList &indexPath) {
	return m_resultList.at(indexPath.at(0).toInt());
}
Esempio n. 6
0
void MarkerUtils::textValueToString(const QVariantList &value, QString &string) {
    string += value.at(0).toString() + " ";
    string += value.at(1).toString();
}
Esempio n. 7
0
/*! id is the object's row in the database (for updates), or 0 (for inserts).
 table is the database table name
 colNames is a list of the column names that the values will be inserted under
 values is a list of QVariants that provide the values to insert.
 (Note that the const& arguments are designed to prevent memory copies, so this should be fast.)
 Return value: (IMPORTANT) returns the id of the row that was inserted into or updated, or 0 on failure.
 When inserting new objects, make sure to set their id to the return value afterwards, otherwise they will be duplicated on next insert.

 Note: This is equivalent to an SQL "INSERT OR REPLACE" (or "REPLACE", in MySQL) command. If a row with \c id exists, it will be replaced completely, so you need to specify ALL column values. To change just some column values, use update().
*/
int AMDatabase::insertOrUpdate(int id, const QString& table, const QStringList& colNames, const QVariantList& values) {

	QSqlDatabase db = qdb();

	if(!db.isOpen()) {
		AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -2, "Could not save to database. (Database is not open.)"));
		return 0;
	}


	// Create the list of columns:
	QString cols = colNames.join(", ");	// this will become something like "name, number, sampleName, comments, startTime"
	QString colPlaceholders;
	for(int i=0; i<colNames.count()+1; i++)
		colPlaceholders.append("?, ");
	colPlaceholders.chop(2);	// remove trailing ", " from "?, ?, ?, ?, ...?, "
	// placeholders will become something like "?, ?, ?, ?, ?, ?", with enough ? for each column name + the id

	// Prepare the query. Todo: sanitize column names and table name. (Can't use binding because it's not an expression here)
	QSqlQuery query(db);
	query.prepare(QString("INSERT OR REPLACE INTO %1 (id, %2) VALUES (%3)").arg(table).arg(cols).arg(colPlaceholders));

	// If we have a unique id already, use that (This will update ourself in the DB)
	if(id > 0)
		query.bindValue(0, id);
	// Otherwise, use NULL for the id. (This will create a new one.)
	else
		query.bindValue(0, QVariant(QVariant::Int));

	// Bind remaining values
	for(int i=0; i<colNames.count(); i++)
		query.bindValue(i+1, values.at(i));

	// Run query. Query failed?
	if(!execQuery(query)) {
		query.finish();	// make sure that sqlite lock is released before emitting signals
		AMErrorMon::report(AMErrorReport(this, AMErrorReport::Alert, -3, QString("database save failed. Could not execute query (%1). The SQL reply was: %2").arg(query.executedQuery()).arg(query.lastError().text())));
		return 0;
	}
	// Query succeeded.

	// If we don't have one, set the unique id for this object (now that the database has established it)
	if(id < 1) {
		QVariant lastId = query.lastInsertId();
		query.finish();	// make sure that sqlite lock is released before emitting signals
		if(lastId.isValid()) {
			emit created(table, lastId.toInt());
			return lastId.toInt();
		}
		else {
			query.finish();	// make sure that sqlite lock is released before emitting signals
			AMErrorMon::report(AMErrorReport(this, AMErrorReport::Debug, -4, "Database save completed, but could not get the last id after insert. This should never happen."));
			emit updated(table, -1);
			return 0;
		}
	}
	// else (we already had an id, which was used for successful insert:
	else {
		query.finish();	// make sure that sqlite lock is released before emitting signals
		emit updated(table, id);
		return id;
	}


}
Esempio n. 8
0
void QDocumentServerContentStorePrivate::invokeSignal( const QDocumentServerMessage &message )
{
    const QByteArray signature = message.signature();
    const QVariantList arguments = message.arguments();

    if( signature == "insertContentIntoSet(int,int,int)" )
    {
        Q_ASSERT( arguments.count() == 3 );

        QDocumentServerContentSetEngine *contentSet = contentSets.value( arguments[ 0 ].toInt(), 0 );

        if( contentSet )
        {
            contentSet->insertContent( arguments[ 1 ].toInt(), arguments[ 2 ].toInt() );
        }
    }
    else if( signature == "removeContentFromSet(int,int,int)" )
    {
        Q_ASSERT( arguments.count() == 3 );

        QDocumentServerContentSetEngine *contentSet = contentSets.value( arguments[ 0 ].toInt(), 0 );

        if( contentSet )
        {
            contentSet->removeContent( arguments[ 1 ].toInt(), arguments[ 2 ].toInt() );
        }
    }
    else if( signature == "contentSetChanged(int,int,int)" )
    {
        Q_ASSERT( arguments.count() == 3 );

        QDocumentServerContentSetEngine *contentSet = contentSets.value( arguments[ 0 ].toInt(), 0 );

        if( contentSet )
        {
            contentSet->refreshContent( arguments[ 1 ].toInt(), arguments[ 2 ].toInt() );
        }
    }
    else if( signature == "contentSetUpdateStarted(int)" )
    {
        Q_ASSERT( arguments.count() == 1 );

        QDocumentServerContentSetEngine *contentSet = contentSets.value( arguments[ 0 ].toInt(), 0 );

        if( contentSet )
        {
            contentSet->updateStarted();
        }
    }
    else if( signature == "contentSetUpdateFinished(int)" )
    {
        Q_ASSERT( arguments.count() == 1 );

        QDocumentServerContentSetEngine *contentSet = contentSets.value( arguments.at( 0 ).toInt(), 0 );

        if( contentSet )
        {
            contentSet->updateFinished();
        }
    }
}
Esempio n. 9
0
bool LoadTagsResponseJSON::parseJson(const QByteArray &data)
{
  clearContainers();

  QJson::Parser parser;
  bool ok;
  QVariantMap result = parser.parse(data, &ok).toMap();

  if (!ok) return false;

  result["errno"].toInt(&ok);
  if (!ok) return false;
  m_errno = result["errno"].toInt(&ok);

  QVariantMap rss = result["rss"].toMap();
  QVariantMap channelVariant = rss["channels"].toMap();
  QVariantList channelsList = channelVariant["items"].toList();
  int size = channelsList.size();

  for (int i = 0; i < size; i++)
  {
    QVariantMap channelDesc = channelsList.at(i).toMap();
    QVariantList markList = channelDesc["items"].toList();
    QString channelName = channelDesc["name"].toString();

    QSharedPointer<Channel> channel(new JsonChannel(channelName,"dummy channel[LoadTagsResponse]"));

    for(int j=0; j<markList.size(); j++)
    {
      QVariantMap markMap = markList.at(j).toMap();

      QString title = markMap["title"].toString();
      QString link = markMap["link"].toString();
      QString description = markMap["description"].toString();
      double altitude = markMap["altitude"].toString().toDouble(&ok);
      if (!ok) return false;
      double latitude = markMap["latitude"].toString().toDouble(&ok);
      if (!ok) return false;
      double longitude = markMap["longitude"].toString().toDouble(&ok);
      if (!ok) return false;

      QString userName = markMap["user"].toString();
      QString timeStr =  markMap["pubDate"].toString();
      QDateTime time = QDateTime::fromString(timeStr, "dd MM yyyy HH:mm:ss.zzz");

      QVector<QSharedPointer<common::User> > v = m_usersContainer->vector();
      QSharedPointer<common::User> user(new JsonUser(userName));
      m_usersContainer->push_back(user);

      QSharedPointer<JsonDataMark> newMark(new JsonDataMark(altitude,
        latitude,
        longitude,
        title,
        description,
        link,
        time));
      newMark->setUser(user);
      m_hashMap.insert(channel, newMark);
    }
  }
  return true;
}
Esempio n. 10
0
  void TabEdit::updateEditWidget()
  {
    if (!m_isInitialized) {
      return;
    }

    QStringList filenames = getTemplateNames();
    if (filenames.isEmpty()) {
      ui_list_edit->setVisible(false);
      ui_edit_edit->setVisible(false);

      if (m_opt->optimizer()->getNumberOfOptSteps() !=
          ui_list_optStep->count()) {
        this->populateOptStepList();
      }
      return;
    }

    int templateInd = ui_combo_templates->currentIndex();
    QString templateName = ui_combo_templates->currentText();
    Q_ASSERT(templateInd >= 0 && templateInd < filenames.size());
    Q_ASSERT(templateName.compare(filenames.at(templateInd)) == 0);

    if (m_opt->optimizer()->getIDString().compare("VASP") == 0 &&
        templateName.compare("POTCAR") == 0) {

      if (m_opt->optimizer()->getNumberOfOptSteps() !=
          ui_list_optStep->count()) {
        populateOptStepList();
      }

      int optStepIndex = ui_list_optStep->currentRow();
      Q_ASSERT(optStepIndex >= 0 &&
               optStepIndex < m_opt->optimizer()->getNumberOfOptSteps());

      // Display appropriate entry widget.
      ui_list_edit->setVisible(true);
      ui_edit_edit->setVisible(false);

      XtalOpt *xtalopt = qobject_cast<XtalOpt*>(m_opt);

      VASPOptimizer *vopt = qobject_cast<VASPOptimizer*>(m_opt->optimizer());
      // Do we need to update the POTCAR info?
      if (!vopt->POTCARInfoIsUpToDate(xtalopt->comp.keys())) {
        if (!generateVASP_POTCAR_info()) {
          return;
        }
        vopt->buildPOTCARs();
      }

      // Build list in GUI
      // "POTCAR info" is of type
      // QList<QHash<QString, QString> >
      // e.g. a list of hashes containing
      // [atomic symbol : pseudopotential file] pairs
      QVariantList potcarInfo = m_opt->optimizer()->getData("POTCAR info").toList();
      QList<QString> symbols = potcarInfo.at(optStepIndex).toHash().keys();
      qSort(symbols);
      ui_list_edit->clear();
      for (int i = 0; i < symbols.size(); i++) {
        ui_list_edit->addItem(tr("%1: %2")
                               .arg(symbols.at(i), 2)
                               .arg(potcarInfo.at(optStepIndex).toHash()[symbols.at(i)].toString()));
      }
    }
    // Default for all templates using text entry
    else {
      AbstractEditTab::updateEditWidget();
    }
  }
Esempio n. 11
0
void packDataValue(QVariant_ *var, DataValue *value)
{
    QVariant *qvar = reinterpret_cast<QVariant *>(var);

    // Some assumptions are made below regarding the size of types.
    // There's apparently no better way to handle this since that's
    // how the types with well defined sizes (qint64) are mapped to
    // meta-types (QMetaType::LongLong).
    switch ((int)qvar->type()) {
    case QVariant::Invalid:
        value->dataType = DTInvalid;
        break;
    case QMetaType::QUrl:
        *qvar = qvar->value<QUrl>().toString();
        // fallthrough
    case QMetaType::QString:
        {
            value->dataType = DTString;
            QByteArray ba = qvar->toByteArray();
            *(char**)(value->data) = local_strdup(ba.constData());
            value->len = ba.size();
            break;
        }
    case QMetaType::Bool:
        value->dataType = DTBool;
        *(qint8*)(value->data) = (qint8)qvar->toInt();
        break;
    case QMetaType::LongLong:
        // Some of these entries will have to be fixed when handling platforms
        // where sizeof(long long) != 8 or sizeof(int) != 4.
        value->dataType = DTInt64;
        *(qint64*)(value->data) = qvar->toLongLong();
        break;
    case QMetaType::ULongLong:
        value->dataType = DTUint64;
        *(quint64*)(value->data) = qvar->toLongLong();
        break;
    case QMetaType::Int:
        value->dataType = DTInt32;
        *(qint32*)(value->data) = qvar->toInt();
        break;
    case QMetaType::UInt:
        value->dataType = DTUint32;
        *(quint32*)(value->data) = qvar->toUInt();
        break;
    case QMetaType::VoidStar:
        value->dataType = DTUintptr;
        *(uintptr_t*)(value->data) = (uintptr_t)qvar->value<void *>();
        break;
    case QMetaType::Double:
        value->dataType = DTFloat64;
        *(double*)(value->data) = qvar->toDouble();
        break;
    case QMetaType::Float:
        value->dataType = DTFloat32;
        *(float*)(value->data) = qvar->toFloat();
        break;
    case QMetaType::QColor:
        value->dataType = DTColor;
        *(unsigned int*)(value->data) = qvar->value<QColor>().rgba();
        break;
    case QMetaType::QVariantList:
        {
            QVariantList varlist = qvar->toList();
            int len = varlist.size();
            DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
            for (int i = 0; i < len; i++) {
                packDataValue((void*)&varlist.at(i), &dvlist[i]);
            }
            value->dataType = DTValueList;
            value->len = len;
            *(DataValue**)(value->data) = dvlist;
        }
        break;
    case QMetaType::QVariantMap:
        {
            QVariantMap varmap = qvar->toMap();
            int len = varmap.size() * 2;
            DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
            QMapIterator<QString, QVariant> it(varmap);
            for (int i = 0; i < len; i += 2) {
                if (!it.hasNext()) {
                    panicf("QVariantMap mutated during iteration");
                }
                it.next();
                QVariant key = it.key();
                QVariant val = it.value();
                packDataValue((void*)&key, &dvlist[i]);
                packDataValue((void*)&val, &dvlist[i+1]);
            }
            value->dataType = DTValueMap;
            value->len = len;
            *(DataValue**)(value->data) = dvlist;
        }
        break;
    default:
        if (qvar->type() == (int)QMetaType::QObjectStar || qvar->canConvert<QObject *>()) {
            QObject *qobject = qvar->value<QObject *>();
            GoValue *goValue = dynamic_cast<GoValue *>(qobject);
            if (goValue) {
                value->dataType = DTGoAddr;
                *(uintptr_t*)(value->data) = goValue->ref;
                break;
            }
            GoPaintedValue *goPaintedValue = dynamic_cast<GoPaintedValue *>(qobject);
            if (goPaintedValue) {
                value->dataType = DTGoAddr;
                *(uintptr_t*)(value->data) = goPaintedValue->ref;
                break;
            }
            value->dataType = DTObject;
            *(void **)(value->data) = qobject;
            break;
        }
        {
            QQmlListReference ref = qvar->value<QQmlListReference>();
            if (ref.isValid() && ref.canCount() && ref.canAt()) {
                int len = ref.count();
                DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
                QVariant elem;
                for (int i = 0; i < len; i++) {
                    elem.setValue(ref.at(i));
                    packDataValue(&elem, &dvlist[i]);
                }
                value->dataType = DTValueList;
                value->len = len;
                *(DataValue**)(value->data) = dvlist;
                break;
            }
        }
        if (qstrncmp(qvar->typeName(), "QQmlListProperty<", 17) == 0) {
            QQmlListProperty<QObject> *list = reinterpret_cast<QQmlListProperty<QObject>*>(qvar->data());
            if (list->count && list->at) {
                int len = list->count(list);
                DataValue *dvlist = (DataValue *) malloc(sizeof(DataValue) * len);
                QVariant elem;
                for (int i = 0; i < len; i++) {
                    elem.setValue(list->at(list, i));
                    packDataValue(&elem, &dvlist[i]);
                }
                value->dataType = DTValueList;
                value->len = len;
                *(DataValue**)(value->data) = dvlist;
                break;
            }
        }
        panicf("unsupported variant type: %d (%s)", qvar->type(), qvar->typeName());
        break;
    }
}
Esempio n. 12
0
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);
}
Esempio n. 13
0
static QVariant fcnLength( const QVariantList& values, QgsFeature* , QgsExpression* parent )
{
  QString str = getStringValue( values.at( 0 ), parent );
  return QVariant( str.length() );
}
Esempio n. 14
0
static QVariant fcnToString( const QVariantList& values, QgsFeature* , QgsExpression* parent )
{
  return QVariant( getStringValue( values.at( 0 ), parent ) );
}
/**
  * timer is running with 50 ms speed
  */
void MutexKnobData::timerEvent(QTimerEvent *)
{
    double diff, repRate;
    char units[40];
    char fec[40];
    char dataString[1024];
    struct timeb now;

    if(blockProcess) return;

    ftime(&now);

    //qDebug() << "============================================";
    for(int i=0; i < GetMutexKnobDataSize(); i++) {
        knobData *kPtr = (knobData*) &KnobData[i];

        if(kPtr->index != -1) {
            diff = ((double) now.time + (double) now.millitm / (double)1000) -
                    ((double) kPtr->edata.lastTime.time + (double) kPtr->edata.lastTime.millitm / (double)1000);
            if(kPtr->edata.repRate < 1) repRate = 1;
            else repRate = kPtr->edata.repRate;
        }

        // update all graphical items for this soft pv when a value changes
        if(kPtr->index != -1 && kPtr->soft && (diff >= (1.0/(double)repRate))) {
            int indx;
            //qDebug() << "I am a soft channel" << kPtr->pv << kPtr->dispName << kPtr->edata.rvalue << kPtr->index;
            // get for this soft pv the index of the corresponding caCalc into the knobData array where the data were updated
            if(getSoftPV(kPtr->pv, &indx, (QWidget*) kPtr->thisW)) {
                // get value from (updated) QMap variable list
                knobData *ptr = (knobData*) &KnobData[indx];
                kPtr->edata.rvalue = ptr->edata.rvalue;
                kPtr->edata.fieldtype = caDOUBLE;
                kPtr->edata.connected = true;
                kPtr->edata.accessW = true;
                kPtr->edata.accessR = true;
                //increase monitor count when value has changed
                if(kPtr->edata.oldsoftvalue != ptr->edata.rvalue) {
                    //qDebug() << kPtr->pv << kPtr->dispName << "will be updated with value=" << ptr->edata.rvalue << "from" << ptr->pv << "index=" << ptr->index << "oldvalue=" << kPtr->edata.oldsoftvalue;
                    kPtr->edata.monitorCount++;
                }

                // when any monitors for calculation increase monitorcount
                QWidget *w1 =  (QWidget*) kPtr->dispW;
                QVariant var = w1->property("MonitorList");
                QVariantList list = var.toList();
                if(list.size() > 0) {
                    int nbMonitors = list.at(0).toInt();
                    if(nbMonitors > 0) {
                        kPtr->edata.monitorCount++;
                    }
                }

                kPtr->edata.oldsoftvalue = ptr->edata.rvalue;
                QWidget *ww = (QWidget *)kPtr->dispW;
                if (caTextEntry *widget = qobject_cast<caTextEntry *>(ww)) {
                    widget->setAccessW(kPtr->edata.accessW);
                }
            }
        }

        // use specified repetition rate (normally 5Hz)
        if( ((kPtr->index != -1) && (kPtr->edata.monitorCount > kPtr->edata.displayCount) && (diff >= (1.0/(double)repRate)))){
            /*
            printf("<%s> index=%d mcount=%d dcount=%d value=%f datasize=%d valuecount=%d\n", kPtr->pv, kPtr->index, kPtr->edata.monitorCount,
                                                                      kPtr->edata.displayCount, kPtr->edata.rvalue,
                                                                      kPtr->edata.dataSize, kPtr->edata.valueCount);
*/
            if((myUpdateType == UpdateTimed) || kPtr->soft) {
                QMutexLocker locker(&mutex);
                int index = kPtr->index;
                QWidget *dispW = (QWidget*) kPtr->dispW;
                dataString[0] = '\0';
                strcpy(units, kPtr->edata.units);
                strcpy(fec, kPtr->edata.fec);
                int caFieldType= kPtr->edata.fieldtype;

                if((caFieldType == DBF_STRING || caFieldType == DBF_ENUM || caFieldType == DBF_CHAR) && kPtr->edata.dataB != (void*) 0) {
                    if(kPtr->edata.dataSize < 1024) {
                        memcpy(dataString, (char*) kPtr->edata.dataB, kPtr->edata.dataSize);
                        dataString[kPtr->edata.dataSize] = '\0';
                    } else {
                        memcpy(dataString, (char*) kPtr->edata.dataB, 1024);
                        dataString[1023] = '\0';
                    }
                }

                kPtr->edata.displayCount = kPtr->edata.monitorCount;
                locker.unlock();
                UpdateWidget(index, dispW, units, fec, dataString, KnobData[index]);
                kPtr->edata.lastTime = now;
                kPtr->edata.initialize = false;
                displayCount++;
            }

        } else if ((kPtr->index != -1)  && (diff >= (1.0/(double)repRate))) {
            if( (!kPtr->edata.connected)) {
                QMutexLocker locker(&mutex);
                bool displayIt = false;
                units[0] = '\0';
                fec[0] = '\0';
                dataString[0] = '\0';
                int index = kPtr->index;
                // brake unconnected displays
                if(kPtr->edata.unconnectCount == 0) {
                    kPtr->edata.displayCount = kPtr->edata.monitorCount;
                    kPtr->edata.lastTime = now;
                    displayIt = true;
                }
                kPtr->edata.unconnectCount++;
                if(kPtr->edata.unconnectCount == 10) kPtr->edata.unconnectCount=0;
                locker.unlock();
                if(displayIt) UpdateWidget(index, (QWidget*) kPtr->dispW, units, fec, dataString, KnobData[index]);
            }
        }
    }
}
Esempio n. 16
0
//! [1]
void NetworkBus::onBusLineFinished(QNetworkReply* reply){
	if(reply->error() != QNetworkReply::NoError){
		m_error = QString::fromUtf8("线路数据请求错误,请检查网络后重试!");
		onError();
		reply->deleteLater();
		return;
	}else{
		JsonDataAccess jda; // at are you
		const QVariant qtData = jda.loadFromBuffer(reply->readAll());
		// TODO if qtData has some error

		const QVariantMap map = qtData.toMap();
		const QString msg = map.values("msg").value(0).toString();
		const QString success = map.values("success").value(0).toString();
		if(success != "true" || msg != "ok"){
			m_error = QString::fromUtf8("线路数据返回不成功,请检查网络后重试!");
			onError();
			reply->deleteLater();
			return;
		}
		//

		const QVariantList data = map["data"].toList();
		if(data.isEmpty() || data.length() == 0){
			m_error = QString::fromUtf8("未查询到该趟公交车数据!");
			onError();
			reply->deleteLater();
			return ;
		}
		QString result = "";
		for(int i=0;i<data.length();i++){
			const QVariantMap iMap = data.at(i).toMap();
			busline *bus = new busline;
			bus->setBeginTime(iMap.value("begin_time").toString());
			bus->setEndTime(iMap.value("end_time").toString());
			bus->setId(iMap.value("id").toString());
			bus->setStartStation(iMap.value("start_station").toString());
			bus->setEndStation(iMap.value("end_station").toString());
			bus->setPrice(iMap.value("price").toString());
			bus->setLineName(iMap.value("line_name").toString());
			bus->setIsOpen(iMap.value("isopen").toInt());//1
			bus->setDir(iMap.value("dir").toInt());//0/1
			bus->setCityId(m_city_id);
			if(bus->getIsOpen() == 0){
				m_error = QString::fromUtf8("本线路暂未开通手机电子站牌。敬请期待!");
				break;
			}
			if(iMap.value("dir").toInt() == 0){
				int record_id = dbService->findRecordId(m_city_id,bus->getLineName());
				if(record_id != 0){
					dbService->updateRecord(record_id);
				}else{
					dbService->createRecord(bus);
				}
				dbService->readRecords(m_city_id);
				emit localDataModelChanged();
				startLine = bus;
			}
			else endLine = bus;
		}
		reply->deleteLater();
		if(m_error.length() > 0){
			onError();
			emit buslineChanged();
			return;
		}

		this->get_subline_inf(startLine->getId());
	}
	emit buslineChanged();
}
Esempio n. 17
0
int Dataset::loadData(QString schema_file_name, QString data_file)
{
    // Reset Data
    vdata.clear();
    schema.clear();

    // CSV File Import

    FILE* f = fopen(data_file.toUtf8().data(), "r");

    if (! f)
        return DS_ERR_FILE_OPEN_FAILED;

    char line[1024];

    while(!feof(f))
    {
        memset(line, 0, 1024);
        fgets(line, 1024, f);
        if (strlen(line) < 2)
            continue;

        QString qline = line;
        QStringList row = qline.split(",");

        if (row.size() < 4)
            continue;

        vdata.append(row);
    }
    cerr << "DS::loadData() : " << vdata.size() << " records." << endl;
    fclose(f);

    // JSON Schema File Import

    QJson::Parser json_parser;
    QFile schemaFile(schema_file_name);

    if (! schemaFile.exists())
        return DS_ERR_FILE_OPEN_FAILED;

    bool json_ok;
    QVariant result = json_parser.parse(&schemaFile, &json_ok);

    if (! json_ok)
    {
        cerr << "Failed to parse schema json string." << endl;
        return DS_ERR_JSON_PARSE_FAILED;
    }

    // Copy values to field container
    QVariantList columns = result.toList();
    for (int i = 0; i < columns.size(); ++i) {
        QMap<QString, QVariant> col = columns.at(i).toMap();
//        QVariantMap jcol = ;

//        QMapIterator<QString, QVariant> i(jcol);
//        while (i.hasNext()) {
//            i.next();
//            col[i.key()] = i.value();
//        }

        this->schema.append(col);
    }

    return DS_ERR_SUCCEED;
}
Esempio n. 18
0
File: qgis.cpp Progetto: GeoCat/QGIS
uint qHash( const QVariant &variant )
{
  if ( !variant.isValid() || variant.isNull() )
    return std::numeric_limits<uint>::max();

  switch ( variant.type() )
  {
    case QVariant::Int:
      return qHash( variant.toInt() );
    case QVariant::UInt:
      return qHash( variant.toUInt() );
    case QVariant::Bool:
      return qHash( variant.toBool() );
    case QVariant::Double:
      return qHash( variant.toDouble() );
    case QVariant::LongLong:
      return qHash( variant.toLongLong() );
    case QVariant::ULongLong:
      return qHash( variant.toULongLong() );
    case QVariant::String:
      return qHash( variant.toString() );
    case QVariant::Char:
      return qHash( variant.toChar() );
    case QVariant::List:

#if QT_VERSION >= 0x050600
      return qHash( variant.toList() );
#else
      {
        QVariantList list = variant.toList();
        if ( list.isEmpty() )
          return -1;
        else
          return qHash( list.at( 0 ) );
      }
#endif
    case QVariant::StringList:
#if QT_VERSION >= 0x050600
      return qHash( variant.toStringList() );
#else
      {
        QStringList list = variant.toStringList();
        if ( list.isEmpty() )
          return -1;
        else
          return qHash( list.at( 0 ) );
      }
#endif
    case QVariant::ByteArray:
      return qHash( variant.toByteArray() );
    case QVariant::Date:
      return qHash( variant.toDate() );
    case QVariant::Time:
      return qHash( variant.toTime() );
    case QVariant::DateTime:
      return qHash( variant.toDateTime() );
    case QVariant::Url:
    case QVariant::Locale:
    case QVariant::RegExp:
      return qHash( variant.toString() );
    default:
      break;
  }

  return std::numeric_limits<uint>::max();
}
Esempio n. 19
0
QVariantMap QgsProcessingModelAlgorithm::parametersForChildAlgorithm( const QgsProcessingModelChildAlgorithm &child, const QVariantMap &modelParameters, const QVariantMap &results, const QgsExpressionContext &expressionContext ) const
{
  QVariantMap childParams;
  Q_FOREACH ( const QgsProcessingParameterDefinition *def, child.algorithm()->parameterDefinitions() )
  {
    if ( def->flags() & QgsProcessingParameterDefinition::FlagHidden )
      continue;

    if ( !def->isDestination() )
    {
      if ( !child.parameterSources().contains( def->name() ) )
        continue; // use default value

      QgsProcessingModelChildParameterSources paramSources = child.parameterSources().value( def->name() );

      QVariantList paramParts;
      Q_FOREACH ( const QgsProcessingModelChildParameterSource &source, paramSources )
      {
        switch ( source.source() )
        {
          case QgsProcessingModelChildParameterSource::StaticValue:
            paramParts << source.staticValue();
            break;

          case QgsProcessingModelChildParameterSource::ModelParameter:
            paramParts << modelParameters.value( source.parameterName() );
            break;

          case QgsProcessingModelChildParameterSource::ChildOutput:
          {
            QVariantMap linkedChildResults = results.value( source.outputChildId() ).toMap();
            paramParts << linkedChildResults.value( source.outputName() );
            break;
          }

          case QgsProcessingModelChildParameterSource::Expression:
          {
            QgsExpression exp( source.expression() );
            paramParts << exp.evaluate( &expressionContext );
            break;
          }
        }
      }
      if ( paramParts.count() == 1 )
        childParams.insert( def->name(), paramParts.at( 0 ) );
      else
        childParams.insert( def->name(), paramParts );

    }
    else
    {
      const QgsProcessingDestinationParameter *destParam = static_cast< const QgsProcessingDestinationParameter * >( def );

      // is destination linked to one of the final outputs from this model?
      bool isFinalOutput = false;
      QMap<QString, QgsProcessingModelOutput> outputs = child.modelOutputs();
      QMap<QString, QgsProcessingModelOutput>::const_iterator outputIt = outputs.constBegin();
      for ( ; outputIt != outputs.constEnd(); ++outputIt )
      {
        if ( outputIt->childOutputName() == destParam->name() )
        {
          QString paramName = child.childId() + ':' + outputIt.key();
          if ( modelParameters.contains( paramName ) )
          {
            QVariant value = modelParameters.value( paramName );
            if ( value.canConvert<QgsProcessingOutputLayerDefinition>() )
            {
              // make sure layout output name is correctly set
              QgsProcessingOutputLayerDefinition fromVar = qvariant_cast<QgsProcessingOutputLayerDefinition>( value );
              fromVar.destinationName = outputIt.key();
              value = QVariant::fromValue( fromVar );
            }

            childParams.insert( destParam->name(), value );
          }
          isFinalOutput = true;
          break;
        }
      }

      if ( !isFinalOutput )
      {
        // output is temporary

        // check whether it's optional, and if so - is it required?
        bool required = true;
        if ( destParam->flags() & QgsProcessingParameterDefinition::FlagOptional )
        {
          required = childOutputIsRequired( child.childId(), destParam->name() );
        }

        // not optional, or required elsewhere in model
        if ( required )
          childParams.insert( destParam->name(), destParam->generateTemporaryDestination() );
      }
    }
  }
Esempio n. 20
0
void LongPollPrivate::_q_on_data_recieved(const QVariant &response)
{
    Q_Q(LongPoll);
    auto data = response.toMap();

    if (data.contains("failed")) {
        q->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 LongPoll::MessageDeleted: {
            emit q->messageDeleted(update.value(1).toInt());
            break;
        }
        case LongPoll::MessageAdded: {
            //qDebug() << update;
            Message::Flags flags(update.value(2).toInt());
            Message message(client);
            int cid = update.value(3).toInt();
            //qDebug() << (flags & Message::FlagChat);
            //if (flags & Message::FlagChat)
            //  cid -= chatMessageOffset;
            message.setId(update.value(1).toInt());
            message.setFlags(flags);
            if (flags & Message::FlagOutbox) {
                message.setToId(cid);
                message.setFrom(client->me());
            } else {
                message.setFromId(cid);
                message.setTo(client->me());
            }
            message.setSubject(update.value(5).toString());
            message.setBody(update.value(6).toString());
            message.setDate(QDateTime::currentDateTime());
            emit q->messageAdded(message);
            break;
        }
        case LongPoll::MessageFlagsReplaced: {
            int id = update.value(1).toInt();
            int flags = update.value(2).toInt();
            int userId = update.value(3).toInt();
            emit q->messageFlagsReplaced(id, flags, userId);
            break;
        }
        case LongPoll::MessageFlagsReseted: { //TODO remove copy/paste
            int id = update.value(1).toInt();
            int flags = update.value(2).toInt();
            int userId = update.value(3).toInt();
            emit q->messageFlagsReseted(id, flags, userId);
            break;
        }
        case LongPoll::UserOnline:
        case LongPoll::UserOffline: {
            // WTF? Why VKontakte sends minus as first char of id?
            auto id = qAbs(update.value(1).toInt());
            Buddy::Status status;
            if (updateType == LongPoll::UserOnline)
                status = Buddy::Online;
            else
                status = update.value(2).toInt() == 1 ? Buddy::Away
                         : Buddy::Offline;
            emit q->contactStatusChanged(id, status);
            break;
        }
        case LongPoll::GroupChatUpdated: {
            int chat_id = update.value(1).toInt();
            bool self = update.value(1).toInt();
            emit q->groupChatUpdated(chat_id, self);
            break;
        }
        case LongPoll::ChatTyping: {
            int user_id = qAbs(update.value(1).toInt());
            //int flags = update.at(2).toInt();
            emit q->contactTyping(user_id);
            break;
        }
        case LongPoll::GroupChatTyping: {
            int user_id = qAbs(update.value(1).toInt());
            int chat_id = update.at(2).toInt();
            emit q->contactTyping(user_id, chat_id);
            break;
        }
        case LongPoll::UserCall: {
            int user_id = qAbs(update.value(1).toInt());
            int call_id = update.at(2).toInt();
            emit q->contactCall(user_id, call_id);
            break;
        }
        }
    }

    q->requestData(data.value("ts").toByteArray());
}
Esempio n. 21
0
AnimeIDMap UserLoader::parseList(const QJsonArray &t_list_data) {
  AnimeIDMap list;

  auto score_type = User::sharedUser()->scoreType();
  auto title_language = User::sharedUser()->titleLanguage();
  auto anime_list = User::sharedUser()->animeList();
  auto airing_list = User::sharedUser()->airingList();

  for (QJsonValue ary : t_list_data) {
    QJsonObject anime = ary.toObject();
    QJsonObject inner_anime = anime.value("anime").toObject();

    if (anime.value("anime").isNull()) {
      auto record_id = anime.value("record_id").toInt();
      qWarning() << "Null anime found for record_id:" << record_id;
      continue;
    }

    AnimePtr anime_data = Anime::makeAnime();

    connect(anime_data.get(), &Anime::loadRequested,
            [anime_data, this]() { loadAnime(anime_data->id()); });

    anime_data->setId(QString::number(inner_anime.value("id").toInt()));

    if (User::sharedUser()->getAnimeByID(anime_data->id()) ==
        AnimePtr(nullptr)) {
      anime_list.append(anime_data);
    } else {
      anime_data = User::sharedUser()->getAnimeByID(anime_data->id());

      if (!anime_list.contains(anime_data)) {
        anime_list.append(anime_data);
      }
    }

    anime_data->setTitleRomaji(inner_anime.value("title_romaji").toString());
    anime_data->setTitleJapanese(
        inner_anime.value("title_japanese").toString());
    anime_data->setTitleEnglish(inner_anime.value("title_english").toString());
    anime_data->setType(inner_anime.value("type").toString());
    anime_data->setAiringStatus(inner_anime.value("airing_status").toString());
    anime_data->setAverageScore(
        inner_anime.value("average_score").toString().toDouble());
    anime_data->setTotalEpisodes(inner_anime.value("total_episodes").toInt());
    anime_data->setAdult(inner_anime.value("adult").toBool());
    anime_data->setImageUrl(
        QUrl(inner_anime.value("image_url_lge").toString()));
    anime_data->setTitle(inner_anime.value(title_language).toString());

    anime_data->setEpisodesWatched(anime.value("episodes_watched").toInt(0));
    anime_data->setNotes(anime.value("notes").toString());
    anime_data->setRewatched(anime.value("rewatched").toInt(0));
    anime_data->setListStatus(anime.value("list_status").toString());
    anime_data->setHiddenDefault(anime.value("hidden_default").toInt());

    QVariantList v = anime.value("custom_lists").toArray().toVariantList();

    QList<int> custom_lists;

    for (int j = 0; j < v.length(); j++) {
      custom_lists.append(v.at(j).toInt());
    }

    anime_data->setCustomLists(custom_lists);

    QJsonArray synonyms = inner_anime.value("synonyms").toArray();

    for (int j = 0; j < synonyms.count(); j++) {
      anime_data->addSynonym(synonyms.at(j).toString());
    }

    if ((score_type == ScoreType::TenPoint) ||
        (score_type == ScoreType::HundredPoint)) {
      anime_data->setScore(QString::number(anime.value("score").toInt(0)));
    } else if (score_type == ScoreType::Decimal) {
      anime_data->setScore(QString::number(anime.value("score").toDouble(0.0)));
    } else if (score_type == ScoreType::FiveStar) {
      int scr = anime.value("score").toInt(0);
      QString my_score = QString::number(scr) + " ★";
      anime_data->setScore(my_score);
    } else {
      anime_data->setScore(anime.value("score").toString(""));
    }

    list.insert(anime_data->id(), anime_data);

    if (anime_data->airingStatus() == "currently airing") {
      if (!airing_list.contains(anime_data)) airing_list.append(anime_data);
    }

    User::sharedUser()->addKnownAnime(anime_data);
  }

  User::sharedUser()->setAnimeList(anime_list);
  User::sharedUser()->setAiringList(airing_list);

  return list;
}
    void testOfonoMultipartyCalls()
    {
        // Test for hangupMultiparty():
        // 1.  Dial a call
        // 2.  Receive a call (dial "199" to trigger phonesim callback)
        // 3.  Combine into multiparty call (2 participants)
        // 4.  Verify createMultiparty() works as expected
        // 5.  Put multiparty call on hold
        // 6.  Dial a 3rd call
        // 7.  Combine into multiparty call (3 participants)
        // 8.  Split one call off to "private chat"
        // 9.  Verify privateChat() works as expected
        // 10. Hangup multiparty call
        // 11. Verify hangupMultiparty() works as expected
        // 12. Hangup all calls

        QVariantList variantList;

        // VoiceCallManager Spy's
        QSignalSpy dialreg(m,SIGNAL(dialComplete(bool)));
        QSignalSpy dspy(m, SIGNAL(callAdded(QString)));
        QSignalSpy rspy(m, SIGNAL(callRemoved(QString)));
        QSignalSpy haspy(m, SIGNAL(hangupAllComplete(bool)));
        QSignalSpy haaspy(m, SIGNAL(holdAndAnswerComplete(bool)));
        QSignalSpy cmspy(m, SIGNAL(createMultipartyComplete(bool, QStringList)));
        QSignalSpy hmspy(m, SIGNAL(hangupMultipartyComplete(bool)));
        QSignalSpy scspy(m, SIGNAL(swapCallsComplete(bool)));
        QSignalSpy pcspy(m, SIGNAL(privateChatComplete(bool, QStringList)));

        // 1. Dial a call (outgoing)
        m->dial("123","");
        QTest::qWait(1000);

        QCOMPARE(dialreg.count(), 1);
        QCOMPARE(dialreg.takeFirst().at(0).toBool(),true);
        QCOMPARE(dspy.count(), 1);
        QString c1id = dspy.takeFirst().at(0).toString();

        QOfonoVoiceCall* c1 = new QOfonoVoiceCall();
        c1->setVoiceCallPath(c1id);

        QSignalSpy c1state(c1, SIGNAL(stateChanged(QString)));
        QSignalSpy c1discreason(c1,SIGNAL(disconnectReason(QString)));
        QSignalSpy c1li (c1, SIGNAL(lineIdentificationChanged(QString)));
        QSignalSpy c1name (c1, SIGNAL(nameChanged(QString)));
        QSignalSpy c1info (c1, SIGNAL(informationChanged(QString)));
        QSignalSpy c1mp (c1, SIGNAL(multipartyChanged(bool)));
        QSignalSpy c1em (c1, SIGNAL(emergencyChanged(bool)));
        QSignalSpy c1st (c1, SIGNAL(startTimeChanged(QString)));
        QSignalSpy c1ic (c1, SIGNAL(iconChanged(quint8)));

        qDebug() << "Please find a call in 'Dialing' state in phonesim window and press 'Active' button";
        QTest::qWait(15000);
        //    - new call should have a state change, and be in "active" state
        QVERIFY(c1state.count()>0);
        QVERIFY(c1st.count()>0);
        QVERIFY(c1ic.count()==0);
        QVERIFY(c1em.count()==0);
        QVERIFY(c1mp.count()==0);
        QVERIFY(c1info.count()==0);
        QVERIFY(c1name.count()==0);
        QVERIFY(c1li.count()==0);

        QCOMPARE(c1->state(),QString("active"));
        QCOMPARE(c1->lineIdentification(),QString("123"));
        QCOMPARE(c1->emergency(),false);
        QCOMPARE(c1->multiparty(),false);
        QCOMPARE(c1->name(),QString(""));
        QCOMPARE(c1->information(),QString(""));

        // 2. Receive a call
        //    - dial "199" to trigger phonesim callback
        m->dial("199","");
        QTest::qWait(8000);

        QCOMPARE(dialreg.count(), 1);
        QCOMPARE(dialreg.takeFirst().at(0).toBool(),false);
        QCOMPARE(dspy.count(),1);
        QString c2id = dspy.takeFirst().at(0).toString();

        QOfonoVoiceCall* c2 = new QOfonoVoiceCall();
        c2->setVoiceCallPath(c2id);
        QSignalSpy c2state(c2, SIGNAL(stateChanged(QString)));
        QSignalSpy c2time(c2,SIGNAL(startTimeChanged(QString)));
        QSignalSpy c2discreason(c2,SIGNAL(disconnectReason(QString)));

        QSignalSpy c2li (c2, SIGNAL(lineIdentificationChanged(QString)));
        QSignalSpy c2name (c2, SIGNAL(nameChanged(QString)));
        QSignalSpy c2info (c2, SIGNAL(informationChanged(QString)));
        QSignalSpy c2mp (c2, SIGNAL(multipartyChanged(bool)));
        QSignalSpy c2em (c2, SIGNAL(emergencyChanged(bool)));
        QSignalSpy c2ic (c2, SIGNAL(iconChanged(quint8)));

        QTest::qWait(3000);
        QCOMPARE(c2->state(),QString("waiting"));

        //    - accept incoming call, placing first call on hold
        m->holdAndAnswer();
        QTest::qWait(1000);

        QCOMPARE(haaspy.count(),1);
        QCOMPARE(haaspy.takeFirst().at(0).toBool(),true);

        QTest::qWait(3000);
        //    - call #1 should be in "held" state
        QVERIFY(c1state.count()>0);
        QCOMPARE(c1->state(),QString("held"));

        //    - call #2 should be in "active" state
        QVERIFY(c2state.count()>0);
        QCOMPARE(c2->state(),QString("active"));
        QCOMPARE(c2->lineIdentification(),QString("1234567"));
        QVERIFY(c2time.count()>0);

        QVERIFY(c2ic.count()==0);
        QVERIFY(c2em.count()==0);
        QVERIFY(c2mp.count()==0);
        QVERIFY(c2info.count()==0);
        QVERIFY(c2name.count()==0);
        QVERIFY(c2li.count()==0);

        // 3. Combine into multiparty call (2 participants)
        m->createMultiparty();
        QTest::qWait(1000);
        QCOMPARE(cmspy.count(),1);
        variantList = cmspy.takeFirst();
        QCOMPARE(variantList.at(0).toBool(),true);
        QVERIFY(variantList.at(1).toStringList().length() > 0);

        QTest::qWait(3000);
        // 4. Verify createMultiparty() works as expected
        //    - call #1 should have a stateChanged signal triggered
        QVERIFY(c1state.count()>0);
        //    - both calls should have a multipartyChanged signal triggered,
        //      be in "active" state and have multiparty property set to "true"
        QVERIFY(c1mp.count()>0);
        QVERIFY(c2mp.count()>0);
        QCOMPARE(c1->state(),QString("active"));
        QCOMPARE(c2->state(),QString("active"));
        QCOMPARE(c1->multiparty(),true);
        QCOMPARE(c2->multiparty(),true);

        // 5. Put multiparty call on hold
        m->swapCalls();
        QTest::qWait(1000);

        QCOMPARE(scspy.count(),1);
        QCOMPARE(scspy.takeFirst().at(0).toBool(),true);

        QTest::qWait(3000);
        //    - both calls should have a stateChanged signal triggered
        //      and be in "held" state
        QVERIFY(c1state.count()>0);
        QVERIFY(c2state.count()>0);
        QCOMPARE(c1->state(),QString("held"));
        QCOMPARE(c2->state(),QString("held"));

        // 6. Dial a 3rd call
        m->dial("456","");
        QTest::qWait(1000);

        QCOMPARE(dialreg.count(), 1);
        QCOMPARE(dialreg.takeFirst().at(0).toBool(),true);
        QCOMPARE(dspy.count(), 1);
        QString c3id = dspy.takeFirst().at(0).toString();

        QOfonoVoiceCall* c3 = new QOfonoVoiceCall();
        c3->setVoiceCallPath(c3id);

        QSignalSpy c3state(c3, SIGNAL(stateChanged(QString)));
        QSignalSpy c3discreason(c3,SIGNAL(disconnectReason(QString)));
        QSignalSpy c3li (c3, SIGNAL(lineIdentificationChanged(QString)));
        QSignalSpy c3name (c3, SIGNAL(nameChanged(QString)));
        QSignalSpy c3info (c3, SIGNAL(informationChanged(QString)));
        QSignalSpy c3mp (c3, SIGNAL(multipartyChanged(bool)));
        QSignalSpy c3em (c3, SIGNAL(emergencyChanged(bool)));
        QSignalSpy c3st (c3, SIGNAL(startTimeChanged(QString)));
        QSignalSpy c3ic (c3, SIGNAL(iconChanged(quint8)));

        qDebug() << "Please find a call in 'Dialing' state in phonesim window and press 'Active' button";
        QTest::qWait(15000);
        //    - 3rd call should have a state change, and be in "active" state
        QVERIFY(c3state.count()>0);
        QVERIFY(c3st.count()>0);
        QVERIFY(c3ic.count()==0);
        QVERIFY(c3em.count()==0);
        QVERIFY(c3mp.count()==0);
        QVERIFY(c3info.count()==0);
        QVERIFY(c3name.count()==0);
        QVERIFY(c3li.count()==0);

        QCOMPARE(c3->state(),QString("active"));
        QCOMPARE(c3->lineIdentification(),QString("456"));
        QCOMPARE(c3->emergency(),false);
        QCOMPARE(c3->multiparty(),false);
        QCOMPARE(c3->name(),QString(""));
        QCOMPARE(c3->information(),QString(""));

        // 7. Combine into multiparty call (3 participants)
        m->createMultiparty();
        QTest::qWait(1000);

        QCOMPARE(cmspy.count(),1);
        variantList = cmspy.takeFirst();
        QCOMPARE(variantList.at(0).toBool(),true);
        QVERIFY(variantList.at(1).toStringList().length() > 0);

        QTest::qWait(3000);
        //    - calls #1 and #2 should have a stateChanged signal triggered
        QVERIFY(c1state.count()>0);
        QVERIFY(c2state.count()>0);
        //    - all calls should have a multipartyChanged signal triggered,
        //      be in "active" state and have multiparty property set to "true"
        QVERIFY(c1mp.count()>0);
        QVERIFY(c2mp.count()>0);
        QVERIFY(c3mp.count()>0);
        QCOMPARE(c1->state(),QString("active"));
        QCOMPARE(c2->state(),QString("active"));
        QCOMPARE(c3->state(),QString("active"));
        QCOMPARE(c1->multiparty(),true);
        QCOMPARE(c2->multiparty(),true);
        QCOMPARE(c3->multiparty(),true);

        // 8.  Split call #1 off to "private chat"
        m->privateChat(c1id);
        QTest::qWait(1000);

        QCOMPARE(pcspy.count(),1);
        variantList = pcspy.takeFirst();
        QCOMPARE(variantList.at(0).toBool(),true);
        QVERIFY(variantList.at(1).toStringList().length() > 0);

        QTest::qWait(3000);
        // 9.  Verify privateChat() works as expected
        //    - call #1 should have a multipartyChanged signal triggered,
        //      it's multiparty property set to false and be in "active" state
        QVERIFY(c1mp.count()>0);
        QCOMPARE(c1->multiparty(),false);
        QCOMPARE(c1->state(),QString("active"));
        //    - calls #2 and #3 should have a stateChanged signal triggered
        //      and be back in "held" state
        QVERIFY(c2state.count()>0);
        QVERIFY(c3state.count()>0);
        QCOMPARE(c2->state(),QString("held"));
        QCOMPARE(c3->state(),QString("held"));


        // 10. Hangup multiparty call
        m->hangupMultiparty();
        QTest::qWait(1000);
        QCOMPARE(hmspy.count(), 1);
        QCOMPARE(hmspy.takeFirst().at(0).toBool(),true);

        QTest::qWait(3000);
        // 11. Verify hangupMultiparty() works as expected
        //    - two calls should have been removed
        QVERIFY(rspy.count()==2);
        QString r2id = rspy.takeFirst().at(0).toString();
        QString r3id = rspy.takeFirst().at(0).toString();
        QCOMPARE(r2id,c2id);
        QCOMPARE(r3id,c3id);

        //    - call #1 should still be in "active" state
        QCOMPARE(c1->state(),QString("active"));

        //    - calls #2 and #3 should have a stateChanged signal triggered
        //      and have a disconnect reason of "local"
        QVERIFY(c2state.count()>0);
        QVERIFY(c3state.count()>0);
        QCOMPARE(c2discreason.count(), 1);
        QCOMPARE(c3discreason.count(), 1);
        QCOMPARE(c2discreason.takeFirst().at(0).toString(), QString("local"));
        QCOMPARE(c3discreason.takeFirst().at(0).toString(), QString("local"));

        // 12. Hangup all calls
        m->hangupAll();
        QTest::qWait(1000);
        QCOMPARE(haspy.count(), 1);
        QCOMPARE(haspy.takeFirst().at(0).toBool(),true);

        QTest::qWait(3000);
        QCOMPARE(c1discreason.count(), 1);
        QCOMPARE(c1discreason.takeFirst().at(0).toString(), QString("local"));

        delete c1;
        delete c2;
        delete c3;
    }
Esempio n. 23
0
void Core::writeOra(const QString& oraPath, const QSize& canvasSize, const QVariantList layerList) {
    QZipWriter zipWriter(oraPath);
    zipWriter.setCompressionPolicy(QZipWriter::AutoCompress);

    QByteArray xmlByteArray;

    // mimetype file
    xmlByteArray.append("image/openraster");
    zipWriter.addFile("mimetype", xmlByteArray);

    // stack.xml file
    QXmlStreamWriter stream(&xmlByteArray);
    stream.setAutoFormatting(true);

    stream.writeStartDocument();

    stream.writeStartElement("image");
    stream.writeAttribute("w", QString::number(canvasSize.width()));
    stream.writeAttribute("h",QString::number(canvasSize.height()));
    stream.writeStartElement("stack");

    QByteArray ba;
    QBuffer buffer(&ba);

    for (int i = 0; i < layerList.count(); i++) {
        QMap<QString, QVariant> map = layerList.at(i).toMap();
        QString name = map.value("name").toString();
        QString isVisible = map.value("isVisible").toString();
        QString isLock = map.value("isLock").toString();
        QString isSelected = map.value("isSelected").toString();

        buffer.open(QIODevice::WriteOnly);
        QObject* obj = qvariant_cast<QObject*>(map.value("canvasItem"));
        CanvasItem* canvasItem = qobject_cast<CanvasItem*>(obj);
        QPixmap* pixmap = canvasItem->pixmap();
        pixmap->save(&buffer, "PNG");
        buffer.close();

        QString src = "data/" + name + ".png";
        zipWriter.addFile(src, ba);

        // layer
        stream.writeStartElement("layer");
        stream.writeAttribute("name", name);
        stream.writeAttribute("composite-op", "svg:src-over");
        stream.writeAttribute("visibility", isVisible == "true" ? "visible" : "hidden");
        stream.writeAttribute("edit-locked", isLock);
        stream.writeAttribute("selected", isSelected);
        stream.writeAttribute("src", src);
        stream.writeAttribute("x", "0");
        stream.writeAttribute("y", "0");
        stream.writeAttribute("opacity", "1.0");
        stream.writeEndElement(); // layer
    }

    stream.writeEndElement(); // stack
    stream.writeEndElement(); // image
    stream.writeEndDocument(); // document
    zipWriter.addFile("stack.xml", xmlByteArray);

    zipWriter.close();
}
/*!
 From HbAbstractViewItem.

 \sa HbAbstractViewItem, HbGridViewItem
 */
void CalenGridItemPrototype::updateChildItems()
{		
    OstTraceFunctionEntry0( CALENGRIDITEMPROTOTYPE_UPDATECHILDITEMS_ENTRY );
    
	// Here update content of each item.
	QVariant monthDayRole;
	bool monthFocusRole;
	bool underlineEnabled = false;
	bool monthEventRole;
	bool monthTextColorRole;
	QVariant itemData = modelIndex().data(Qt::UserRole + 1);
	if (itemData.isValid()) {
		if (itemData.canConvert<QVariantList>()) {
		
			// Get the item list
			QVariantList itemList = itemData.toList();
			// Get the day text
			monthDayRole = itemList.at(CalendarNamespace::CalendarMonthDayRole);
			if (monthDayRole.canConvert<QString>()) {
				mMonthDayInfoItem->setText(monthDayRole.toString());
			}
			
			// Get the focus data
			monthFocusRole = itemList.at(CalendarNamespace::CalendarMonthFocusRole).value<bool>();
			if (monthFocusRole) {
				mFocusIndicatorItem->frameDrawer().setFrameGraphicsName(focusIconName);
			} else {
				mFocusIndicatorItem->frameDrawer().setFrameGraphicsName(QString(""));
			}
			
			// Get the today indicator role
			underlineEnabled = itemList.at(
					CalendarNamespace::CalendarMonthUnderlineRole).
					value<bool>();
			if(underlineEnabled) {
				mTodayIndicatorItem->show();
			} else {
				mTodayIndicatorItem->hide();
			}
			
			// Get the event indicator data
			monthEventRole = itemList.at(CalendarNamespace::CalendarMonthEventRole).value<bool>();
			if (monthEventRole) {
				// Set the event indicator
				//QString iconName(focusIconName);
				mEventIndicatorItem->setIconName(eventIndname);
			} else {
				mEventIndicatorItem->setIconName(QString(""));
			}
			
			// Get the text color
			monthTextColorRole = itemList.at(CalendarNamespace::CalendarMonthTextColorRole).value<bool>();
			if (monthTextColorRole) {
                if (monthFocusRole) {
                    // Set the Highlighted text color
                    mMonthDayInfoItem->setTextColor(mCurrentDateColor);
                } else {
                    // Set the active text color
                    mMonthDayInfoItem->setTextColor(mActiveTextColor);
                }
			} else {
				// Set the inactive text color
				mMonthDayInfoItem->setTextColor(mInActiveTextColor);
			}
		}
	}
	
	// base class implementation
	HbGridViewItem::updateChildItems();
	OstTraceFunctionExit0( CALENGRIDITEMPROTOTYPE_UPDATECHILDITEMS_EXIT );
}
Esempio n. 25
0
void ReverseGeoLookupThread::run() {
	if (geo_lookup_data.isEmpty())
		return;

	QNetworkRequest request;
	QNetworkAccessManager *rgl = new QNetworkAccessManager();
	QEventLoop loop;
	QString mapquestURL("http://open.mapquestapi.com/nominatim/v1/reverse.php?format=json&accept-language=%1&lat=%2&lon=%3");
	QString geonamesURL("http://api.geonames.org/findNearbyPlaceNameJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString geonamesOceanURL("http://api.geonames.org/oceanJSON?language=%1&lat=%2&lng=%3&radius=50&username=dirkhh");
	QString divelogsURL("https://www.divelogs.de/mapsearch_divespotnames.php?lat=%1&lng=%2&radius=50");
	QTimer timer;

	request.setRawHeader("Accept", "text/json");
	request.setRawHeader("User-Agent", getUserAgent().toUtf8());
	connect(&timer, SIGNAL(timeout()), &loop, SLOT(quit()));

	Q_FOREACH (const GeoLookupInfo& info, geo_lookup_data ) {
		struct dive_site *ds = info.uuid ? get_dive_site_by_uuid(info.uuid) : &displayed_dive_site;

		// first check the findNearbyPlaces API from geonames - that should give us country, state, city
		request.setUrl(geonamesURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));

		QNetworkReply *reply = rgl->get(request);
		timer.setSingleShot(true);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();

		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant geoNamesObject = obj.value("geonames").toVariant();
			QVariantList geoNames = geoNamesObject.toList();
			if (geoNames.count() > 0) {
				QVariantMap firstData = geoNames.at(0).toMap();
				int ri = 0, l3 = -1, lt = -1;
				if (ds->taxonomy.category == NULL) {
					ds->taxonomy.category = alloc_taxonomy();
				} else {
					// clear out the data (except for the ocean data)
					int ocean;
					if ((ocean = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN)) > 0) {
						ds->taxonomy.category[0] = ds->taxonomy.category[ocean];
						ds->taxonomy.nr = 1;
					} else {
						// ocean is -1 if there is no such entry, and we didn't copy above
						// if ocean is 0, so the following gets us the correct count
						ds->taxonomy.nr = ocean + 1;
					}
				}
				// get all the data - OCEAN is special, so start at COUNTRY
				for (int j = TC_COUNTRY; j < TC_NR_CATEGORIES; j++) {
					if (firstData[taxonomy_api_names[j]].isValid()) {
						ds->taxonomy.category[ri].category = j;
						ds->taxonomy.category[ri].origin = taxonomy::GEOCODED;
						free((void*)ds->taxonomy.category[ri].value);
						ds->taxonomy.category[ri].value = copy_string(qPrintable(firstData[taxonomy_api_names[j]].toString()));
						ri++;
					}
				}
				ds->taxonomy.nr = ri;
				l3 = taxonomy_index_for_category(&ds->taxonomy, TC_ADMIN_L3);
				lt = taxonomy_index_for_category(&ds->taxonomy, TC_LOCALNAME);
				if (l3 == -1 && lt != -1) {
					// basically this means we did get a local name (what we call town), but just like most places
					// we didn't get an adminName_3 - which in some regions is the actual city that town belongs to,
					// then we copy the town into the city
					ds->taxonomy.category[ri].value = copy_string(ds->taxonomy.category[lt].value);
					ds->taxonomy.category[ri].origin = taxonomy::COPIED;
					ds->taxonomy.category[ri].category = TC_ADMIN_L3;
					ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			} else {
				report_error("geonames.org did not provide reverse lookup information");
				qDebug() << "no reverse geo lookup; geonames returned\n" << fullReply;
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}
		// next check the oceans API to figure out the body of water
		request.setUrl(geonamesOceanURL.arg(uiLanguage(NULL)).arg(info.lat.udeg / 1000000.0).arg(info.lon.udeg / 1000000.0));
		reply = rgl->get(request);
		connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
		timer.start(5000);   // 5 secs. timeout
		loop.exec();
		if(timer.isActive()) {
			timer.stop();
			if(reply->error() > 0) {
				report_error("got error accessing oceans API of geonames.org: %s", qPrintable(reply->errorString()));
				goto clear_reply;
			}
			int v = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
			if (v < 200 || v >= 300)
				goto clear_reply;
			QByteArray fullReply = reply->readAll();
			QJsonParseError errorObject;
			QJsonDocument jsonDoc = QJsonDocument::fromJson(fullReply, &errorObject);
			if (errorObject.error != QJsonParseError::NoError) {
				report_error("error parsing geonames.org response: %s", qPrintable(errorObject.errorString()));
				goto clear_reply;
			}
			QJsonObject obj = jsonDoc.object();
			QVariant oceanObject = obj.value("ocean").toVariant();
			QVariantMap oceanName = oceanObject.toMap();
			if (oceanName["name"].isValid()) {
				int idx;
				if (ds->taxonomy.category == NULL)
					ds->taxonomy.category = alloc_taxonomy();
				idx = taxonomy_index_for_category(&ds->taxonomy, TC_OCEAN);
				if (idx == -1)
					idx = ds->taxonomy.nr;
				if (idx < TC_NR_CATEGORIES) {
					ds->taxonomy.category[idx].category = TC_OCEAN;
					ds->taxonomy.category[idx].origin = taxonomy::GEOCODED;
					ds->taxonomy.category[idx].value = copy_string(qPrintable(oceanName["name"].toString()));
					if (idx == ds->taxonomy.nr)
						ds->taxonomy.nr++;
				}
				mark_divelist_changed(true);
			}
		} else {
			report_error("timeout accessing geonames.org");
			disconnect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
			reply->abort();
		}

clear_reply:
		reply->deleteLater();
	}
	rgl->deleteLater();
}
Esempio n. 26
0
int main(int argc, char **argv)
{
    enum ExitCode
    {
        /**
         * We start from 2, because QApplicationArgumentParser
         * uses 1.
         */
        QueryFailure = 2,
        StdOutFailure
    };

    const QCoreApplication app(argc, argv);
    QCoreApplication::setApplicationName(QLatin1String("xmlpatterns"));

    QXmlNamePool namePool;
    PatternistApplicationParser parser(argc, argv, namePool);
    parser.setApplicationDescription(QLatin1String("A tool for running XQuery queries."));
    parser.setApplicationVersion(QLatin1String("0.1"));

    QApplicationArgument param(QLatin1String("param"),
                               QXmlPatternistCLI::tr("Binds an external variable. The value is directly available using the variable reference: $name."),
                               qMetaTypeId<Parameter>());
    param.setMaximumOccurrence(-1);
    parser.addArgument(param);

    const QApplicationArgument noformat(QLatin1String("no-format"),
                                        QXmlPatternistCLI::tr("By default output is formatted for readability. When specified, strict serialization is performed."));
    parser.addArgument(noformat);

    const QApplicationArgument isURI(QLatin1String("is-uri"),
                                     QXmlPatternistCLI::tr("If specified, all filenames on the command line are interpreted as URIs instead of a local filenames."));
    parser.addArgument(isURI);

    const QApplicationArgument initialTemplateName(QLatin1String("initial-template"),
                                                   QXmlPatternistCLI::tr("The name of the initial template to call as a Clark Name."),
                                                   QVariant::String);
    parser.addArgument(initialTemplateName);

    /* The temporary object is required to compile with g++ 3.3. */
    QApplicationArgument queryURI = QApplicationArgument(QLatin1String("query/stylesheet"),
                                                         QXmlPatternistCLI::tr("A local filename pointing to the query to run. If the name ends with .xsl it's assumed "
                                                                               "to be an XSL-T stylesheet. If it ends with .xq, it's assumed to be an XQuery query. (In "
                                                                               "other cases it's also assumed to be an XQuery query, but that interpretation may "
                                                                               "change in a future release of Qt.)"),
                                                         QVariant::String);
    queryURI.setMinimumOccurrence(1);
    queryURI.setNameless(true);
    parser.addArgument(queryURI);

    QApplicationArgument focus = QApplicationArgument(QLatin1String("focus"),
                                                      QXmlPatternistCLI::tr("The document to use as focus. Mandatory "
                                                                            "in case a stylesheet is used. This option is "
                                                                            "also affected by the is-uris option."),
                                                      QVariant::String);
    focus.setMinimumOccurrence(0);
    focus.setNameless(true);
    parser.addArgument(focus);

    QApplicationArgument output(QLatin1String("output"),
                                QXmlPatternistCLI::tr("A local file to which the output should be written. "
                                                      "The file is overwritten, or if not exist, created. "
                                                      "If absent, stdout is used."),
                                qMetaTypeId<QIODevice *>());
    parser.addArgument(output);

    if(!parser.parse())
        return parser.exitCode();

    /* Get the query URI. */
    const QUrl effectiveURI(finalizeURI(parser, isURI, queryURI));

    QXmlQuery::QueryLanguage lang;

    if(effectiveURI.toString().endsWith(QLatin1String(".xsl")))
         lang = QXmlQuery::XSLT20;
    else
         lang = QXmlQuery::XQuery10;

    if(lang == QXmlQuery::XQuery10 && parser.has(initialTemplateName))
    {
        parser.message(QXmlPatternistCLI::tr("An initial template name cannot be specified when running an XQuery."));
        return QApplicationArgumentParser::ParseError;
    }

    QXmlQuery query(lang, namePool);

    query.setInitialTemplateName(qvariant_cast<QXmlName>(parser.value(initialTemplateName)));

    /* Bind external variables. */
    {
        const QVariantList parameters(parser.values(param));
        const int len = parameters.count();

        /* For tracking duplicates. */
        QSet<QString> usedParameters;

        for(int i = 0; i < len; ++i)
        {
            const Parameter p(qvariant_cast<Parameter>(parameters.at(i)));

            if(usedParameters.contains(p.first))
            {
                parser.message(QXmlPatternistCLI::tr("Each parameter must be unique, %1 is specified at least twice.").arg(p.first));
                return QApplicationArgumentParser::ParseError;
            }
            else
            {
                usedParameters.insert(p.first);
                query.bindVariable(p.first, QXmlItem(p.second));
            }
        }
    }

    if(parser.has(focus))
    {
        if(!query.setFocus(finalizeURI(parser, isURI, focus)))
            return QueryFailure;
    }
    else if(lang == QXmlQuery::XSLT20 && !parser.has(initialTemplateName))
    {
        parser.message(QXmlPatternistCLI::tr("When a stylesheet is used, a "
                                             "document must be specified as a focus, or an "
                                             "initial template name must be specified, or both."));
        return QApplicationArgumentParser::ParseError;
    }

    query.setQuery(effectiveURI);

    const QPatternist::AutoPtr<QIODevice> outDevice(qvariant_cast<QIODevice *>(parser.value(output)));
    Q_ASSERT(outDevice);
    Q_ASSERT(outDevice->isWritable());

    if(query.isValid())
    {
        typedef QPatternist::AutoPtr<QAbstractXmlReceiver> RecPtr;
        RecPtr receiver;

        if(parser.has(noformat))
            receiver = RecPtr(new QXmlSerializer(query, outDevice.data()));
        else
            receiver = RecPtr(new QXmlFormatter(query, outDevice.data()));

        const bool success = query.evaluateTo(receiver.data());

        if(success)
            return parser.exitCode();
        else
            return QueryFailure;
    }
    else
        return QueryFailure;
}
Esempio n. 27
0
void ApiYandexSearch::getSuggestionsFinished(QNetworkReply *reply)
{
    QByteArray content = reply->readAll();

    if (m_suggestionsParameters.v == "4") {
        QJsonParseError parseError;

        QVariant json = QJsonDocument::fromJson(content, &parseError).toVariant();
        if (Q_UNLIKELY(parseError.error)) {
            qWarning() << "ApiYandexSearch::getSuggestionsFinished():"
                       << tr("Can't parse JSON data:") << content
                       << tr(". Parser returned an error:") << parseError.errorString();
            qWarning() << "Request:" << m_currentSuggestionsRequest;
            m_currentSuggestionsRequest.clear();
            return;
        }
        QVariantList jsonList = json.toList();

        if (jsonList.size() == 0) {
                return;
        }

        QVariantList suggestions = jsonList.at(1).toList();

        QList<Consts::Shared::Suggestion> suggestionsToReturn;
        forc11 (QVariant var, suggestions) {
            Consts::Shared::Suggestion suggestion;

            // Query
            if (var.type() == QVariant::String) {
                suggestion.text = var.toString();
                suggestion.kind = Consts::Shared::Suggestion::Kind::Query;
            }
            else if (var.type() == QVariant::List) {
                QVariantList list = var.toList();

                QString kind = list.first().toString();

                // Fact
                if (kind == "fact") {
                    suggestion.text = list.at(1).toString();
                    suggestion.kind = Consts::Shared::Suggestion::Kind::Fact;
                    suggestion.others.fact = list.at(2).toString();
                }

                // Navigation
                else if (kind == "nav") {
                    suggestion.text = list.at(3).toString();
                    suggestion.kind = Consts::Shared::Suggestion::Kind::Navigation;
                    const QString nameOfGoToSite = QString::fromUtf8("перейти на сайт");
                    if (list.at(2).toString() != nameOfGoToSite)
                        suggestion.others.linkTitle = list.at(2).toString();
                }
                else {
                    continue;
                }
            }
            else {
                continue;
            }

            suggestionsToReturn.append(suggestion);
        }
void AM2DScanConfigurationGeneralView::createView(const QString &databaseName, const QString &tableName, int dbId)
{
	AMDatabase *database = AMDatabase::database(databaseName);
	if(database){
		QSqlQuery q = database->query();
		q.prepare("PRAGMA table_info("%tableName%")");
		if(!database->execQuery(q)) {
			q.finish();
			AMErrorMon::report(AMErrorReport(0, AMErrorReport::Debug, -275002, QString("2D Scan Configuration Generl View: There was an error while trying to read meta data on table %1.").arg(tableName)));
		}
		else{
			QStringList columnNames;
			while(q.next()){
				columnNames << q.value(1).toString();
			}
			columnNames.removeFirst();
			q.finish();

			QVariantList columnValues = database->retrieve(dbId, tableName, columnNames);

			QFormLayout *fl = new QFormLayout();
			QLabel *tempLabel;
			QString labelValue;

			labelValue = columnValues.at(columnNames.indexOf("xStart")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("X Start", tempLabel);

			labelValue = columnValues.at(columnNames.indexOf("xStep")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("X Step", tempLabel);

			labelValue = columnValues.at(columnNames.indexOf("xEnd")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("X End", tempLabel);

			labelValue = columnValues.at(columnNames.indexOf("yStart")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("Y Start", tempLabel);

			labelValue = columnValues.at(columnNames.indexOf("yStep")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("Y Step", tempLabel);

			labelValue = columnValues.at(columnNames.indexOf("yEnd")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("Y End", tempLabel);

			labelValue = columnValues.at(columnNames.indexOf("timeStep")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("Dwell Time", tempLabel);

			labelValue = columnValues.at(columnNames.indexOf("fastAxis")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("fastAxis", tempLabel);

			labelValue = columnValues.at(columnNames.indexOf("slowAxis")).toString();
			tempLabel = new QLabel(labelValue);
			fl->addRow("Slow Axis", tempLabel);

			fl->setLabelAlignment(Qt::AlignLeft);
			setLayout(fl);
		}
	}
}
Esempio n. 29
0
int HtmlExporter::exportSelected(bool open)
{
  int exported = 0, totalToExport = 0, currentPage = 0, totalPages = 0, exportedPage = 0;

  QString filename = saveHtmlFileDialog();
  QString basename = QFileInfo(filename).fileName();
  qDebug() << "exportSelectedHtml" << filename;

  if(filename.isEmpty())
    return 0;

  const QItemSelection sel = controller->getSelection();
  for(QItemSelectionRange rng : sel)
    totalToExport += rng.height();
  totalPages = static_cast<int>(std::ceil(static_cast<float>(totalToExport) / static_cast<float>(pageSize)));

  if(!askOverwriteDialog(filename, totalPages))
    return exported;

  QFile file(filename);
  QXmlStreamWriter stream;
  if(!startFile(file, basename, stream, currentPage, totalPages))
    return exported;

  QVector<const Column *> columnList = controller->getCurrentColumns();

  QVector<int> visualColumnIndex;

  for(QItemSelectionRange rng : sel)
    for(int row = rng.top(); row <= rng.bottom(); ++row)
    {
      if(exportedPage == 0)
      {
        // Create an index that maps the (probably reordered) columns of the
        // view to the model
        createVisualColumnIndex(columnList.size(), visualColumnIndex);
        writeHtmlTableHeader(stream, headerNames(columnList.size(), visualColumnIndex));
      }
      exportedPage++;

      stream.writeStartElement("tr");
      if((exported % 2) == 1)
        // Write alternating color class
        stream.writeAttribute("class", "alt");

      QVariantList values = controller->getFormattedModelData(row);

      for(int col = 0; col < values.size(); ++col)
      {
        int physIndex = visualColumnIndex[col];
        if(physIndex != -1)
          writeHtmlTableCellRaw(stream, columnList.at(physIndex)->getColumnName(),
                                values.at(physIndex).toString(), exported);
      }
      stream.writeEndElement(); // tr

      exported++;
      if((exported % pageSize) == 0)
      {
        endFile(file, basename, stream, currentPage, totalPages);
        currentPage++;
        exportedPage = 0;

        file.setFileName(filenameForPage(filename, currentPage));
        if(!startFile(file, basename, stream, currentPage, totalPages))
          return exported;
      }
    }

  endFile(file, basename, stream, currentPage, totalPages);

  if(open)
    openDocument(filename);

  return exported;
}
Esempio n. 30
0
static QVariant fcnExp( const QVariantList& values, QgsFeature* , QgsExpression* parent )
{
  double x = getDoubleValue( values.at( 0 ), parent );
  return QVariant( exp( x ) );
}