ParameterizedCommand::ParameterizedCommand(const SmartPointer<Command>& command,
                                           const QList<Parameterization>& params)
  : command(command), hashCode(HASH_CODE_NOT_COMPUTED)
{
  if (!command)
  {
    throw Poco::NullPointerException(
        "A parameterized command cannot have a null command");
  }

  QList<IParameter::Pointer> parameters;
  try
  {
    parameters = command->GetParameters();
  } catch (const NotDefinedException* /*e*/)
  {
    // This should not happen.
  }
  if (!params.empty() && !parameters.empty())
  {
    for (int j = 0; j < parameters.size(); j++)
    {
      for (int i = 0; i < params.size(); i++)
      {
        if (parameters[j] == params[i].GetParameter())
        {
          this->parameterizations.push_back(params[i]);
        }
      }
    }
  }
}
Example #2
0
    void pushMatrixData(QString matrixName)
    {
        QString fileName = "/home/maltanar/spm-data/graph/" + matrixName;

        // TODO load matrix once & reuse for multiple SpMV iterations
        CSCGraph matrix(fileName);


        cout << "Loaded matrix " << matrixName.toStdString() << endl;
        cout << "Vertex count = " << matrix.rowCount() << endl;
        cout << "Edge count = " << matrix.nzCount() << endl;
        cout << "Input vector pointer = " << inpVecPtr << endl;
        cout << "Result vector pointer = " << resVecPtr << endl;

        sc_assert(io_state == 0);   // make sure we are in idle

        io_colCount = matrix.colCount();
        io_memDump = false;
        io_memFill = false;
        io_start = true;
        wait(2);
        io_start = false;

        sc_assert(io_state == 4); // should be in sReadColLen

        QList<CSCPtr> colLenData = matrix.getColLengths();
        QList<CSCPtr> rowIndData = matrix.getRowIndices();

        while (!colLenData.empty() || !rowIndData.empty())
        {
            if(!colLenData.empty())
            {
                unsigned int len = colLenData.takeFirst();
                // cout << "collen: " << len << endl;
                colLen.write(len);
            }
            if(!rowIndData.empty())
            {

                unsigned int y = rowIndData.takeFirst();
                //cout << "yind: " << y << endl;
                rowInd.write(y);
            }
        }

        cout << "Finished pushing matrix data, waiting for idle @" << NOW << endl;

        // wait until we go back to idle
        while(io_state != 0)
            wait(1);

        cout << "Column length transfers = " << colLenAdp.getTransferCount() << endl;
        cout << "Row index transfers = " << rowIndAdp.getTransferCount() << endl;
    }
Example #3
0
void
MainWindow::removeModuleMenuItem(QAction* action)
{
  QList<QAction*> actionList = moduleMenu->actions();
  if (!actionList.empty())
    moduleMenu->removeAction(action);
}
Example #4
0
void S60DeployConfigurationWidget::updateSerialDevices()
{
    m_serialPortsCombo->clear();
    const QString previouPortName = m_deployConfiguration->serialPortName();
    const QList<SymbianUtils::SymbianDevice> devices = SymbianUtils::SymbianDeviceManager::instance()->devices();
    int newIndex = -1;
    for (int i = 0; i < devices.size(); ++i) {
        const SymbianUtils::SymbianDevice &device = devices.at(i);
        m_serialPortsCombo->addItem(device.friendlyName(), qVariantFromValue(device));
        if (device.portName() == previouPortName)
            newIndex = i;
    }

    if(m_deployConfiguration->communicationChannel()
            == S60DeployConfiguration::CommunicationCodaTcpConnection) {
        m_deviceInfoButton->setEnabled(true);
        return;
    }

    clearDeviceInfo();
    // Set new index: prefer to keep old or set to 0, if available.
    if (newIndex == -1 && !devices.empty())
        newIndex = 0;
    m_serialPortsCombo->setCurrentIndex(newIndex);
    if (newIndex == -1) {
        m_deviceInfoButton->setEnabled(false);
        m_deployConfiguration->setSerialPortName(QString());
    } else {
        m_deviceInfoButton->setEnabled(true);
        const QString newPortName = device(newIndex).portName();
        m_deployConfiguration->setSerialPortName(newPortName);
    }
}
void NebulaMgr::drawPointer(const StelCore* core, StelPainter& sPainter)
{
	const StelProjectorP prj = core->getProjection(StelCore::FrameJ2000);

	const QList<StelObjectP> newSelected = GETSTELMODULE(StelObjectMgr)->getSelectedObject("Nebula");
	if (!newSelected.empty())
	{
		const StelObjectP obj = newSelected[0];
		Vec3d pos=obj->getJ2000EquatorialPos(core);

		// Compute 2D pos and return if outside screen
		if (!prj->projectInPlace(pos)) return;		
		if (StelApp::getInstance().getVisionModeNight())
			sPainter.setColor(0.8f,0.0f,0.0f);
		else
			sPainter.setColor(0.4f,0.5f,0.8f);

		texPointer->bind();

		sPainter.enableTexture2d(true);
		glEnable(GL_BLEND);
		glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Normal transparency mode

		// Size on screen
		float size = obj->getAngularSize(core)*M_PI/180.*prj->getPixelPerRadAtCenter();

		size+=20.f + 10.f*std::sin(2.f * StelApp::getInstance().getTotalRunTime());
		sPainter.drawSprite2dMode(pos[0]-size/2, pos[1]-size/2, 10, 90);
		sPainter.drawSprite2dMode(pos[0]-size/2, pos[1]+size/2, 10, 0);
		sPainter.drawSprite2dMode(pos[0]+size/2, pos[1]+size/2, 10, -90);
		sPainter.drawSprite2dMode(pos[0]+size/2, pos[1]-size/2, 10, -180);
	}
}
void GitoriousRepositoryWizardPage::initializePage()
{
    // Populate the model
    ui->repositoryTreeView->selectionModel()->clearSelection();
    if (const int oldRowCount = m_model->rowCount())
        m_model->removeRows(0, oldRowCount);
    ui->filterLineEdit->clear();
    // fill model
    const QSharedPointer<GitoriousProject> proj = m_projectPage->project();
    setSubTitle(tr("Choose a repository of the project '%1'.").arg(proj->name));
    // Create a hierarchical list by repository type, sort by type
    QList<GitoriousRepository> repositories = proj->repositories;
    QStandardItem *firstEntry = 0;
    if (!repositories.empty()) {
        int lastRepoType = -1;
        QStandardItem *header = 0;
        qStableSort(repositories.begin(), repositories.end(), gitRepoLessThanByType);
        const QString types[GitoriousRepository::PersonalRepository + 1] =
            { tr("Mainline Repositories"), tr("Clones"), tr("Baseline Repositories"), tr("Shared Project Repositories"), tr("Personal Repositories") };
        foreach(const GitoriousRepository &r, repositories) {
            // New Header?
            if (r.type != lastRepoType || !header) {
                lastRepoType = r.type;
                const QList<QStandardItem *> headerRow = headerEntry(types[r.type]);
                m_model->appendRow(headerRow);
                header = headerRow.front();
            }
            // Repository row
            const QList<QStandardItem *> row = repositoryEntry(r);
            header->appendRow(row);
            if (!firstEntry)
                firstEntry = row.front();
        }
    }
Example #7
0
void TablePile::timerEvent(QTimerEvent *)
{    
    QList<CardItem *> oldCards;
    _m_mutex_pileCards.lock();
    m_currentTime++;
    foreach (CardItem* toRemove, m_visibleCards)
    {
        if (m_currentTime - toRemove->m_uiHelper.tablePileClearTimeStamp
            > S_CLEARANCE_DELAY_BUCKETS)
        {
            oldCards.append(toRemove);
            m_visibleCards.removeOne(toRemove);
        }
        else if (m_currentTime > toRemove->m_uiHelper.tablePileClearTimeStamp)
            toRemove->setEnabled(false); // @todo: this is a dirty trick. Use another property in the future
    }
    
    if (oldCards.empty()) {
        _m_mutex_pileCards.unlock();
        return;
    }

    _fadeOutCardsLocked(oldCards);
    _m_mutex_pileCards.unlock();
    
    adjustCards();
}
Example #8
0
void PropertiesEditorDialog::valueChanged(QtProperty *property, const QVariant &value)
{
    if (!m_property_to_id.contains(property))
    {
        return;
    }

    if (!m_canvas)
    {
        return;
    }
    QList<QGraphicsSvgItem *> list = m_canvas->selectedGeneralItems();

    m_canvas->beginUndoMacro(tr("Change Property"));
    if (list.empty())
    {
        // Set the property directly on the canvas:
        m_canvas->setProperty(m_property_to_id[property].toLatin1().constData(), value);
    }
    else
    {
        // Otherwise, set it on the first item in the selection:
        QGraphicsSvgItem *item = list.front();
        item->setProperty(m_property_to_id[property].toLatin1().constData(), value);
    }
}
/**
 * Find a relevant jump point for this type of media.
 *
 * If there's more than one we should show a popup
 * to allow the user to select which one to use,
 * but for now, we're going to just use the first one.
 */
void MediaMonitor::JumpToMediaHandler(MythMediaDevice* pMedia)
{
    QList<MHData>                    handlers;
    QMap<QString, MHData>::Iterator  itr = m_handlerMap.begin();

    while (itr != m_handlerMap.end())
    {
        if (((*itr).MythMediaType & (int)pMedia->getMediaType()))
        {
            LOG(VB_GENERAL, LOG_NOTICE,
                QString("Found a handler for %1 - '%2'")
                .arg(pMedia->MediaTypeString()) .arg(itr.key())); 
            handlers.append(*itr);
        }
        itr++;
    }

    if (handlers.empty())
    {
        LOG(VB_MEDIA, LOG_INFO, "No media handler found for event type");
        return;
    }


    // TODO - Generate a dialog, add buttons for each description,
    // if user didn't cancel, selected = handlers.at(choice);
    int selected = 0;

    handlers.at(selected).callback(pMedia);
}
Example #10
0
void AlbumManager::addClicked()
      {
      QStringList files = mscore->getOpenScoreNames(
         tr("MuseScore Files") + " (*.mscz *.mscx);;", tr("Load Score")
         );
      QList<MasterScore*> scores;
      for (const QString& fn : files) {
            MasterScore* score = mscore->readScore(fn);
            Movements* m = score->movements();
            for (MasterScore* ms : *m) {
                  scores.push_back(ms);
                  ms->setMovements(0);
                  }
            delete m;
            }
      if (scores.empty())
            return;
      MasterScore* topScore = album->front();
      scoreList->blockSignals(true);
      for (MasterScore* score : scores) {
            topScore->addMovement(score);
            QString name = getScoreTitle(score);
            QListWidgetItem* li = new QListWidgetItem(name, scoreList);
            li->setFlags(Qt::ItemFlags(Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsEnabled));
            }
      scoreList->blockSignals(false);
      topScore->setLayoutAll();
      topScore->update();
      }
void Supernovae::drawPointer(StelCore* core, StelRenderer* renderer, StelProjectorP projector)
{
    const QList<StelObjectP> newSelected = GETSTELMODULE(StelObjectMgr)->getSelectedObject("Supernova");
    if (!newSelected.empty())
    {
        const StelObjectP obj = newSelected[0];
        Vec3d pos=obj->getJ2000EquatorialPos(core);

        Vec3d screenpos;
        // Compute 2D pos and return if outside screen
        if (!projector->project(pos, screenpos))
        {
            return;
        }

        const Vec3f& c(obj->getInfoColor());
        renderer->setGlobalColor(c[0],c[1],c[2]);
        if(NULL == texPointer)
        {
            texPointer = renderer->createTexture("textures/pointeur2.png");
        }
        texPointer->bind();
        renderer->setBlendMode(BlendMode_Alpha);
        renderer->drawTexturedRect(screenpos[0] - 13.0f, screenpos[1] - 13.0f, 26.0f, 26.0f,
                                   StelApp::getInstance().getTotalRunTime() * 40.0f);
    }
}
void CoveredRegionsLabel::sl_updateContent() {
    QString text = "<style>a:link { color: " + L10N::linkColorLabelStr() + " }</style>";
    text += prefix;

    QList<CoveredRegion> coveredRegions = browser->getCoveredRegions();
    if(!browser->areCoveredRegionsReady()) {
        text += tr("Computing coverage...");
    } else if(!coveredRegions.empty()) {
        QString coveredRegionsText = "<style>td { padding-right: 8px;}</style>";
        coveredRegionsText += "<table cellspacing='2'>";
        /*
        * |   | Region | Coverage |
        * | 1 | [x,y]  | z        |
        */
        coveredRegionsText += tr("<tr><th/><th align='left'><div style='margin-right: 5px;'>Position</div></th><th align = 'center'>Coverage</th></tr>");
        for(int i = 0; i < coveredRegions.size(); ++i) {
            const CoveredRegion & cr = coveredRegions.at(i);
            QString crRegion = FormatUtils::splitThousands(cr.region.center());
            QString crCoverage = FormatUtils::splitThousands(cr.coverage);
            coveredRegionsText += "<tr>";
            coveredRegionsText += QString("<td align='right'>%1&nbsp;&nbsp;</td>").arg(i+1);
            coveredRegionsText += QString("<td><a href=\"%1\">%2</a></td>").arg(i).arg(crRegion);
            coveredRegionsText += tr("<td align=\"center\">%4</td>").arg(crCoverage);
            coveredRegionsText += "</tr>";
        }
        coveredRegionsText += "</table>";
        text += coveredRegionsText;
    }

    text += postfix;

    setText(text);
}
Example #13
0
void ControlDock_MapTab::selected_map_changed()
{
	if (!updating_ui_)
	{
		MapHandlerGen* old = selected_map_;

		if (old)
		{
			disconnect(old, SIGNAL(attribute_added(cgogn::Orbit, const QString&)), this, SLOT(selected_map_attribute_added(cgogn::Orbit, const QString&)));
			disconnect(old, SIGNAL(attribute_removed(cgogn::Orbit, const QString&)), this, SLOT(selected_map_attribute_removed(cgogn::Orbit, const QString&)));
			disconnect(old, SIGNAL(vbo_added(cgogn::rendering::VBO*)), this, SLOT(selected_map_vbo_added(cgogn::rendering::VBO*)));
			disconnect(old, SIGNAL(vbo_removed(cgogn::rendering::VBO*)), this, SLOT(selected_map_vbo_removed(cgogn::rendering::VBO*)));
			disconnect(old, SIGNAL(bb_vertex_attribute_changed(const QString&)), this, SLOT(selected_map_bb_vertex_attribute_changed(const QString&)));
			disconnect(old, SIGNAL(connectivity_changed()), this, SLOT(selected_map_connectivity_changed()));
			disconnect(old, SIGNAL(cells_set_added(CellType, const QString&)), this, SLOT(selected_map_cells_set_added(CellType, const QString&)));
			disconnect(old, SIGNAL(cells_set_removed(CellType, const QString&)), this, SLOT(selected_map_cells_set_removed(CellType, const QString&)));
		}

		QList<QListWidgetItem*> items = list_maps->selectedItems();
		if (!items.empty())
		{
			QString selected_map_name = items[0]->text();
			selected_map_ = schnapps_->get_map(selected_map_name);

			connect(selected_map_, SIGNAL(attribute_added(cgogn::Orbit, const QString&)), this, SLOT(selected_map_attribute_added(cgogn::Orbit, const QString&)));
			connect(selected_map_, SIGNAL(attribute_removed(cgogn::Orbit, const QString&)), this, SLOT(selected_map_attribute_removed(cgogn::Orbit, const QString&)));
			connect(selected_map_, SIGNAL(vbo_added(cgogn::rendering::VBO*)), this, SLOT(selected_map_vbo_added(cgogn::rendering::VBO*)));
			connect(selected_map_, SIGNAL(vbo_removed(cgogn::rendering::VBO*)), this, SLOT(selected_map_vbo_removed(cgogn::rendering::VBO*)));
			connect(selected_map_, SIGNAL(bb_vertex_attribute_changed(const QString&)), this, SLOT(selected_map_bb_vertex_attribute_changed(const QString&)));
			connect(selected_map_, SIGNAL(connectivity_changed()), this, SLOT(selected_map_connectivity_changed()));
			connect(selected_map_, SIGNAL(cells_set_added(CellType, const QString&)), this, SLOT(selected_map_cells_set_added(CellType, const QString&)));
			connect(selected_map_, SIGNAL(cells_set_removed(CellType, const QString&)), this, SLOT(selected_map_cells_set_removed(CellType, const QString&)));
		}
void chanFileSystemDockWidget::createFolder() {

    QList<QTreeWidgetItem*> items = m_fileSystemTree->selectedItems();

    QString folderName;
    QString path;
    QDir dir;

    folderName = QInputDialog::getText(this, "set folder's name", "enter name:");
    path = m_home + QDir::separator() + folderName;

    //修改硬盘中的数据
    if (!dir.mkdir(path)) {
        QMessageBox::warning(this, tr("error"),
                             tr("make directory %1 failed").arg(folderName));
        return;
    }

    QTreeWidgetItem* item = items.empty() ?
                            new QTreeWidgetItem(m_fileSystemTree) :
                            new QTreeWidgetItem(items.front());

    item->setData(0, ITEM_TYPE_KEY, Folder);
    item->setData(0, FOLDER_NAME_KEY,path);
    item->setText(0, folderName);

    item->setIcon(0, QIcon(resourceFileName::pFolder));
}
Example #15
0
void RSSWidget::askNewFolder()
{
    bool ok;
    QString newName = AutoExpandableDialog::getText(
                this, tr("Please choose a folder name"), tr("Folder name:"), QLineEdit::Normal
                , tr("New folder"), &ok);
    if (!ok) return;

    newName = newName.trimmed();
    if (newName.isEmpty()) return;

    // Determine destination folder for new item
    QTreeWidgetItem *destItem = nullptr;
    QList<QTreeWidgetItem *> selectedItems = m_feedListWidget->selectedItems();
    if (!selectedItems.empty()) {
        destItem = selectedItems.first();
        if (!m_feedListWidget->isFolder(destItem))
            destItem = destItem->parent();
    }
    // Consider the case where the user clicked on Unread item
    RSS::Folder *rssDestFolder = ((!destItem || (destItem == m_feedListWidget->stickyUnreadItem()))
                                  ? RSS::Session::instance()->rootFolder()
                                  : qobject_cast<RSS::Folder *>(m_feedListWidget->getRSSItem(destItem)));

    QString error;
    const QString newFolderPath = RSS::Item::joinPath(rssDestFolder->path(), newName);
    if (!RSS::Session::instance()->addFolder(newFolderPath, &error))
        QMessageBox::warning(this, "qBittorrent", error, QMessageBox::Ok);

    // Expand destination folder to display new feed
    if (destItem && (destItem != m_feedListWidget->stickyUnreadItem()))
        destItem->setExpanded(true);
    // As new RSS items are added synchronously, we can do the following here.
    m_feedListWidget->setCurrentItem(m_feedListWidget->mapRSSItem(RSS::Session::instance()->itemByPath(newFolderPath)));
}
void DynamicDirectoryBasedPlaylistCreator::createPlaylistFromBaseDirectory() {
    // Wait 1s to enshure that all other modules are initialized before we fire any events!
    SleeperThread::msleep(1000);

    emit startupPlaylistGenerationStarted();
    initBaseDir();

    if ( _mediaDirectories.count() == 0 ) {
        emit startupPlaylistGenerationFinished();
        return;
    } else {
        QDir directory( _mediaDirectories.at( 0 ) );

        if ( ! directory.exists() ) {
            emit startupPlaylistGenerationFinished();
            return;
        }
    }

    QList<QPair<QUuid, QString>*>* discoverdMedia = readMediaFromMediaLibrary();
    readNewMediaFromFS( discoverdMedia );
    filterVanishedMedia( discoverdMedia );

    while( !discoverdMedia->empty() ) {
        delete discoverdMedia->takeFirst();
    }

    delete discoverdMedia;
    SimpleLogger::instance()->debug( Constants::LOGGER_PLAYLISTCREATOR, QString( "Playlist Creation finished" ) );
    emit startupPlaylistGenerationFinished();
    emit playlistGenerationFinished();
}
Example #17
0
int main(int argc, char **argv)
{
    QCoreApplication app(argc, argv);
    KComponentData data("tutorial5");

    //get a Network Device
    QList<Solid::Device> netlist = Solid::Device::listFromType(Solid::DeviceInterface::NetworkInterface, QString());

    //check to see if no network devices were found
    if(netlist.empty())
    {
        kDebug() << "No network devices found!";
        return 0;
    }

    Solid::Device device = netlist[0];
    Solid::NetworkInterface *netdev = device.as<Solid::NetworkInterface>();
    //keep the program from crashing in the event that there's a bug in solid
    if(!netdev)
    {
        kDebug() << "Device could not be converted.  There is a bug.";
        return 0;
    }

    kDebug() << "The iface of " << device.udi() << " is " << netdev->ifaceName();

    return 0;
}
void OverwriteFilesDialog::renameSelectedFiles()
{	
	QList<QListWidgetItem*> items = m_fileList->selectedItems();
	if ( items.empty() )
	{
		QMessageBox::information(this, tr("No item selected"), tr("You have to select the files to rename first"));
		return;
	}	
	for (int i=0; i<items.count(); ++i)
	{
		CopyJob job = items.at(i)->data(Qt::UserRole).value<CopyJob>();
		bool ok = false;
		QString newFileName = QInputDialog::getText(this, tr("Select new filename"), tr("New name"), QLineEdit::Normal, job.Target.fileName(), &ok);
		if (!ok) return;
		if ( newFileName == job.Target.fileName() || QFile::exists(job.Target.absoluteDir().absoluteFilePath(newFileName)) )
		{
			if (QMessageBox::warning(
				this, 
				tr("Warning"), 
				tr("The file %1 already exists! Do you want to overwrite it?").arg(newFileName), 
				QMessageBox::Yes | QMessageBox::Default, 
				QMessageBox::No | QMessageBox::Escape) == QMessageBox::No)
				return;
			QFile::remove(job.Target.absoluteDir().absoluteFilePath(newFileName));
		}
		job.Target.setFile(job.Target.absoluteDir(), newFileName);
		QFile::copy(job.Source.absoluteFilePath(), job.Target.absoluteFilePath());
		delete m_fileList->takeItem(m_fileList->row(items.at(i)));
	}		
}
Example #19
0
bool ConnectionManager2::applyConfig(QVariant const & config)
{
    if (config.type() != QVariant::List)
        return false;

    QList<Connection *> newConns;
    struct cleanup
    {
        QList<Connection *> & conns;
        cleanup(QList<Connection *> & conns) : conns(conns) {}
        ~cleanup() { for (int i = 0; i < conns.size(); ++i) conns[i]->releaseAll(); }
    } cleanupGuard(newConns);

    QList<QVariant> const & connConfigs = config.toList();

    for (int i = 0; i < connConfigs.size(); ++i)
    {
        if (connConfigs[i].type() != QVariant::Hash)
            return false;
        QHash<QString, QVariant> const & connConfig = connConfigs[i].toHash();

        QVariant typev = connConfig.value("type");
        if (typev.type() != QVariant::String)
            return false;

        QString const & type = typev.toString();

        ConnectionPointer<Connection> conn;
        if (type == "serial_port")
            conn.reset(new SerialPort());
        else if (type == "tcp_client")
            conn.reset(new TcpSocket());
        else if (type == "udp_socket")
            conn.reset(new UdpSocket());
#ifdef HAVE_LIBYB
        else if (type == "usb_yb_acm")
            conn.reset(new UsbAcmConnection2(m_yb_runner));
#endif

        if (!conn)
            return false;

        QVariant settings = connConfig.value("settings");
        if (settings.type() != QVariant::Hash || !conn->applyConfig(settings.toHash()))
            return false;

        newConns.push_back(conn.data());
        conn.take();
    }

    this->clearUserOwnedConns();
    while (!newConns.empty())
    {
        this->addUserOwnedConn(newConns.back());
        newConns.pop_back();
    }

    return true;
}
Example #20
0
std::string App::__getSelectedCuvant() {
	QList<QListWidgetItem*> selectedItems = this->__cuvinteListWidget->selectedItems();
	if (selectedItems.empty()) {
		return "";
	}
	QListWidgetItem* selectedItem = selectedItems.at(0);
	return selectedItem->text().toStdString();
}
Example #21
0
    void project(const Template &src, Template &dst) const
    {
        QList<QPointF> points = src.file.points();
        QList<QRectF> rects = src.file.rects();

        if (points.empty() || rects.empty()) {
            dst = src;
            qWarning("Procrustes alignment failed because points or rects are empty.");
            return;
        }

        // Assume rect appended last was bounding box
        points.append(rects.last().topLeft());
        points.append(rects.last().topRight());
        points.append(rects.last().bottomLeft());
        points.append(rects.last().bottomRight());

        Scalar mean = cv::mean(OpenCVUtils::toPoints(points).toVector().toStdVector());
        for (int i = 0; i < points.size(); i++) points[i] -= QPointF(mean[0],mean[1]);

        Eigen::MatrixXf srcMat(points.size(), 2);
        float norm = cv::norm(OpenCVUtils::toPoints(points).toVector().toStdVector());
        for (int i = 0; i < points.size(); i++) {
            points[i] /= norm;
            srcMat(i,0) = points[i].x();
            srcMat(i,1) = points[i].y();
        }

        Eigen::JacobiSVD<Eigen::MatrixXf> svd(srcMat.transpose()*meanShape, Eigen::ComputeThinU | Eigen::ComputeThinV);
        Eigen::MatrixXf R = svd.matrixU()*svd.matrixV().transpose();

        dst = src;

        // Store procrustes stats in the order:
        // R(0,0), R(1,0), R(1,1), R(0,1), mean_x, mean_y, norm
        QList<float> procrustesStats;
        procrustesStats << R(0,0) << R(1,0) << R(1,1) << R(0,1) << mean[0] << mean[1] << norm;
        dst.file.setList<float>("ProcrustesStats",procrustesStats);

        if (warp) {
            Eigen::MatrixXf dstMat = srcMat*R;
            for (int i = 0; i < dstMat.rows(); i++) {
                dst.file.appendPoint(QPointF(dstMat(i,0),dstMat(i,1)));
            }
        }
    }
Example #22
0
QString QgsMeshCalculatorDialog::currentDatasetGroup() const
{
  const QList<QListWidgetItem *> items = mDatasetsListWidget->selectedItems();
  if ( !items.empty() )
    return items[0]->text();
  else
    return mDatasetsListWidget->item( 0 )->text();
}
Example #23
0
std::string App::__getSelectedExplicatie() {
	QList<QListWidgetItem*> selectedItems = this->__explicatiiListWidget->selectedItems();
	if (selectedItems.empty()) {
		return "";
	}
	QListWidgetItem* selectedItem = selectedItems.at(0);
	return selectedItem->text().toStdString();
}
bool BtBookshelfTreeModel::setData(const QModelIndex &itemIndex,
                                   const QVariant &value,
                                   int role) {
    typedef QPair<Item *, QModelIndex> IP;

    Qt::CheckState newState;
    if (role == Qt::CheckStateRole) {
        bool ok;
        newState = (Qt::CheckState) value.toInt(&ok);
        if (!ok) return false;
    }
    else {
        return false;
    }

    // Handle partially checked as checked here in setData():
    if (newState == Qt::PartiallyChecked) newState = Qt::Checked;

    Item *item(static_cast<Item*>(itemIndex.internalPointer()));
    Q_ASSERT(item != 0);
    if (item->checkState() == newState) return false;

    // Recursively (un)check all children:
    QList<IP> q;
    IP p(item, itemIndex);
    for (;;) {
        if (item->checkState() != newState) {
            item->setCheckState(newState);
            emit dataChanged(p.second, p.second);
            if (item->type() == Item::ITEM_MODULE) {
                ModuleItem *mItem(static_cast<ModuleItem*>(item));
                CSwordModuleInfo *mInfo(mItem->moduleInfo());
                if (newState == Qt::Checked) {
                    m_checkedModulesCache.insert(mInfo);
                    emit moduleChecked(mInfo, true);
                }
                else {
                    m_checkedModulesCache.remove(mInfo);
                    emit moduleChecked(mInfo, false);
                }
            }
            else {
                const QList<Item*> &children(item->children());
                for (int i(0); i < children.size(); i++) {
                    q.append(IP(children.at(i), index(i, 0, p.second)));
                }
            }
        }
        if (q.empty()) break;
        p = q.takeFirst();
        item = p.first;
    }

    // Recursively change parent check states.
    resetParentCheckStates(itemIndex.parent());

    return true;
}
Example #25
0
MessageModel::StatusCode MessageModel::sendMessages(const QList<SendMessagesRecipient> &recipients, const QString &addressFrom)
{

    QSet<QString> setAddress;

    if(recipients.empty())
        return OK;

    // Pre-check input data for validity
    foreach(const SendMessagesRecipient &rcp, recipients)
    {
        if(!walletModel->validateAddress(rcp.address))
            return InvalidAddress;

        if(rcp.message == "")
            return MessageCreationFailed;

        std::string sendTo  = rcp.address.toStdString();
        std::string pubkey  = rcp.pubkey.toStdString();
        std::string message = rcp.message.toStdString();
        std::string addFrom = addressFrom.toStdString();

        SecureMsgAddAddress(sendTo, pubkey);
        setAddress.insert(rcp.address);
        
        std::string sError;
        if (SecureMsgSend(addFrom, sendTo, message, sError) != 0)
        {
            QMessageBox::warning(NULL, tr("Send Secure Message"),
                tr("Send failed: %1.").arg(sError.c_str()),
                QMessageBox::Ok, QMessageBox::Ok);
            
            return FailedErrorShown;
        };

        // Add addresses / update labels that we've sent to to the address book
        std::string strAddress = rcp.address.toStdString();
        CTxDestination dest = CBitcoinAddress(strAddress).Get();
        std::string strLabel = rcp.label.toStdString();
        {
            LOCK(wallet->cs_wallet);

            std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);

            // Check if we have a new address or an updated label
            if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
            {
                wallet->SetAddressBookName(dest, strLabel);
            }
        }
    }

    if(recipients.size() > setAddress.size())
        return DuplicateAddress;

    return OK;
}
Example #26
0
static inline bool isValidIcon(const QIcon &icon)
{
    if (!icon.isNull()) {
        const QList<QSize> availableSizes = icon.availableSizes();
        if (!availableSizes.empty()) {
            return !availableSizes.front().isEmpty();
        }
    }
    return false;
}
Example #27
0
void TimestampsUpdater::updateTimestamps(const TopLevelProjectPtr &project,
        const QList<ResolvedProductPtr> &products, const Logger &logger)
{
    TimestampsUpdateVisitor v;
    for (const ResolvedProductPtr &product : products)
        v.visitProduct(product);
    if (!products.empty())
        project->buildData->setDirty();
    project->store(logger);
}
Example #28
0
bool FxSelection::insertPasteSelection() {
  QClipboard *clipboard  = QApplication::clipboard();
  const FxsData *fxsData = dynamic_cast<const FxsData *>(clipboard->mimeData());

  m_pastePosition = TConst::nowhere;

  if (!fxsData || !fxsData->isConnected()) return false;

  if (m_selectedLinks.isEmpty()) return true;

  // Start an undo block and ensure it is appropriately destroyed
  struct Auto {
    bool m_destruct;
    ~Auto() {
      if (m_destruct) TUndoManager::manager()->endBlock();
    }
  } auto_ = {false};

  // Need to make a temporary copy of selected links. It's necessary since the
  // selection will
  // be updated (cleared) after each insertion.
  QList<TFxCommand::Link> selectedLinks(m_selectedLinks);

  int i, size = selectedLinks.size();
  for (i = 0; i < size; ++i) {
    // Clone the fxs to be inserted
    QList<TFxP> fxs;
    QMap<TFx *, int> zeraryFxColumnSize;
    QList<TXshColumnP> columns;

    fxsData->getFxs(fxs, zeraryFxColumnSize, columns);
    if (fxs.empty() && columns.empty()) return true;

    if (!auto_.m_destruct)
      auto_.m_destruct = true, TUndoManager::manager()->beginBlock();

    TFxCommand::insertPasteFxs(selectedLinks[i], fxs.toStdList(),
                               zeraryFxColumnSize.toStdMap(),
                               columns.toStdList(), m_xshHandle, m_fxHandle);
  }

  return true;
}
Example #29
0
void ConstellationMgr::selectedObjectChange(StelModule::StelModuleSelectAction action)
{
	StelObjectMgr* omgr = GETSTELMODULE(StelObjectMgr);
	Q_ASSERT(omgr);
	const QList<StelObjectP> newSelected = omgr->getSelectedObject();
	if (newSelected.empty())
	{
		// Even if do not have anything selected, KEEP constellation selection intact
		// (allows viewing constellations without distraction from star pointer animation)
		// setSelected(NULL);
		return;
	}

	const QList<StelObjectP> newSelectedConst = omgr->getSelectedObject("Constellation");
	if (!newSelectedConst.empty())
	{
		// If removing this selection
		if(action == StelModule::RemoveFromSelection)
		{
			unsetSelectedConst((Constellation *)newSelectedConst[0].data());
		}
		else
		{
			// Add constellation to selected list (do not select a star, just the constellation)
			setSelectedConst((Constellation *)newSelectedConst[0].data());
		}
	}
	else
	{
		const QList<StelObjectP> newSelectedStar = omgr->getSelectedObject("Star");
		if (!newSelectedStar.empty())
		{
//			if (!added)
//				setSelected(NULL);
			setSelected(newSelectedStar[0].data());
		}
		else
		{
//			if (!added)
				setSelected(NULL);
		}
	}
}
Example #30
0
void ExpoBlendingDlg::slotAddItems(const QList<QUrl>& urls)
{
    if (!urls.empty())
    {
        d->mngr->thread()->identifyFiles(urls);

        if (!d->mngr->thread()->isRunning())
            d->mngr->thread()->start();
    }
}