Beispiel #1
0
void TeaLeafReader::generateProjectTree(CMakeProjectNode *root, const QList<const FileNode *> &allFiles)
{
    if (m_files.size() == 0)
        return;

    root->setDisplayName(m_projectName);

    // Delete no longer necessary file watcher based on m_cmakeFiles:
    const QSet<FileName> currentWatched
            = transform(m_watchedFiles, [](CMakeFile *cmf) { return cmf->filePath(); });
    const QSet<FileName> toWatch = m_cmakeFiles;
    QSet<FileName> toDelete = currentWatched;
    toDelete.subtract(toWatch);
    m_watchedFiles = filtered(m_watchedFiles, [&toDelete](Internal::CMakeFile *cmf) {
            if (toDelete.contains(cmf->filePath())) {
                delete cmf;
                return false;
            }
            return true;
        });

    // Add new file watchers:
    QSet<FileName> toAdd = toWatch;
    toAdd.subtract(currentWatched);
    foreach (const FileName &fn, toAdd) {
        CMakeFile *cm = new CMakeFile(this, fn);
        DocumentManager::addDocument(cm);
        m_watchedFiles.insert(cm);
    }
Beispiel #2
0
QList<QChar> EPath::availableDriveLetters() {
	QSet<QChar> letters;
	QString alpha = "abcdefghijklmnopqrstuvwxyz"; // FIXME: find a better way to get the latin alphabet
	for (int i=0; i < alpha.size(); i++)
		letters << alpha[i];
	return letters.subtract(existingDriveLetters().toSet()).toList();
}
void populateMenu(QSet<ActionInterface* > &actionInterfaces,
                  const QByteArray &category,
                  QMenu* menu,
                  const SelectionContext &selectionContext)
{
    QSet<ActionInterface* > matchingFactories = findMembers(actionInterfaces, category);

    actionInterfaces.subtract(matchingFactories);

    QList<ActionInterface* > matchingFactoriesList = matchingFactories.toList();
    Utils::sort(matchingFactoriesList, [](ActionInterface *l, ActionInterface *r) {
        return l->priority() > r->priority();
    });

    foreach (ActionInterface* actionInterface, matchingFactoriesList) {
        if (actionInterface->type() == ActionInterface::ContextMenu) {
            actionInterface->currentContextChanged(selectionContext);
            QMenu *newMenu = actionInterface->action()->menu();
            if (newMenu && !newMenu->title().isEmpty())
                menu->addMenu(newMenu);

            //recurse

            populateMenu(actionInterfaces, actionInterface->menuId(), newMenu, selectionContext);
       } else if (actionInterface->type() == ActionInterface::ContextMenuAction
                  || actionInterface->type() == ActionInterface::Action) {
           QAction* action = actionInterface->action();
           actionInterface->currentContextChanged(selectionContext);
           action->setIconVisibleInMenu(false);
           menu->addAction(action);
       }
    }
}
	bool PluginManager::setData (const QModelIndex& index,
			const QVariant& data, int role)
	{
		if (index.column () != 0 ||
				role != Qt::CheckStateRole)
			return false;

		QPluginLoader_ptr loader = AvailablePlugins_.at (index.row ());

		if (!data.toBool () &&
				PluginContainers_.contains (loader))
		{
			PluginTreeBuilder builder;
			builder.AddObjects (Plugins_);
			builder.Calculate ();

			QSet<QObject*> oldSet = QSet<QObject*>::fromList (builder.GetResult ());

			builder.RemoveObject (loader->instance ());
			builder.Calculate ();

			const QSet<QObject*>& newSet = QSet<QObject*>::fromList (builder.GetResult ());
			oldSet.subtract (newSet);

			oldSet.remove (loader->instance ());

			if (!oldSet.isEmpty ())
			{
				QStringList pluginNames;
				Q_FOREACH (QObject *obj, oldSet)
				{
					IInfo *ii = qobject_cast<IInfo*> (obj);
					pluginNames << (ii->GetName () + " (" + ii->GetInfo () + ")");
				}
Beispiel #5
0
void MThreadPool::waitForDone(void)
{
    QMutexLocker locker(&m_priv->m_lock);
    while (true)
    {
        while (!m_priv->m_delete_threads.empty())
        {
            m_priv->m_delete_threads.back()->wait();
            delete m_priv->m_delete_threads.back();
            m_priv->m_delete_threads.pop_back();
        }

        if (m_priv->m_running && !m_priv->m_run_queues.empty())
        {
            m_priv->m_wait.wait(locker.mutex());
            continue;
        }

        QSet<MPoolThread*> working = m_priv->m_running_threads;
        working = working.subtract(m_priv->m_avail_threads);
        if (working.empty())
            break;
        m_priv->m_wait.wait(locker.mutex());
    }
}
Beispiel #6
0
NFA RE2NFA::parseSet()
{
    QSet<InputType> set;
    bool negate = false;

    next(TOK_STRING);

    do {
        Q_ASSERT(symbol().lexem.length() == 1);
        // ###
        QChar ch = symbol().lexem.at(0);
        if (set.isEmpty() && ch == QLatin1Char('^')) {
            negate = true;
            continue;
        }

        // look ahead for ranges like a-z
        bool rangeFound = false;
        if (test(TOK_STRING)) {
            if (symbol().lexem.length() == 1
                && symbol().lexem.at(0) == QLatin1Char('-')) {
                next(TOK_STRING);
                Q_ASSERT(symbol().lexem.length() == 1);
                QChar last = symbol().lexem.at(0);

                if (ch.unicode() > last.unicode())
                    qSwap(ch, last);

                for (ushort i = ch.unicode(); i <= last.unicode(); ++i) {
                    if (caseSensitivity == Qt::CaseInsensitive) {
                        set.insert(QChar(i).toLower().unicode());
                    } else {
                        set.insert(i);
                    }
                }

                rangeFound = true;
            } else {
                prev();
            }
        }

        if (!rangeFound) {
            if (caseSensitivity == Qt::CaseInsensitive) {
                set.insert(ch.toLower().unicode());
            } else {
                set.insert(ch.unicode());
            }
        }
    } while (test(TOK_STRING));

    if (negate) {
        QSet<InputType> negatedSet = maxInputSet;
        negatedSet.subtract(set);
        set = negatedSet;
    }

    return NFA::createSetNFA(set);
}
Beispiel #7
0
NFA RE2NFA::parseSet2()
{
    QSet<InputType> set;
    bool negate = false;

    QString str = symbol().lexem;
    // strip off brackets
    str.chop(1);
    str.remove(0, 1);

    int i = 0;
    while (i < str.length()) {
        // ###
        QChar ch = str.at(i++);
        if (set.isEmpty() && ch == QLatin1Char('^')) {
            negate = true;
            continue;
        }

        // look ahead for ranges like a-z
        bool rangeFound = false;
        if (i < str.length() - 1 && str.at(i) == QLatin1Char('-')) {
            ++i;
            QChar last = str.at(i++);

            if (ch.unicode() > last.unicode())
                qSwap(ch, last);

            for (ushort i = ch.unicode(); i <= last.unicode(); ++i) {
                if (caseSensitivity == Qt::CaseInsensitive) {
                    set.insert(QChar(i).toLower().unicode());
                } else {
                    set.insert(i);
                }
            }

            rangeFound = true;
        }

        if (!rangeFound) {
            if (caseSensitivity == Qt::CaseInsensitive) {
                set.insert(ch.toLower().unicode());
            } else {
                set.insert(ch.unicode());
            }
        }
    }

    if (negate) {
        QSet<InputType> negatedSet = maxInputSet;
        negatedSet.subtract(set);
        set = negatedSet;
    }

    return NFA::createSetNFA(set);
}
EditSolutionDialog::EditSolutionDialog(const QModelIndex &solution, const QString &out,
                                                            const QString &err, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::EditSolutionDialog),
    mRow(solution.row()),
    mModel(const_cast<QAbstractItemModel *>(solution.model()))
{
    ui->setupUi(this);
    QDesktopWidget *dw = QApplication::desktop();
    QSettings s("winewizard", "settings");
    s.beginGroup("EditSolutionDialog");
    resize(s.value("Size", QSize(dw->width() * 0.7, dw->height() * 0.6)).toSize());
    ui->vSplitter->restoreState(s.value("VSplitter").toByteArray());
    ui->hSplitter->restoreState(s.value("HSplitter").toByteArray());
    s.endGroup();
    setWindowTitle(solution.sibling(mRow, 1).data().toString());
    int bw = solution.data(SolutionModel::BWRole).toInt();
    int aw = solution.data(SolutionModel::AWRole).toInt();
    ui->lockBtn->setChecked(aw == bw);
    SolutionModel::PackageList wines = solution.data(SolutionModel::WinesRole).value<SolutionModel::PackageList>();
    SolutionModel::PackageList packages = solution.data(SolutionModel::PackagesRole).value<SolutionModel::PackageList>();
    mWineModel = new PackageModel(wines.keys(), wines, this);
    setWine(ui->bw, wines.value(bw).name);
    setWine(ui->aw, wines.value(aw).name);
    SolutionModel::IntList bp = solution.data(SolutionModel::BPRole).value<SolutionModel::IntList>();
    SolutionModel::IntList ap = solution.data(SolutionModel::APRole).value<SolutionModel::IntList>();
    QSet<int> all = QSet<int>::fromList(packages.keys());
    all.subtract(QSet<int>::fromList(bp));
    all.subtract(QSet<int>::fromList(ap));
    ui->bp->setModel(new PackageModel(bp, packages, this));
    ui->ap->setModel(new PackageModel(ap, packages, this));
    PackageModel *pm = new PackageModel(all.toList(), packages, this);
    QSortFilterProxyModel *psm = new PackageSortModel(pm, this);
    connect(ui->search, &QLineEdit::textChanged, psm, &QSortFilterProxyModel::setFilterFixedString);
    ui->all->setModel(psm);
    SolutionModel::CategoryList c = solution.data(SolutionModel::CatRole).value<SolutionModel::CategoryList>();
    ui->categories->setModel(new CategoryModel(c, this));
    ui->output->setPlainText(out);
    ui->errors->setPlainText(err);
    SolutionModel::ErrorList errors = solution.data(SolutionModel::ErrorsRole).value<SolutionModel::ErrorList>();
    for (const QString &e : errors.keys())
    {
        if (err.contains(e))
        {
            QString package = packages.value(errors.value(e)).name;
            ui->advices->appendPlainText(tr("You can try to install \"%1\".").arg(package));
        }
    }
}
void ControlleurJDR::modification (bool fini, Qt::CheckState achat, QSet<Supplement> supplement)
{
    JeuxDeRole* athena = dynamic_cast<JeuxDeRole*>(courant ());

    athena->setFini (fini);
    athena->setAchat (achat);
    QSet<Supplement> hera;
    QSet<Supplement> artemis = athena->supplement ();
    foreach(Supplement zeus, artemis)
    {
        if(!supplement.contains (zeus))
        {
            hera<<zeus;
        }
    }

    artemis.subtract (hera);
    artemis += supplement;
}
Beispiel #10
0
void Search::slotResultsAvailable(const QSet<qint64> &results)
{
    QSet<qint64> newResults = results;
    newResults.subtract(mAllResults);
    mAllResults.unite(newResults);

    if (newResults.isEmpty()) {
        return;
    }

    ImapSet imapSet;
    imapSet.add(newResults);

    Scope scope;
    scope.setUidSet(imapSet);

    FetchHelper fetchHelper(connection(), scope, mFetchScope);
    fetchHelper.fetchItems();
}
void ImageProcessing::deleteUnusedFiles()
{
	QSettings settings(QSettings::IniFormat, QSettings::UserScope, "Home", "PictureViewer");
	QString path = settings.value("ImagePath1").toString();
	QDir pImagePath(path);;
	QMapIterator<QString, QString> it(m_ImageList);
	QStringList files = pImagePath.entryList(QDir::Files|QDir::NoDotAndDotDot, QDir::Name);

	QSet<QString> fromLocal = QSet<QString>::fromList(files);
	QSet<QString> fromServer = QSet<QString>::fromList(m_delList);

	qWarning() << __FUNCTION__ << ": there are" << files.size() << "local files";
	qWarning() << __FUNCTION__ << ": there are" << m_delList.size() << "files in the delete list";
	fromLocal.subtract(fromServer);
	qWarning() << __FUNCTION__ << ": The list of files to delete has" << fromLocal.size() << "entries";
	QSetIterator<QString> toDel(fromLocal);
	while (toDel.hasNext()) {
		QString file = pImagePath.absolutePath() + "/" + toDel.next();
		qWarning() << __FUNCTION__ << ": Deleting" << file;
		QFile f(file);
		f.remove();
	}
}
Beispiel #12
0
void QGoogleCalendarContext::setVisibleSources(const QSet<QPimSource> &set)
{
    syncAccountList();
    QMapIterator<QString, Account> it(mAccounts);
    QSet<int> show;
    QSet<int> hide;
    while(it.hasNext()) {
        it.next();
        QPimSource s;
        s.context = id();
        s.identity = it.key();
        int context = QPimSqlIO::sourceContext(s);
        if (set.contains(s)) {
            show.insert(context);
        } else {
            hide.insert(context);
        }
    }

    QSet<int> filter = mAccess->contextFilter();
    filter.unite(hide);
    filter.subtract(show);
    mAccess->setContextFilter(filter);
}
bool AndroidSettingsWidget::checkNDK(const Utils::FileName &location)
{
    if (location.isEmpty()) {
        m_ui->ndkWarningIconLabel->setVisible(false);
        m_ui->toolchainFoundLabel->setVisible(false);
        m_ui->kitWarningIconLabel->setVisible(false);
        m_ui->kitWarningLabel->setVisible(false);
        return false;
    }
    Utils::FileName platformPath = location;
    Utils::FileName toolChainPath = location;
    Utils::FileName sourcesPath = location;
    if (!platformPath.appendPath(QLatin1String("platforms")).toFileInfo().exists()
            || !toolChainPath.appendPath(QLatin1String("toolchains")).toFileInfo().exists()
            || !sourcesPath.appendPath(QLatin1String("sources/cxx-stl")).toFileInfo().exists()) {
        m_ui->toolchainFoundLabel->setText(tr("\"%1\" does not seem to be an Android NDK top folder.").arg(location.toUserOutput()));
        m_ui->toolchainFoundLabel->setVisible(true);
        m_ui->ndkWarningIconLabel->setVisible(true);
        return false;
    }

    // Check how many toolchains we could add...
    QList<AndroidToolChainFactory::AndroidToolChainInformation> compilerPaths = AndroidToolChainFactory::toolchainPathsForNdk(location);
    if (compilerPaths.isEmpty()) {
        m_ui->ndkWarningIconLabel->setVisible(false);
        m_ui->toolchainFoundLabel->setVisible(false);
    } else {
        m_ui->ndkWarningIconLabel->setVisible(false);
        m_ui->toolchainFoundLabel->setText(tr("Found %n toolchains for this NDK.", 0, compilerPaths.count()));
        m_ui->toolchainFoundLabel->setVisible(true);
    }

    // See if we have qt versions for those toolchains
    QSet<ProjectExplorer::Abi::Architecture> toolchainsForArch;
    foreach (const AndroidToolChainFactory::AndroidToolChainInformation &ati, compilerPaths)
        toolchainsForArch.insert(ati.architecture);

    QSet<ProjectExplorer::Abi::Architecture> qtVersionsForArch;
    foreach (QtSupport::BaseQtVersion *qtVersion, QtSupport::QtVersionManager::versions()) {
        if (qtVersion->type() != QLatin1String(Constants::ANDROIDQT) || qtVersion->qtAbis().isEmpty())
            continue;
        qtVersionsForArch.insert(qtVersion->qtAbis().first().architecture());
    }

    QSet<ProjectExplorer::Abi::Architecture> missingQtArchs = toolchainsForArch.subtract(qtVersionsForArch);
    if (missingQtArchs.isEmpty()) {
        m_ui->kitWarningIconLabel->setVisible(false);
        m_ui->kitWarningLabel->setVisible(false);
    } else {
        m_ui->kitWarningIconLabel->setVisible(true);
        m_ui->kitWarningLabel->setVisible(true);
        if (missingQtArchs.count() == 1) {
            m_ui->kitWarningLabel->setText(tr("Qt version for architecture %1 is missing.\n To add the Qt version, select Options > Build & Run > Qt Versions.")
                                           .arg(ProjectExplorer::Abi::toString((*missingQtArchs.constBegin()))));
        } else {
            QStringList missingArchs;
            foreach (ProjectExplorer::Abi::Architecture arch, missingQtArchs)
                missingArchs.append(ProjectExplorer::Abi::toString(arch));
            m_ui->kitWarningLabel->setText(tr("Qt versions for architectures %1 are missing.\n To add the Qt versions, select Options > Build & Run > Qt Versions.")
                                           .arg(missingArchs.join(QLatin1String(", "))));
        }
    }

    m_androidConfig.ndkLocation = location;
    return true;

}
/**
* Populates the items (log values) into their table.
*
* @param fittedWsList :: a workspace list containing ONLY the workspaces that have parameter
*                   tables associated with it.
*/
void MuonAnalysisResultTableTab::populateLogsAndValues(const QStringList& fittedWsList)
{
  // A set of all the logs we've met in the workspaces
  QSet<QString> allLogs;

  for (int i=0; i<fittedWsList.size(); i++)
  { 
    QMap<QString, QVariant> wsLogValues;

    // Get log information
    auto ws = retrieveWSChecked<ExperimentInfo>(fittedWsList[i].toStdString() + WORKSPACE_POSTFIX);

    Mantid::Kernel::DateAndTime start = ws->run().startTime();
    Mantid::Kernel::DateAndTime end = ws->run().endTime();

    const std::vector<Property*> & logData = ws->run().getLogData();
    std::vector<Property*>::const_iterator pEnd = logData.end();

    for( std::vector<Property*>::const_iterator pItr = logData.begin(); pItr != pEnd; ++pItr )
    {  
      // Check if is a timeseries log
      if( TimeSeriesProperty<double> *tspd = dynamic_cast<TimeSeriesProperty<double>*>(*pItr) )
      {
        QString logFile(QFileInfo((**pItr).name().c_str()).fileName());

        double value(0.0);
        int count(0);

        Mantid::Kernel::DateAndTime logTime;

        //iterate through all logs entries of a specific log
        for (int k(0); k<tspd->size(); k++)
        {
          // Get the log time for the specific entry
          logTime = tspd->nthTime(k);

          // If the entry was made during the run times
          if ((logTime >= start) && (logTime <= end))
          {
            // add it to a total and increment the count (will be used to make average entry value during a run)
            value += tspd->nthValue(k);
            count++;
          }
        }

        if ( count != 0 )
        {
          //Find average
          wsLogValues[logFile] = value / count;
        }
      }
      else // Should be a non-timeseries one
      {
        QString logName = QString::fromStdString( (**pItr).name() );

        // Check if we should display it
        if ( NON_TIMESERIES_LOGS.contains(logName) )
        {
          QVariant value;

          if ( auto stringProp = dynamic_cast<PropertyWithValue<std::string>*>(*pItr) )
          {
            value = QString::fromStdString( (*stringProp)() );
          }
          else if ( auto doubleProp = dynamic_cast<PropertyWithValue<double>*>(*pItr) )
          {
            value = (*doubleProp)();
          }
          else
          {
            throw std::runtime_error("Unsupported non-timeseries log type");
          }

          wsLogValues[logName] = value;
        }
      }
    }

    // Append log names found in the workspace to the list of all known log names
    allLogs += wsLogValues.keys().toSet();

    // Add all data collected from one workspace to another map. Will be used when creating table.
    m_logValues[fittedWsList[i]] = wsLogValues;

  } // End loop over all workspace's log information and param information

  // Remove the logs that don't appear in all workspaces
  QSet<QString> toRemove;
  for ( auto logIt = allLogs.constBegin(); logIt != allLogs.constEnd(); ++logIt )
  {
    for ( auto wsIt = m_logValues.constBegin(); wsIt != m_logValues.constEnd(); ++wsIt )
    { 
      auto wsLogValues = wsIt.value();
      if ( ! wsLogValues.contains(*logIt) )
      {      
        toRemove.insert(*logIt);
        break;
      }
    }      
  }

  allLogs = allLogs.subtract(toRemove);

  // Sort logs
  QList<QString> allLogsSorted(allLogs.toList());
  qSort(allLogsSorted.begin(), allLogsSorted.end(), MuonAnalysisResultTableTab::logNameLessThan);
  
  // Add number of rows to the table based on number of logs to display.
  m_uiForm.valueTable->setRowCount(allLogsSorted.size());

  // Populate table with all log values available without repeating any.
  for ( auto it = allLogsSorted.constBegin(); it != allLogsSorted.constEnd(); ++it )
  {
    int row = static_cast<int>( std::distance(allLogsSorted.constBegin(), it) );
    m_uiForm.valueTable->setItem(row, 0, new QTableWidgetItem(*it));
  }

  // Save the number of logs displayed
  // XXX: this is redundant, as number of logs == number of rows
  m_numLogsdisplayed = m_uiForm.valueTable->rowCount();

  // Add check boxes for the include column on log table, and make text uneditable.
  for (int i = 0; i < m_uiForm.valueTable->rowCount(); i++)
  {
    m_uiForm.valueTable->setCellWidget(i,1, new QCheckBox);
    
    if( auto textItem = m_uiForm.valueTable->item(i, 0) )
    {
      textItem->setFlags(textItem->flags() & (~Qt::ItemIsEditable));
    }
  }
}
void FillIn::updateMetrics()
{
    QSharedPointer<Food> selectedFood = getSelectedFood();

    if (!selectedFood) {

        ui.btnFillIn->setEnabled(false);
        ui.txtAmount->setText("");
        ui.txtAverageError->setText("");
        ui.txtLargestError->setText("");
        ui.txtLargestErrorField->setText("");
        ui.txtLargestErrorSelectedVal->setText("");
        ui.txtLargestErrorYourVal->setText("");
        ui.txtNumFields->setText("");
        ui.txtStdDev->setText("");

        fillinNutrients.clear();

    } else {

        ui.btnFillIn->setEnabled(true);

        // TODO: Break this up into multiple methods

        // Step 1. Compute the amount of the selected food needed to give the same
        // number of calories as the original food

        QSharedPointer<const Nutrient> calories = Nutrient::getNutrientByName(Nutrient::CALORIES_NAME);

        FoodAmount selectedBaseAmount = selectedFood->getBaseAmount();

        double caloriesInOriginal = originalNutrients[calories->getId()].getAmount();
        double caloriesInSelectedBaseAmount =
            selectedBaseAmount.getScaledNutrients()[calories->getId()].getAmount();

        qDebug() << "Calories in original: " << caloriesInOriginal;
        qDebug() << "Calories in selected base amount: " << selectedBaseAmount.getScaledNutrients()[calories->getId()].getAmount();

        FoodAmount selectedAmount =
            selectedBaseAmount * (caloriesInOriginal / caloriesInSelectedBaseAmount);

        ui.txtAmount->setText(QString::number(selectedAmount.getAmount(), 'f', 2) + " " +
                              selectedAmount.getUnit()->getAbbreviation());


        // Step 2. Determine which nutrients are in common, and which can be filled in

        QMap<QString, NutrientAmount> selectedNutrients = selectedAmount.getScaledNutrients();

        QSet<QString> originalNutrientIds = originalNutrients.keys().toSet();
        QSet<QString> selectedNutrientIds = selectedNutrients.keys().toSet();

        QSet<QString> commonNutrientIds = originalNutrientIds;
        commonNutrientIds.intersect(selectedNutrientIds);

        QSet<QString> fillinNutrientIds = selectedNutrientIds;
        fillinNutrientIds.subtract(originalNutrientIds);

        qDebug() << "Original nutrients: " << originalNutrientIds.size();
        qDebug() << "Selected nutrients: " << selectedNutrientIds.size();
        qDebug() << "Common nutrients: " << commonNutrientIds.size();
        qDebug() << "Fill-in nutrients: " << fillinNutrientIds.size();

        ui.txtNumFields->setText(QString::number(fillinNutrientIds.size()));

        // Step 3. Compute the percent error for each common nutrient, and compute
        // the average, also making note of the largest.

        QMap<QString, double> pctError;
        double sumOfErrors = 0;

        QString largestErrorId;
        double largestError = 0;

        for (QSet<QString>::const_iterator i = commonNutrientIds.begin(); i != commonNutrientIds.end(); ++i) {
            double originalValue = originalNutrients[*i].getAmount();

            if (originalValue > 0) {

                double selectedValue = selectedNutrients[*i].getAmount();
                double error = std::fabs(originalValue - selectedValue) / originalValue;
                pctError[*i] = error;
                sumOfErrors += error;

                if (error > largestError) {
                    largestErrorId = *i;
                    largestError = error;
                }

                qDebug() << "Error for common nutrient " << *i << " ("
                         << originalNutrients[*i].getNutrient()->getName() << ") is "
                         << error;
            }
        }

        double avgError = sumOfErrors / pctError.size();

        ui.txtAverageError->setText(QString::number(avgError * 100, 'f', 2) + " %");

        ui.txtLargestError->setText(QString::number(largestError * 100, 'f', 2) + " %");
        ui.txtLargestErrorField->setText(originalNutrients[largestErrorId].getNutrient()->getName());

        ui.txtLargestErrorYourVal->setText
        (QString::number(originalNutrients[largestErrorId].getAmount(), 'f', 2) + " " +
         originalNutrients[largestErrorId].getUnit()->getAbbreviation());

        ui.txtLargestErrorSelectedVal->setText
        (QString::number(selectedNutrients[largestErrorId].getAmount(), 'f', 2) + " " +
         selectedNutrients[largestErrorId].getUnit()->getAbbreviation());


        // Step 4. Compute the standard deviation of the error percentages

        double sumOfDistancesSquared = 0;

        for (QMap<QString, double>::const_iterator i = pctError.begin(); i != pctError.end(); ++i) {
            double distance = i.value() - avgError;
            sumOfDistancesSquared += (distance * distance);
        }

        double stdDev = std::sqrt(sumOfDistancesSquared / pctError.size());

        ui.txtStdDev->setText(QString::number(stdDev, 'f', 2));

        // Step 5. Save a copy of all of the fill-in nutrient amounts

        fillinNutrients.clear();
        for (QSet<QString>::const_iterator i = fillinNutrientIds.begin(); i != fillinNutrientIds.end(); ++i) {
            fillinNutrients[*i] = selectedNutrients[*i];
        }
    }
}
Beispiel #16
0
void GenericProjectNode::refresh(QSet<QString> oldFileList)
{
    if (oldFileList.isEmpty()) {
        // Only do this once
        FileNode *projectFilesNode = new FileNode(m_project->filesFileName(),
                                                  ProjectFileType,
                                                  /* generated = */ false);

        FileNode *projectIncludesNode = new FileNode(m_project->includesFileName(),
                                                     ProjectFileType,
                                                     /* generated = */ false);

        FileNode *projectConfigNode = new FileNode(m_project->configFileName(),
                                                   ProjectFileType,
                                                   /* generated = */ false);

        addFileNodes(QList<FileNode *>()
                     << projectFilesNode
                     << projectIncludesNode
                     << projectConfigNode,
                     this);
    }

    // Do those separately
    oldFileList.remove(m_project->filesFileName());
    oldFileList.remove(m_project->includesFileName());
    oldFileList.remove(m_project->configFileName());

    QSet<QString> newFileList = m_project->files().toSet();
    newFileList.remove(m_project->filesFileName());
    newFileList.remove(m_project->includesFileName());
    newFileList.remove(m_project->configFileName());

    QSet<QString> removed = oldFileList;
    removed.subtract(newFileList);
    QSet<QString> added = newFileList;
    added.subtract(oldFileList);

    QString baseDir = QFileInfo(path()).absolutePath();
    QHash<QString, QStringList> filesInPaths = sortFilesIntoPaths(baseDir, added);
    foreach (const QString &filePath, filesInPaths.keys()) {
        QStringList components = filePath.split(QLatin1Char('/'));
        FolderNode *folder = findFolderByName(components, components.size());
        if (!folder)
            folder = createFolderByName(components, components.size());

        QList<FileNode *> fileNodes;
        foreach (const QString &file, filesInPaths.value(filePath)) {
            FileType fileType = SourceType; // ### FIXME
            FileNode *fileNode = new FileNode(file, fileType, /*generated = */ false);
            fileNodes.append(fileNode);
        }

        addFileNodes(fileNodes, folder);
    }

    filesInPaths = sortFilesIntoPaths(baseDir, removed);
    foreach (const QString &filePath, filesInPaths.keys()) {
        QStringList components = filePath.split(QLatin1Char('/'));
        FolderNode *folder = findFolderByName(components, components.size());

        QList<FileNode *> fileNodes;
        foreach (const QString &file, filesInPaths.value(filePath)) {
            foreach (FileNode *fn, folder->fileNodes())
                if (fn->path() == file)
                    fileNodes.append(fn);
        }

        removeFileNodes(fileNodes, folder);
    }

    foreach (FolderNode *fn, subFolderNodes())
        removeEmptySubFolders(this, fn);

}