示例#1
0
static int score_words(const QStringList &al, const QStringList &bl)
{
    QStringList::const_iterator ait = al.begin();
    QStringList::const_iterator bit = bl.begin();
    int score = 0;
    for (; (ait != al.end()) && (bit != bl.end()); ++ait)
    {
        QStringList::const_iterator bit2 = bit;
        int dist = 0;
        int bscore = 0;
        for (; bit2 != bl.end(); ++bit2)
        {
            if (*ait == *bit)
            {
                bscore = max(1000, 2000 - (dist * 500));
                // lower score for short words
                if (ait->length() < 5)
                    bscore /= 5 - ait->length();
                break;
            }
            dist++;
        }
        if (bscore && dist < 3)
        {
            for (int i = 0; (i < dist) && bit != bl.end(); i++)
                ++bit;
        }
        score += bscore;
    }

    return score / al.size();
}
示例#2
0
int QgsWFSData::pointsFromCoordinateString( std::list<QgsPoint>& points, const QString& coordString ) const
{
  //tuples are separated by space, x/y by ','
  QStringList tuples = coordString.split( mTupleSeparator, QString::SkipEmptyParts );
  QStringList tuples_coordinates;
  double x, y;
  bool conversionSuccess;

  QStringList::const_iterator tupleIterator;
  for ( tupleIterator = tuples.constBegin(); tupleIterator != tuples.constEnd(); ++tupleIterator )
  {
    tuples_coordinates = tupleIterator->split( mCoordinateSeparator, QString::SkipEmptyParts );
    if ( tuples_coordinates.size() < 2 )
    {
      continue;
    }
    x = tuples_coordinates.at( 0 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess )
    {
      continue;
    }
    y = tuples_coordinates.at( 1 ).toDouble( &conversionSuccess );
    if ( !conversionSuccess )
    {
      continue;
    }
    points.push_back( QgsPoint( x, y ) );
  }
  return 0;
}
示例#3
0
void VideoScannerThread::SetHosts(const QStringList &hosts)
{
    m_liveSGHosts.clear();
    QStringList::const_iterator iter = hosts.begin();
    for (; iter != hosts.end(); ++iter)
        m_liveSGHosts << iter->toLower();
}
static KUrl parseURL( int mRealArgType, const QString& str )
{
  if ( mRealArgType == 33 ) { // LDAP server
    // The format is HOSTNAME:PORT:USERNAME:PASSWORD:BASE_DN
    QStringList items = str.split( ':' );
    if ( items.count() == 5 ) {
      QStringList::const_iterator it = items.constBegin();
      KUrl url;
      url.setProtocol( "ldap" );
      url.setHost( urlpart_decode( *it++ ) );

      bool ok;
      const int port = (*it++).toInt( &ok );
      if ( ok )
          url.setPort( port );
      else if ( !it->isEmpty() )
          kWarning(5150) <<"parseURL: malformed LDAP server port, ignoring: \"" << *it << "\"";

      url.setPath( "/" ); // workaround KUrl parsing bug
      url.setUser( urlpart_decode( *it++ ) );
      url.setPass( urlpart_decode( *it++ ) );
      url.setQuery( urlpart_decode( *it ) );
      return url;
    } else
      kWarning(5150) <<"parseURL: malformed LDAP server:" << str;
  }
  // other URLs : assume wellformed URL syntax.
  return KUrl( str );
}
示例#5
0
文件: config.cpp 项目: Fale/qtmoko
QStringList Config::getFilesHere(const QString& dir,
                                 const QString& nameFilter,
                                 const QSet<QString> &excludedDirs)
{
    QStringList result;
    if (excludedDirs.contains(dir))
        return result;

    QDir dirInfo(dir);
    QStringList fileNames;
    QStringList::const_iterator fn;

    dirInfo.setNameFilters(nameFilter.split(' '));
    dirInfo.setSorting(QDir::Name);
    dirInfo.setFilter(QDir::Files);
    fileNames = dirInfo.entryList();
    fn = fileNames.constBegin();
    while (fn != fileNames.constEnd()) {
        if (!fn->startsWith(QLatin1Char('~')))
            result.append(dirInfo.filePath(*fn));
	++fn;
    }    
    
    dirInfo.setNameFilters(QStringList("*"));
    dirInfo.setFilter(QDir::Dirs|QDir::NoDotAndDotDot);
    fileNames = dirInfo.entryList();
    fn = fileNames.constBegin();
    while (fn != fileNames.constEnd()) {
        result += getFilesHere(dirInfo.filePath(*fn), nameFilter, excludedDirs);
	++fn;
    }
    return result;
}
bool SQLiteDatabaseConnection::createTables()
{
	bool retVal = true;
	
    //Liste von auszuführenden Statements erstellen
	QStringList statements;
    statements << "PRAGMA page_size = 4096;";
    statements << "PRAGMA max_page_count = 2147483646;";
    statements << "PRAGMA cache_size=50000;";
    statements << "PRAGMA synchronous=OFF;";
    statements << "PRAGMA journal_mode=MEMORY;";
    statements << "PRAGMA temp_store = MEMORY;";
	statements << "CREATE TABLE IF NOT EXISTS EDGES(ID INTEGER PRIMARY KEY, STARTNODE INTEGER NOT NULL, ENDNODE INTEGER NOT NULL, PROPERTIES INTEGER NOT NULL);";
	statements << "CREATE TABLE IF NOT EXISTS NODES(ID INTEGER PRIMARY KEY, LAT, LON, BUCKETID);";
	//TODO: Müssen noch Indicies erstellt werden? Laut Doku sollte es so schon schnell sein.
    statements << "CREATE TABLE EDGES_STREETNAME(ID INTEGER PRIMARY KEY, STREETNAME VARCHAR);";
    
    //Alle Statements der Liste ausführen in einer Transaktion
    //retVal = this->beginTransaction();
	QStringList::const_iterator it;
	for (it = statements.constBegin(); it != statements.constEnd(); it++)
	{
		retVal &= execCreateTableStatement(it->toStdString());
	}
    //retVal &= this->endTransaction();
	
	return retVal;
}
示例#7
0
const DataVariant& DynamicObjectImp::getAttributeByPath(QStringList pathComponents) const
{
   static DataVariant sEmptyVariant;

   QString finalName = pathComponents.back();
   pathComponents.pop_back();

   string loopType = "DynamicObject";
   const DynamicObject* pCurrentObj = dynamic_cast<const DynamicObject*>(this);
   for (QStringList::const_iterator iter = pathComponents.begin();
      iter != pathComponents.end(); ++iter)
   {
      if ( (pCurrentObj == NULL) || loopType != "DynamicObject")
      {
         sEmptyVariant = DataVariant();
         return sEmptyVariant;
      }

      const DataVariant& attrValue = pCurrentObj->getAttribute(iter->toStdString());
      loopType = attrValue.getTypeName();
      pCurrentObj = attrValue.getPointerToValue<DynamicObject>();
   }

   if (pCurrentObj == NULL)
   {
      sEmptyVariant = DataVariant();
      return sEmptyVariant;
   }

   return pCurrentObj->getAttribute(finalName.toStdString());
}
/** @short Find a message body part through its slash-separated string path */
Imap::Mailbox::TreeItemPart *MsgPartNetAccessManager::pathToPart(const QModelIndex &message, const QString &path)
{
    QStringList items = path.split('/', QString::SkipEmptyParts);
    const Mailbox::Model *model = 0;
    Imap::Mailbox::TreeItem *target = Mailbox::Model::realTreeItem(message, &model);
    Q_ASSERT(model);
    Q_ASSERT(target);
    bool ok = ! items.isEmpty(); // if it's empty, it's a bogous URL

    for (QStringList::const_iterator it = items.constBegin(); it != items.constEnd(); ++it) {
        uint offset = it->toUInt(&ok);
        if (!ok) {
            // special case, we have to dive into that funny, irregular special parts now
            if (*it == QLatin1String("HEADER"))
                target = target->specialColumnPtr(0, Imap::Mailbox::TreeItem::OFFSET_HEADER);
            else if (*it == QLatin1String("TEXT"))
                target = target->specialColumnPtr(0, Imap::Mailbox::TreeItem::OFFSET_TEXT);
            else if (*it == QLatin1String("MIME"))
                target = target->specialColumnPtr(0, Imap::Mailbox::TreeItem::OFFSET_MIME);
            else
                return 0;
            continue;
        }
        if (offset >= target->childrenCount(const_cast<Mailbox::Model *>(model))) {
            return 0;
        }
        target = target->child(offset, const_cast<Mailbox::Model *>(model));
    }
    return dynamic_cast<Imap::Mailbox::TreeItemPart *>(target);
}
示例#9
0
文件: chatbox.cpp 项目: jesyspa/4DGo
void Chatbox::parseString(QString str) {
	if (str[0] != '!') {
		emit message(str);
		return;
	}
	str[0] = ' ';
	str = str.trimmed().toLower();
	QStringList list = str.split(QRegExp("\\s+"));
	QStringList::const_iterator it = list.begin();
	if (it->contains(rgxPos)) {
		emit playStone(Position(*it));
	} else if (*it == "pass" || *it == "p") {
		emit pass();
	} else if (*it == "undo" || *it == "u") {
		emit undo();
	} else if (*it == "kill" || *it == "k") {
		if (++it == list.end() || !it->contains(rgxPos))
			display("Expected position as second argument.");
		else
			emit kill(Position(*it));
	} else if (*it == "exit" || *it == "e") {
		emit exit();
	} else if (*it == "connect" || *it == "c") {
		if (++it != list.end()) {
			emit setHost(*it);
			if (++it != list.end()) {
				emit setPort(it->toInt());
			}
		}
		emit cl_connect();
	} else if (*it == "disconnect" || *it == "dc") {
		emit cl_disconnect();
	} else if (*it == "yes" || *it == "y") {
		emit confirm(true);
	} else if (*it == "no" || *it == "n") {
		emit confirm(false);
	} else if (*it == "save" || *it == "s") {
		if (++it == list.end())
			display("Expected filename as second argument.");
		else
			emit writeLogToDisk(*it);
	} else if (*it == "help" || *it == "h" ) {
		display("4DGo -- A four-dimensional goban for online play.");
		display("All commands start with a '!'. Any input that does not is treated as a chat message. All comands are case-insensitive.");
		display("  Commands:");
		display("!connect [hostname] [port]: connect to the game server. By default, localhost:15493 will be used.");
		display("!disconnect: break connection to server and clear the goban.");
		display("!A4d4: on slice A4 (top-left), on intersection d4 (top-right).");
		display("!pass: end your turn without playing a stone.");
		display("!undo: request that your last move be undone.");
		display("!yes: allow the action your opponent requested (usually an undo or kill).");
		display("!yes: refuse to allow the action your opponent requested (usually an undo or kill).");
		display("!kill: request a certain group to be immediately taken off the board. Useful in endgame, to not need to play out all captures.");
		display("!save filename: save the current history to file filename.");
		display("!exit: disconnect and close the window.");
	} else {
		tbCBox_->append(QString("Unknown command: ")+*it);
	}
}
示例#10
0
std::vector<std::string> const MergeGeometriesDialog::getSelectedGeometries() const
{
	std::vector<std::string> indexList;
	QStringList const& list (_selGeo->stringList());
	for (QStringList::const_iterator it = list.begin(); it != list.end(); ++it)
		indexList.push_back(it->toStdString());
	return indexList;
}
void MakefileFactory::setEnvironment(const QStringList &env)
{
    for (QStringList::const_iterator it = env.begin(); it != env.end(); ++it) {
        int idx = it->indexOf(QLatin1Char('='));
        if (idx >= 0)
            m_environment.insert(it->left(idx), it->mid(idx + 1));
    }
}
void QgsSimpleLineSymbolLayerV2::applyDataDefinedSymbology( QgsSymbolV2RenderContext& context, QPen& pen, QPen& selPen, double& offset )
{
  //data defined properties
  double scaledWidth = 0;
  if ( mStrokeWidthExpression )
  {
    scaledWidth = mStrokeWidthExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble()
                  * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit );
    pen.setWidthF( scaledWidth );
    selPen.setWidthF( scaledWidth );
  }
  else if ( context.renderHints() & QgsSymbolV2::DataDefinedSizeScale )
  {
    scaledWidth = mWidth * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mWidthUnit );
    pen.setWidthF( scaledWidth );
    selPen.setWidthF( scaledWidth );
  }

  //color
  if ( mStrokeColorExpression )
  {
    pen.setColor( QgsSymbolLayerV2Utils::decodeColor( mStrokeColorExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString() ) );
  }

  //offset
  offset = mOffset;
  if ( mLineOffsetExpression )
  {
    offset = mLineOffsetExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toDouble();
  }

  //dash dot vector
  if ( mDashPatternExpression )
  {
    QVector<qreal> dashVector;
    QStringList dashList = mDashPatternExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString().split( ";" );
    QStringList::const_iterator dashIt = dashList.constBegin();
    for ( ; dashIt != dashList.constEnd(); ++dashIt )
    {
      dashVector.push_back( dashIt->toDouble() * QgsSymbolLayerV2Utils::lineWidthScaleFactor( context.renderContext(), mCustomDashPatternUnit ) / mPen.widthF() );
    }
    pen.setDashPattern( dashVector );
  }

  //join style
  if ( mJoinStyleExpression )
  {
    QString joinStyleString = mJoinStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    pen.setJoinStyle( QgsSymbolLayerV2Utils::decodePenJoinStyle( joinStyleString ) );
  }

  //cap style
  if ( mCapStyleExpression )
  {
    QString capStyleString = mCapStyleExpression->evaluate( const_cast<QgsFeature*>( context.feature() ) ).toString();
    pen.setCapStyle( QgsSymbolLayerV2Utils::decodePenCapStyle( capStyleString ) );
  }
}
示例#13
0
QStringList CMDLineRegistryUtils::getParameterValuesByWords( const QString & paramName, int startWith ) {
    QStringList words;
    QStringList res = getParameterValues( paramName, startWith );
    QStringList::const_iterator it = res.constBegin();
    while( it != res.constEnd() ) {
        words << it->split( QRegExp("\\s"), QString::SkipEmptyParts );
        ++it;
    }
    return words;
}
DataSetPtr readSelectedFeatures(char *filename, FeatureMappingPtr featureMapping)
{
	SelectedFeatures selectedFeatures;
	OverlappingFeatures overlappingFeatures;

	QFile featureFile(filename);
	if (!featureFile.open(QFile::ReadOnly))
	{
		qCritical() << "Could not open" << filename << "for reading!";
		return QSharedPointer<DataSet>(new DataSet(selectedFeatures, overlappingFeatures));
	}

	QTextStream featureStream(&featureFile);

	while(!featureStream.atEnd())
	{
		QString featureLine(featureStream.readLine());		
		QStringList lineParts = featureLine.split("\t");
		size_t featureNr = lineParts[0].toULong();
		QString featureName = (*featureMapping)[featureNr];

		SelectedFeature feature(featureName, lineParts[1].toDouble(),
			lineParts[2].toDouble());
		selectedFeatures.push_back(feature);

		QString overlapLine(featureStream.readLine());
		QStringList overlapParts = overlapLine.split("\t", QString::SkipEmptyParts);

		QVector<OverlappingFeature> overlaps;
		double normOverlapSum = 0.0;
		double normActivationSum = 0.0;
		for (QStringList::const_iterator iter = overlapParts.begin();
			iter != overlapParts.end(); ++iter)
		{
			QStringList overlap = iter->split('#');

			double normOverlap = overlap[0].toDouble();
			if (normOverlap > 0.0)
				normOverlapSum += normOverlap;
			else if (normOverlap < 0.0)
				normActivationSum += fabs(normOverlap);

			OverlappingFeature overlappingFeature(
				(*featureMapping)[overlap[1].toUInt()],
				normOverlap);
			overlaps.push_back(overlappingFeature);
		}


		overlappingFeatures[featureName] = Overlap(normOverlapSum, normActivationSum,
			overlaps);
	}

	return QSharedPointer<DataSet>(new DataSet(selectedFeatures, overlappingFeatures));
}
示例#15
0
bool QDesigner::parseCommandLineArgs(QStringList &fileNames, QString &resourceDir)
{
    const QStringList args = arguments();
    const QStringList::const_iterator acend = args.constEnd();
    QStringList::const_iterator it = args.constBegin();
    for (++it; it != acend; ++it) {
        const QString &argument = *it;
        do {
            // Arguments
            if (!argument.startsWith(QLatin1Char('-'))) {
                if (!fileNames.contains(argument))
                    fileNames.append(argument);
                break;
            }
            // Options
            if (argument == QStringLiteral("-server")) {
                m_server = new QDesignerServer();
                printf("%d\n", m_server->serverPort());
                fflush(stdout);
                break;
            }
            if (argument == QStringLiteral("-client")) {
                bool ok = true;
                if (++it == acend) {
                    qWarning("** WARNING The option -client requires an argument");
                    return false;
                }
                const quint16 port = it->toUShort(&ok);
                if (ok) {
                    m_client = new QDesignerClient(port, this);
                } else {
                    qWarning("** WARNING Non-numeric argument specified for -client");
                    return false;
                }
                break;
            }
            if (argument == QStringLiteral("-resourcedir")) {
                if (++it == acend) {
                    qWarning("** WARNING The option -resourcedir requires an argument");
                    return false;
                }
                resourceDir = QFile::decodeName(it->toLocal8Bit());
                break;
            }
            if (argument == QStringLiteral("-enableinternaldynamicproperties")) {
                QDesignerPropertySheet::setInternalDynamicPropertiesEnabled(true);
                break;
            }
            const QString msg = QString::fromUtf8("** WARNING Unknown option %1").arg(argument);
            qWarning("%s", qPrintable(msg));
        } while (false);
    }
    return true;
}
示例#16
0
bool QgsDatumTransformDialog::testGridShiftFileAvailability( QTreeWidgetItem* item, int col ) const
{
  if ( !item )
  {
    return false;
  }

  QString itemText = item->text( col );
  if ( itemText.isEmpty() )
  {
    return false;
  }

  char* projLib = getenv( "PROJ_LIB" );
  if ( !projLib ) //no information about installation directory
  {
    item->setToolTip( col, tr( "The PROJ_LIB enviroment variable not set." ) );
    return false;
  }

  QStringList itemEqualSplit = itemText.split( "=" );
  QString filename;
  for ( int i = 1; i < itemEqualSplit.size(); ++i )
  {
    if ( i > 1 )
    {
      filename.append( "=" );
    }
    filename.append( itemEqualSplit.at( i ) );
  }

  QDir projDir( projLib );
  if ( projDir.exists() )
  {
    //look if filename in directory
    QStringList fileList = projDir.entryList();
    QStringList::const_iterator fileIt = fileList.constBegin();
    for ( ; fileIt != fileList.constEnd(); ++fileIt )
    {
#if defined(Q_OS_WIN)
      if ( fileIt->compare( filename, Qt::CaseInsensitive ) == 0 )
#else
      if ( fileIt->compare( filename ) == 0 )
#endif //Q_OS_WIN
      {
        return true;
      }
    }
    item->setToolTip( col, tr( "File '%1' not found in directory '%2'" ).arg( filename ).arg( projDir.absolutePath() ) );
    return false; //not found in PROJ_LIB directory
  }
  item->setToolTip( col, tr( "The directory '%1' set to PROJ_LIB variable doesn't exist" ).arg( projDir.absolutePath() ) );
  return false;
}
示例#17
0
void OCamlWatch::restoreWatches()
{
    QStringList vars = Options::get_opt_strlst( objectName()+"_VARIABLES" );
    for (QStringList::const_iterator itVar = vars.begin(); itVar != vars.end() ; ++itVar)
    {
        QString variable = *itVar;
        ++itVar;
        bool displayed = itVar->toInt() != 0;
        watch( variable, displayed );
    }
}
示例#18
0
bool DynamicObjectImp::setAttributeByPath(QStringList pathComponents, DataVariant& value, bool swap)
{
   if (!value.isValid())
   {
      return false;
   }

   QString finalName = pathComponents.back();
   pathComponents.pop_back();

   string loopType = "DynamicObject";
   DynamicObject* pLoopObj = dynamic_cast<DynamicObject*>(this);
   DynamicObject* pCurObj = pLoopObj;
   for (QStringList::const_iterator iter = pathComponents.begin();
      iter != pathComponents.end(); ++iter)
   {
      if (pLoopObj == NULL || loopType != "DynamicObject")
      {
         return false;
      }

      pCurObj = pLoopObj;
      DataVariant& attrValue = pCurObj->getAttribute(iter->toStdString());
      loopType = attrValue.getTypeName();
      pLoopObj = attrValue.getPointerToValue<DynamicObject>();

      if ((pLoopObj != NULL) && (loopType != "DynamicObject"))
      {
         return false;
      }

      if (pLoopObj == NULL)
      {
         FactoryResource<DynamicObject> pNewObj;
         if (pCurObj != NULL)
         {
            pCurObj->setAttribute(iter->toStdString(), *pNewObj.get());
            DataVariant& currentValue = pCurObj->getAttribute(iter->toStdString());
            loopType = currentValue.getTypeName();
            pLoopObj = currentValue.getPointerToValue<DynamicObject>();
         }
      }
   }

   if (pLoopObj == NULL || loopType != "DynamicObject")
   {
      return false;
   }

   pCurObj = pLoopObj;
   DynamicObjectImp* const pCurObjImp = dynamic_cast<DynamicObjectImp*>(pCurObj);
   VERIFY(pCurObjImp != NULL);
   return pCurObjImp->setAttribute(finalName.toStdString(), value, swap);
}
QT_BEGIN_NAMESPACE

static QList<QByteArray> stringListToByteArray(const QStringList &l)
{
    if (l.empty())
        return QList<QByteArray>();
    QList<QByteArray> rc;
    const QStringList::const_iterator cend = l.constEnd();
    for (QStringList::const_iterator it = l.constBegin(); it != cend; ++it)
        rc += it->toUtf8();
    return rc;
}
示例#20
0
bool MercurialPlugin::parseStatus(DVcsJob *job) const
{
    if (job->status() != VcsJob::JobSucceeded) {
        mercurialDebug() << "Job failed: " << job->output();
        return false;
    }

    const QString dir = job->directory().absolutePath().append(QDir::separator());
    mercurialDebug() << "Job succeeded for " << dir;
    const QStringList output = job->output().split('\n', QString::SkipEmptyParts);
    QList<QVariant> filestatus;

    QSet<QUrl> conflictedFiles;

    QStringList::const_iterator it = output.constBegin();

    // FIXME: Revive this functionality and add tests for it!
    // conflicts first
//     for (; it != output.constEnd(); it++) {
//         QChar stCh = it->at(0);
//         if (stCh == '%') {
//             it++;
//             break;
//         }
// 
//         QUrl file = QUrl::fromLocalFile(it->mid(2).prepend(dir));
// 
//         VcsStatusInfo status;
//         status.setUrl(file);
//         // FIXME: conflicts resolved
//         status.setState(VcsStatusInfo::ItemHasConflicts);
// 
//         conflictedFiles.insert(file);
//         filestatus.append(qVariantFromValue(status));
//     }

    // standard statuses next
    for (; it != output.constEnd(); it++) {
        QChar stCh = it->at(0);

        QUrl file = QUrl::fromLocalFile(it->mid(2).prepend(dir));

        if (!conflictedFiles.contains(file)) {
            VcsStatusInfo status;
            status.setUrl(file);
            status.setState(charToState(stCh.toLatin1()));
            filestatus.append(qVariantFromValue(status));
        }
    }

    job->setResults(qVariantFromValue(filestatus));
    return true;
}
static std::ostream& operator<<( std::ostream& stream, const QStringList& list )
{
    stream << "QStringList(";
    for( QStringList::const_iterator it = list.begin(); it != list.end(); ++it )
    {
        stream << " " << it->toLocal8Bit().data();
        if( it + 1 != list.end() )
            stream << ",";
    }
    stream << " )";
    return stream;
}
示例#22
0
  StringList StringListUtils::fromQStringList(const QStringList& rhs)
  {
    StringList sl;
    sl.reserve(rhs.size());

    for (QStringList::const_iterator it = rhs.begin(); it != rhs.end(); ++it)
    {
      sl.push_back(it->toStdString());
    }

    return sl;
  }
QString CreateDesktopEntryOperation::absoluteFileName()
{
    const QString filename = arguments().first();

    // give filename is already absolute
    if (QFileInfo(filename).isAbsolute())
        return filename;

    // we're not searching for the first time, let's re-use the old value
    if (hasValue(QLatin1String("directory")))
        return QDir(value(QLatin1String("directory")).toString()).absoluteFilePath(filename);

    const QProcessEnvironment env;
    QStringList XDG_DATA_DIRS = env.value(QLatin1String("XDG_DATA_DIRS")).split(QLatin1Char(':'),
        QString::SkipEmptyParts);
    QStringList XDG_DATA_HOME = env.value(QLatin1String("XDG_DATA_HOME")).split(QLatin1Char(':'),
        QString::SkipEmptyParts);

    XDG_DATA_DIRS.push_back(QLatin1String("/usr/share")); // default path
    XDG_DATA_HOME.push_back(QDir::home().absoluteFilePath(QLatin1String(".local/share"))); // default path

    const QStringList directories = XDG_DATA_DIRS + XDG_DATA_HOME;
    QString directory;
    for (QStringList::const_iterator it = directories.begin(); it != directories.end(); ++it) {
        if (it->isEmpty())
            continue;

        directory = QDir(*it).absoluteFilePath(QLatin1String("applications"));
        QDir dir(directory);

        // let's see whether this dir exists or we're able to create it
        if (!dir.exists() && !QDir().mkpath(directory))
            continue;

        // we just try whether we're able to open the file in ReadWrite
        QFile file(QDir(directory).absoluteFilePath(filename));
        const bool existed = file.exists();
        if (!file.open(QIODevice::ReadWrite))
            continue;
        file.close();
        if (!existed)
            file.remove();
        break;
    }

    if (!QDir(directory).exists())
        QDir().mkpath(directory);

    setValue(QLatin1String("directory"), directory);

    return QDir(directory).absoluteFilePath(filename);
}
示例#24
0
QList<int> Options::get_opt_intlst ( const QString &opt, const QList<int> &def )
{
    QStringList defs;
    for (QList<int>::const_iterator itDef = def.begin(); itDef != def.end(); ++itDef )
        defs << QString::number( *itDef );
    QStringList rets = get_opt_strlst( opt, defs );

    QList<int> ret;
    for (QStringList::const_iterator itStr = rets.begin(); itStr != rets.end(); ++itStr )
        ret << itStr->toInt();

    return ret;
}
示例#25
0
void DelaylineDetector::loadSettings(CASSSettings &s)
{
  s.beginGroup(QString::fromStdString(_name));
  DelaylineType delaylinetype
      (static_cast<DelaylineType>(s.value("DelaylineType",Hex).toInt()));
  s.beginGroup("MCP");
  _mcp.loadSettings(s);
  s.endGroup();
  switch (delaylinetype)
  {
  case Hex:
    s.beginGroup("ULayer");
    _anodelayers['U'].loadSettings(s);
    s.endGroup();
    s.beginGroup("VLayer");
    _anodelayers['V'].loadSettings(s);
    s.endGroup();
    s.beginGroup("WLayer");
    _anodelayers['W'].loadSettings(s);
    s.endGroup();
    break;
  case Quad:
    s.beginGroup("XLayer");
    _anodelayers['X'].loadSettings(s);
    s.endGroup();
    s.beginGroup("YLayer");
    _anodelayers['Y'].loadSettings(s);
    s.endGroup();
    break;
  default:
    throw invalid_argument("DelaylineDetector::loadSettings(): delayline type '" +
                           toString(delaylinetype) + "' does not exist");
    break;
  }
  _analyzer =
      DetectorAnalyzerBackend::instance(static_cast<DetectorAnalyzerType>(s.value("AnalysisMethod",DelaylineSimple).toInt()));
  _analyzer->loadSettings(s, *this);
  s.beginGroup("Particles");
  _particles.clear();
  QStringList particlesNameList(s.childGroups());
  QStringList::const_iterator pNamesIt (particlesNameList.begin());
  for (; pNamesIt != particlesNameList.end();++pNamesIt)
  {
    s.beginGroup(*pNamesIt);
    string particleName (pNamesIt->toStdString());
    _particles[particleName].loadSettings(s);
    s.endGroup();
  }
  s.endGroup();
  s.endGroup();
}
示例#26
0
void NRemoteFSBrowser::send_favorites(const QStringList &favs)
{
  SignalFrame frame("set_favorites", uri(), SERVER_CORE_PATH);
  QStringList::const_iterator it = favs.begin();
  std::vector<std::string> vect( favs.count() );

  for( int i = 0 ; it != favs.end() ; ++it, ++i )
    vect[i] = it->toStdString();

  frame.set_array("favorite_dirs", common::class_name<std::string>(), common::option_vector_to_str(vect, ";"), ";");

  frame.options().flush();

  NetworkQueue::global()->send( frame, NetworkQueue::IMMEDIATE );
}
示例#27
0
void JointMotorI::getAllMotorState(MotorStateMap &mstateMap, const Ice::Current&)
{
	for (QStringList::const_iterator name = jointIDs.constBegin() ; name != jointIDs.constEnd() ; ++name)
	{
		InnerModelNode *node = innerModel->getNode(*name);
		if (dynamic_cast<InnerModelJoint*>(node) != NULL)
		{
			states[name->toStdString()].pos = dynamic_cast<InnerModelJoint*>(node)->getAngle();
		}
		else if (dynamic_cast<InnerModelPrismaticJoint*>(node) != NULL)
		{
			states[name->toStdString()].pos = dynamic_cast<InnerModelPrismaticJoint*>(node)->getPosition();
		}
	}
	mstateMap = states;
}
示例#28
0
/**Moves the entry in the line edit new2Add_edit to the
*  listbox toAdd_List, expanding any run number lists
*/
void SANSAddFiles::add2Runs2Add() {
  // split comma separated file names or run numbers into a list
  ArrayProperty<std::string> commaSep(
      "unusedName", m_SANSForm->new2Add_edit->text().toStdString());
  const std::vector<std::string> nam = commaSep;

  for (std::vector<std::string>::const_iterator i = nam.begin(); i != nam.end();
       ++i) { // each comma separated item could be a range of run numbers
              // specified with a ':' or '-'
    QStringList ranges;
    std::vector<int> runNumRanges;
    try { // if the entry is in the form 454:456, runNumRanges will be filled
          // with the integers ({454, 455, 456}) otherwise it will throw
      appendValue(*i, runNumRanges);
      std::vector<int>::const_iterator num = runNumRanges.begin();
      for (; num != runNumRanges.end(); ++num) {
        ranges.append(QString::number(*num));
      }
    } catch (boost::bad_lexical_cast &) { // this means that we don't have a
                                          // list of integers, treat it as full
                                          // (and valid) filename
      ranges.append(QString::fromStdString(*i));
    }

    for (QStringList::const_iterator k = ranges.begin(); k != ranges.end();
         ++k) {
      // Don't display the full file path in the box, it's too long
      QListWidgetItem *newL = insertListFront(QFileInfo(*k).fileName());
      newL->setData(Qt::WhatsThisRole, QVariant(*k));
      // Put the full path in the tooltip so people can see it if they want to
      // do this with the file finding functionality of the FileProperty
      FileProperty search("dummy", k->toStdString(), FileProperty::Load,
                          std::vector<std::string>(), Direction::Input);
      if (search.isValid() == "") { // this means the file was found
        newL->setToolTip(QString::fromStdString(search.value()));

        // If we don't have an event workspace data set, then we disable the
        // event options
        if (!isEventWorkspace(QString::fromStdString(search.value()))) {
          setBinningOptions(false);
        }
      }
    }
  }
  m_SANSForm->new2Add_edit->clear();
}
示例#29
0
double convertToNumber(const QStringList::const_iterator & strPtr, QStringList * lineStrList, bool & ok)
{  
  double d = -1;
  ok = false;
  if(strPtr != lineStrList->end())
    d = strPtr->toDouble(&ok);
  return d;
}
示例#30
0
void GuiBibtex::setSelectedBibs(QStringList const sl)
{
	selected_model_.clear();
	QStringList headers;
	headers << qt_("Database")
		<< qt_("File Encoding");
	selected_model_.setHorizontalHeaderLabels(headers);
	bool const moreencs = usingBiblatex() && sl.count() > 1;
	selectedLV->setColumnHidden(1, !moreencs);
	selectedLV->verticalHeader()->setVisible(false);
	selectedLV->horizontalHeader()->setVisible(moreencs);
	if (moreencs) {
		bibEncodingLA->setText(qt_("General E&ncoding:"));
		bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
					      "encoding than the LyX document, specify it here. "
					      "If indivivual databases have different encodings, "
					      "you can set it in the list above."));
	} else {
		bibEncodingLA->setText(qt_("E&ncoding:"));
		bibEncodingCO->setToolTip(qt_("If your bibliography databases use a different "
					      "encoding than the LyX document, specify it here"));
	}
	QStringList::const_iterator it  = sl.begin();
	QStringList::const_iterator end = sl.end();
	for (int i = 0; it != end; ++it, ++i) {
		QStandardItem * si = new QStandardItem();
		si->setData(*it);
		si->setText(*it);
		si->setToolTip(*it);
		si->setEditable(false);
		selected_model_.insertRow(i, si);
		QComboBox * cb = new QComboBox;
		cb->addItem(qt_("General Encoding"), "general");
		cb->addItem(qt_("Document Encoding"), "auto");
		QMap<QString, QString>::const_iterator it = encodings_.constBegin();
		while (it != encodings_.constEnd()) {
			cb->addItem(it.key(), it.value());
			++it;
		}
		cb->setToolTip(qt_("If this bibliography database uses a different "
				   "encoding than specified below, set it here"));
		selectedLV->setIndexWidget(selected_model_.index(i, 1), cb);
	}
	editPB->setEnabled(deletePB->isEnabled());
}