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);
}
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;
}
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());
}
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;
}
Exemple #5
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;
}
  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;
  }
Exemple #7
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();
}
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 );
}
Exemple #9
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();
}
void SQLiteDatabaseConnection::open(QString dbConnectionString)
{
    int rc; //return-Wert speichern
    QFile file(dbConnectionString);
    bool dbExisted = file.exists();
    
    rc = sqlite3_open_v2(dbConnectionString.toStdString().c_str(), &_db, 
		SQLITE_OPEN_READWRITE |
		SQLITE_OPEN_CREATE |
		SQLITE_OPEN_FULLMUTEX,
		NULL);
    
    if (rc != SQLITE_OK)
    {   //Es gab einen Fehler beim Öffnen der Datenbank.
        _dbOpen = false;
        sqlite3_close(_db);
        std::cerr << "Failed to open database file \"" << dbConnectionString.toStdString()
            << "\"" << std::endl;
        return;
    }
    
    //Erstelle Tabellen nur, wenn die Datei vorher nicht existierte.
    if (!dbExisted)
        _dbOpen = createTables();
    else
    {
        _dbOpen = true;
        
        //Geschwindigkeit der DB erhöhen
        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;";
        QStringList::const_iterator it;
        for (it = statements.constBegin(); it != statements.constEnd(); it++)
        {
            execCreateTableStatement(it->toStdString());
        }
    }
}
bool SQLiteDatabaseConnection::createIndexes()
{
	bool retVal = true;
	
    //Liste von auszuführenden Statements erstellen
	QStringList statements;
	statements << "CREATE INDEX IF NOT EXISTS EDGES_STARTNODE_INDEX ON EDGES(STARTNODE);";
	statements << "CREATE INDEX IF NOT EXISTS EDGES_ENDNODE_INDEX ON EDGES(ENDNODE);";
    
    //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;
}
Exemple #12
0
const vector<string> &SymbolManager::getAvailableSymbolNames() const
{
   static vector<string> symbolNames;
   symbolNames.clear();

   string annoPath;
   const Filename* pSupportFilesPath = ConfigurationSettings::getSettingSupportFilesPath();
   if (pSupportFilesPath != NULL)
   {
      annoPath = pSupportFilesPath->getFullPathAndName();
   }

   QDir dir(QString::fromStdString(annoPath + SLASH + "Annotation"), "*.cgm");
   QStringList entryList = dir.entryList();
   
   for (QStringList::const_iterator iter = entryList.begin(); 
      iter != entryList.end(); ++iter)
   {
      symbolNames.push_back(iter->toStdString());
   }

   return symbolNames;
}
  bool CEPasteDialog::acceptVaspFormat()
  {
    // Validate identities field
    QStringList idents = ui.edit_identities->text().simplified()
      .split(QRegExp("\\s+|,|;"));

    if (static_cast<unsigned int>(idents.size()) != m_numAtomTypes) {
      QMessageBox::critical
        (this,
         tr("Bad Compostion"),
         tr("The identities field must contain the same number of "
            "space delimited entries as line 6 of the POSCAR."));
      return false;
    }

    bool ok;
    QList<unsigned int> compAtomicNums;
    QList<unsigned int> compCounts;

    for (QStringList::const_iterator
           it = idents.constBegin(),
           it_end = idents.constEnd();
         it != it_end; ++it) {
      // Attempt to use the string as a uint
      unsigned int atomicNum = it->toUInt(&ok);
      // If this doesn't work, try passing the string to OB's translator
      if (!ok) {
        atomicNum = OpenBabel::etab.GetAtomicNum(it->toStdString().c_str());
      }
      compAtomicNums.append(atomicNum);
    }

    QStringList lines = m_text.split("\n");

    unsigned int lineIndex = 0;
    const QString *line;
    QStringList lineList;
    unsigned int numAtoms = 0;
    QList<Eigen::Vector3d> positions;
    QList<unsigned int> atomicNums;
    Eigen::Matrix3d cellMatrix;

    // First line is comment
    line = &lines[lineIndex++];

    // Next is a scale factor, single float
    line = &lines[lineIndex++];
    double scale = line->toDouble(&ok);
    if (!ok) {
      return false;
    }

    // Next three lines are cell vectors, three floats
    for (int vecInd = 0; vecInd < 3; ++vecInd) {
      line = &lines[lineIndex++];
      lineList = line->simplified().split(QRegExp("\\s+|,|;"));
      if (lineList.size() != 3) {
        return false;
      }
      for (int i = 0; i < 3; ++i) {
        double v = lineList.at(i).toDouble(&ok);
        if (!ok) {
          return false;
        }
        cellMatrix(vecInd, i) = v * scale;
      }
    }

    // Next line is a list of unsigned integers (composition)
    line = &lines[lineIndex++];
    lineList = line->simplified().split(QRegExp("\\s+|,|;"));
    // If vasp >= 5.x, this may be a list of atomic symbols. Skip it if so,
    // since the user should have already specified/verified the composition
    // in the GUI by this point.
    if (lineList.isEmpty()) {
      return false;
    }
    bool vaspVersionLessThan5;
    lineList.first().toUInt(&vaspVersionLessThan5);
    if (!vaspVersionLessThan5) {
      line = &lines[lineIndex++];
      lineList = line->simplified().split(QRegExp("\\s+|,|;"));
    }
    for (QStringList::const_iterator it = lineList.constBegin(),
         it_end = lineList.constEnd(); it != it_end; ++it) {
      unsigned int v = it->toUInt(&ok);
      if (!ok) {
        return false;
      }
      numAtoms += v;
      compCounts.append(v);
    }

    // Next line is a string. First character is important:
    line = &lines[lineIndex++];
    if (line->size() && line->at(0).toLower() == QChar('s')){
      // If first letter is s (selective dynamics), skip one more line
      line = &lines[lineIndex++];
    }
    // Current line is a string. If it starts with K, k, C, or c,
    // positions are in cartesian units. Otherwise, reciprocal units.
    bool isCartesian = false;
    if (line->size() &&
        (line->at(0).toLower() == QChar('k') ||
         line->at(0).toLower() == QChar('c') ) ) {
      isCartesian = true;
    }

    // Next [numAtoms] lines are vectors. So long as they're ok, we
    // have a POSCAR or CONTCAR!
    for (unsigned int i = 0; i < numAtoms; ++i) {
      line = &lines[lineIndex++];
      lineList = line->simplified().split(QRegExp("\\s+|,|;"));
      if (lineList.size() != 3) {
        return false;
      }
      Eigen::Vector3d vec;
      for (int i = 0; i < 3; ++i) {
        double v = lineList.at(i).toDouble(&ok);
        if (!ok) {
          return false;
        }
        vec(i) = v;
      }
      positions.append(vec);
    }

    // Build list of atomic numbers
    Q_ASSERT(compAtomicNums.size() == compCounts.size());
    for (int i = 0; i < compCounts.size(); ++i) {
      for (unsigned int j = 0; j < compCounts.at(i); ++j) {
        atomicNums.append(compAtomicNums.at(i));
      }
    }
    Q_ASSERT(atomicNums.size() == positions.size());

    // Set unit cell
    QWriteLocker locker (m_molecule->lock());
    OpenBabel::OBUnitCell *cell =  m_molecule->OBUnitCell();
    cell->SetData(Eigen2OB(cellMatrix));

    // Convert to cartesian coords if necessary:
    if (!isCartesian) {
      for (QList<Eigen::Vector3d>::iterator
             it = positions.begin(),
             it_end = positions.end();
           it != it_end; ++it) {
        *it = OB2Eigen(cell->FractionalToCartesian
                       (Eigen2OB(*it)));
      }
    }

    // Remove old atoms
    QList<Avogadro::Atom*> oldAtoms = m_molecule->atoms();
    for (QList<Avogadro::Atom*>::iterator
           it = oldAtoms.begin(),
           it_end = oldAtoms.end();
         it != it_end;
         ++it) {
      m_molecule->removeAtom(*it);
    }

    // Add new atoms
    for (int i = 0; i < positions.size(); ++i) {
      Atom *atom = m_molecule->addAtom();
      atom->setAtomicNumber(atomicNums.at(i));
      atom->setPos(positions.at(i));
    }

    return true;
  }
Exemple #14
0
  ExitCodes main_(int, const char **) override
  {
    //-------------------------------------------------------------
    // Parsing parameters
    //-------------------------------------------------------------

    String in = getStringOption_("in");
    String out_sirius = getStringOption_("out_sirius");
    String out_csifingerid = getStringOption_("out_fingerid");

    // needed for counting
    int number_compounds = getIntOption_("number"); 

    // Parameter for Sirius3
    QString executable = getStringOption_("executable").toQString();
    const QString profile = getStringOption_("profile").toQString();
    const QString elements = getStringOption_("elements").toQString();
    const QString database = getStringOption_("database").toQString();
    const QString isotope = getStringOption_("isotope").toQString();
    const QString noise = QString::number(getIntOption_("noise"));
    const QString ppm_max = QString::number(getIntOption_("ppm_max"));
    const QString candidates = QString::number(getIntOption_("candidates"));

    bool auto_charge = getFlag_("auto_charge");
    bool no_recalibration = getFlag_("no_recalibration");
    bool iontree = getFlag_("iontree");

    //-------------------------------------------------------------
    // Determination of the Executable
    //-------------------------------------------------------------

    // Parameter executable not provided
    if (executable.isEmpty())
    {
      const QProcessEnvironment env;
      const QString & qsiriuspathenv = env.systemEnvironment().value("SIRIUS_PATH");
      if (qsiriuspathenv.isEmpty())
      {
        writeLog_( "FATAL: Executable of Sirius could not be found. Please either use SIRIUS_PATH env variable or provide with -executable");
        return MISSING_PARAMETERS;
      }
      executable = qsiriuspathenv;
    }
    // Normalize file path
    QFileInfo file_info(executable);
    executable = file_info.canonicalFilePath();

    writeLog_("Executable is: " + executable);
    const QString & path_to_executable = File::path(executable).toQString();

    //-------------------------------------------------------------
    // Calculations
    //-------------------------------------------------------------
    PeakMap spectra;
    MzMLFile f;
    f.setLogType(log_type_);
    f.load(in, spectra);
    std::vector<String> subdirs;

    QString tmp_base_dir = File::getTempDirectory().toQString();
    QString tmp_dir = QDir(tmp_base_dir).filePath(File::getUniqueName().toQString());

    String tmp_ms_file = QDir(tmp_base_dir).filePath((File::getUniqueName() + ".ms").toQString());
    String out_dir = QDir(tmp_dir).filePath("sirius_out");

    //Write msfile
    SiriusMSFile::store(spectra, tmp_ms_file);

    // Assemble SIRIUS parameters
    QStringList process_params;
    process_params << "-p" << profile
                   << "-e" << elements
                   << "-d" << database
                   << "-s" << isotope
                   << "--noise" << noise
                   << "--candidates" << candidates
                   << "--ppm-max" << ppm_max
                   << "--quiet"
                   << "--output" << out_dir.toQString(); //internal output folder for temporary SIRIUS output file storage

    // Add flags
    if (no_recalibration)
    {
      process_params << "--no-recalibration";
    }
    if (!out_csifingerid.empty())
    {
      process_params << "--fingerid";
    }
    if (iontree)
    {
      process_params << "--iontree";
    }
    if (auto_charge)
    {
      process_params << "--auto-charge";
    }

    process_params << tmp_ms_file.toQString();

    // The actual process
    QProcess qp;
    qp.setWorkingDirectory(path_to_executable); //since library paths are relative to sirius executable path
    qp.start(executable, process_params); // does automatic escaping etc... start
    std::stringstream ss;
    ss << "COMMAND: " << executable.toStdString();
    for (QStringList::const_iterator it = process_params.begin(); it != process_params.end(); ++it)
    {
        ss << " " << it->toStdString();
    }
    LOG_DEBUG << ss.str() << endl;
    writeLog_("Executing: " + String(executable));
    writeLog_("Working Dir is: " + path_to_executable);
    const bool success = qp.waitForFinished(-1); // wait till job is finished
    qp.close();

    if (success == false || qp.exitStatus() != 0 || qp.exitCode() != 0)
    {
      writeLog_( "FATAL: External invocation of Sirius failed. Standard output and error were:");
      const QString sirius_stdout(qp.readAllStandardOutput());
      const QString sirius_stderr(qp.readAllStandardOutput());
      writeLog_(sirius_stdout);
      writeLog_(sirius_stderr);
      writeLog_(String(qp.exitCode()));

      return EXTERNAL_PROGRAM_ERROR;
    }

    //-------------------------------------------------------------
    // writing output
    //-------------------------------------------------------------

    //Extract path to subfolders (sirius internal folder structure)
    QDirIterator it(out_dir.toQString(), QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::NoIteratorFlags);
    while (it.hasNext())
    {
      subdirs.push_back(it.next());
    }

    //sort vector path list
    std::sort(subdirs.begin(), subdirs.end(), sortByScanIndex);

    //Convert sirius_output to mztab and store file
    MzTab sirius_result;
    MzTabFile siriusfile;
    SiriusMzTabWriter::read(subdirs, number_compounds, sirius_result);
    siriusfile.store(out_sirius, sirius_result);

    //Convert sirius_output to mztab and store file
    if (out_csifingerid.empty() == false)
    {
      MzTab csi_result;
      MzTabFile csifile;
      CsiFingerIdMzTabWriter::read(subdirs, number_compounds, csi_result);
      csifile.store(out_csifingerid, csi_result);
    }

    //clean tmp directory if debug level < 2
    if (debug_level_ >= 2)
    {
      writeDebug_("Keeping temporary files in directory '" + String(tmp_dir) + " and msfile at this location "+ tmp_ms_file + ". Set debug level to 1 or lower to remove them.", 2);
    }
    else
    {
      if (tmp_dir.isEmpty() == false)
      {
        writeDebug_("Deleting temporary directory '" + String(tmp_dir) + "'. Set debug level to 2 or higher to keep it.", 0);
        File::removeDir(tmp_dir);
      }
      if (tmp_ms_file.empty() == false)
      {
        writeDebug_("Deleting temporary msfile '" + tmp_ms_file + "'. Set debug level to 2 or higher to keep it.", 0);
        File::remove(tmp_ms_file); // remove msfile
      }
    }

    return EXECUTION_OK;
  }