static void _writeByteArrayToFd(const QByteArray& data, const QByteArray& prefix, FILE *fh)
{
    QList<QByteArray> lines = data.split('\n');
    if (lines.isEmpty())
        return;

    // If the last item was a separator, there will be an extra blank item at the end
    if (lines.last().isEmpty())
        lines.removeLast();

    if (!lines.isEmpty()) {
        QFile f;
        f.open(fh, QIODevice::WriteOnly);
        foreach (const QByteArray& line, lines) {
            f.write(prefix);
            f.write(line);
            f.write("\n");
        }
QList<QStringList> QHelpDBReader::filterAttributeSets() const
{
    QList<QStringList> result;
    if (m_query) {
        m_query->exec(QLatin1String("SELECT a.Id, b.Name FROM FileAttributeSetTable a, "
            "FilterAttributeTable b WHERE a.FilterAttributeId=b.Id ORDER BY a.Id"));
        int oldId = -1;
        while (m_query->next()) {
            int id = m_query->value(0).toInt();
            if (id != oldId) {
                result.append(QStringList());
                oldId = id;
            }
            result.last().append(m_query->value(1).toString());
        }
    }
    return result;
}
Пример #3
0
void PropertiesWidget::saveSettings() {
  Preferences* const pref = Preferences::instance();
  pref->setPropVisible(state==VISIBLE);
  // Splitter sizes
  QSplitter *hSplitter = static_cast<QSplitter*>(parentWidget());
  QList<int> sizes;
  if (state == VISIBLE)
    sizes = hSplitter->sizes();
  else
    sizes = slideSizes;
  qDebug("Sizes: %d", sizes.size());
  if (sizes.size() == 2) {
    pref->setPropSplitterSizes(QString::number(sizes.first())+','+QString::number(sizes.last()));
  }
  pref->setPropFileListState(filesList->header()->saveState());
  // Remember current tab
  pref->setPropCurTab(m_tabBar->currentIndex());
}
void QalfTreeModel::setupModelData(const QStringList &lines, TreeItem *parent) {
	QList<TreeItem*> parents;
	QList<int> indentations;
	parents << parent;
	indentations << 0;

	int number = 0;

	while (number < lines.count()) {
		int position = 0;
		while (position < lines[number].length()) {
			if (lines[number].mid(position, 1) != " ")
				break;
			position++;
		}

		QString lineData = lines[number].mid(position).trimmed();

		if (!lineData.isEmpty()) {
			// Read the column data from the rest of the line.
			QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
			QList<QVariant> columnData;
			for (int column = 0; column < columnStrings.count(); ++column)
				columnData << columnStrings[column];

			if (position > indentations.last()) {
				// The last child of the current parent is now the new parent
				// unless the current parent has no children.

				if (parents.last()->childCount() > 0) {
					parents << parents.last()->child(parents.last()->childCount()-1);
					indentations << position;
				}
			} else {
				while (position < indentations.last() && parents.count() > 0) {
					parents.pop_back();
					indentations.pop_back();
				}
			}

			// Append a new item to the current parent's list of children.
			parents.last()->appendChild(new TreeItem(columnData, parents.last()));
		}

		number++;
	}
}
Пример #5
0
QList<SharedSampleBuffer> SampleUtils::splitSampleBuffer( const SharedSampleBuffer sampleBuffer,
                                                          QList<int> slicePointFrameNums )
{
    Q_ASSERT( ! slicePointFrameNums.isEmpty() );

    QList<SharedSampleBuffer> sampleBufferList;

    qSort( slicePointFrameNums );

    const int totalNumFrames = sampleBuffer->getNumFrames();

    if ( slicePointFrameNums.last() != totalNumFrames )
    {
        slicePointFrameNums << totalNumFrames;
    }

    const int numChans = sampleBuffer->getNumChannels();

    int startFrame = 0;

    foreach ( int frameNum, slicePointFrameNums )
    {
        if( frameNum <= totalNumFrames )
        {
            const int numFrames = frameNum - startFrame;

            if ( numFrames > 0 )
            {
                SharedSampleBuffer newSampleBuffer( new SampleBuffer( numChans, numFrames ) );

                for ( int chanNum = 0; chanNum < numChans; chanNum++ )
                {
                    newSampleBuffer->copyFrom( chanNum, 0, *sampleBuffer.data(), chanNum, startFrame, numFrames );
                }

                sampleBufferList << newSampleBuffer;

                startFrame += numFrames;
            }
        }
    }

    return sampleBufferList;
}
/** Sets the modules used by the search. */
void BtSearchOptionsArea::setModules( QList<CSwordModuleInfo*> modules ) {
    qDebug() << "BtSearchOptionsArea::setModules";
    qDebug() << modules;
    QString t;

    m_modules.clear(); //remove old modules
    QList<CSwordModuleInfo*>::iterator end_it = modules.end();

    for (QList<CSwordModuleInfo*>::iterator it(modules.begin()); it != end_it; ++it) {
        /// \todo Check for containsRef compat
        if (*it == 0) { //don't operate on null modules.
            continue;
        }
        qDebug() << "new module:" << (*it)->name();
        if ( !m_modules.contains(*it) ) {
            m_modules.append( *it );
            t.append( (*it)->name() );
            if (*it != modules.last()) {
                t += QString::fromLatin1(", "); // so that it will become a readable list (WLC, LXX, GerLut...)
            }
        }
    };
    //m_modulesLabel->setText(t);
    int existingIndex = m_modulesCombo->findText(t);
    qDebug() << "index of the module list string which already exists in combobox:" << existingIndex;
    if (existingIndex >= 0) {
        m_modulesCombo->removeItem(existingIndex);
    }
    if (m_modulesCombo->count() > 10) {
        m_modulesCombo->removeItem(m_modulesCombo->count() - 1);
    }
    m_modulesCombo->insertItem(0, t);
    m_modulesCombo->setItemData(0, t, Qt::ToolTipRole);
    m_modulesCombo->setCurrentIndex(0);
    m_modulesCombo->setToolTip(t);
    //Save the list in config here, not when deleting, because the history may be used
    // elsewhere while the dialog is still open
    QStringList historyList;
    for (int i = 0; i < m_modulesCombo->count(); ++i) {
        historyList.append(m_modulesCombo->itemText(i));
    }
    CBTConfig::set(CBTConfig::searchModulesHistory, historyList);
    emit sigSetSearchButtonStatus(modules.count() != 0);
}
Пример #7
0
Expression RangeCommand::operator()(const QList< Analitza::Expression >& args)
{
    Expression ret;
    
    const int nargs = args.size();
    
    double a = 1;
    double b = 0;
    double h = 1;
    
    switch(nargs) {
        case 0: {
            ret.addError(QCoreApplication::tr("Invalid parameter count for '%1'").arg(RangeCommand::id));
            
            return ret;
        }    break;
        case 1: {
            b = static_cast<const Analitza::Cn*>(args.first().tree())->value();
        }    break;
        case 2: {
            a = static_cast<const Analitza::Cn*>(args.first().tree())->value();
            b = static_cast<const Analitza::Cn*>(args.last().tree())->value();
        }    break;
        case 3: {
            a = static_cast<const Analitza::Cn*>(args.at(0).tree())->value();
            b = static_cast<const Analitza::Cn*>(args.at(1).tree())->value();
            h = static_cast<const Analitza::Cn*>(args.at(2).tree())->value();
        }    break;
        default:
            ret.addError(QCoreApplication::tr("Invalid parameter count for '%1'").arg(RangeCommand::id));
            
            return ret;
            break;
    }
    
    Analitza::List *seq = new Analitza::List;
        
    for (double x = a; x <= b; x += h)
        seq->appendBranch(new Analitza::Cn(x));
    
    ret.setTree(seq);
    
    return ret;
}
Пример #8
0
	Private(const QByteArray *ba)
	{
		init();

		QBuffer buffer((QByteArray *)ba);
		buffer.open(QBuffer::ReadOnly);
		QImageReader reader(&buffer);

		while ( reader.canRead() ) {
			QImage image = reader.read();
			if ( !image.isNull() ) {
				Frame newFrame;
				frames.append( newFrame );
				frames.last().impix  = Impix(image);
				frames.last().period = reader.nextImageDelay();
			}
			else {
				break;
			}
		}

		looping = reader.loopCount();

		if ( !reader.supportsAnimation() && (frames.count() == 1) ) {
			QImage frame = frames[0].impix.image();

			// we're gonna slice the single image we've got if we're absolutely sure
			// that it's can be cut into multiple frames
			if ((frame.width() / frame.height() > 0) && !(frame.width() % frame.height())) {
				int h = frame.height();
				QList<Frame> newFrames;

				for (int i = 0; i < frame.width() / frame.height(); i++) {
					Frame newFrame;
					newFrames.append( newFrame );
					newFrames.last().impix  = Impix(frame.copy(i * h, 0, h, h));
					newFrames.last().period = 120;
				}

				frames  = newFrames;
				looping = 0;
			}
		}
	}
Пример #9
0
	void TwitterPage::updateScreenTwits (QList<Tweet_ptr> twits)
	{
		if (twits.isEmpty ())	// if we have no tweets to parse
			return;

		Tweet_ptr firstNewTwit = twits.first ();

		if (ScreenTwits_.length () && (twits.last ()->GetId () == ScreenTwits_.first ()->GetId ())) // if we should prepend
			for (auto i = twits.end () - 2; i >= twits.begin (); i--)
				ScreenTwits_.insert (0, *i);
		else
		{
			int i;
			// Now we'd find firstNewTwit in twitList
			for (i = 0; i < ScreenTwits_.length (); i++)
				if ((ScreenTwits_.at (i)->GetId ()) == firstNewTwit->GetId ())
					break;

			int insertionShift = ScreenTwits_.length () - i;    // We've already got insertionShift twits to our list

			for (i = 0; i < insertionShift && !twits.isEmpty (); i++)
				twits.removeFirst ();

			if (XmlSettingsManager::Instance ()->property ("notify").toBool ())
			{
				if (twits.length () == 1)			// We can notify the only twit
				{
					const auto& notification = Util::MakeNotification (twits.first ()->GetAuthor ()->GetUsername (),
							twits.first ()->GetText (),
							PInfo_);
					EntityManager_->HandleEntity (notification);
				}
				else if (!twits.isEmpty ()) {
					const auto& notification = Util::MakeNotification (tr ("Woodpecker"),
							tr ( "%1 new twit (s)" ).arg (twits.length ()),
							PInfo_);
					EntityManager_->HandleEntity (notification);
				}
			}
			ScreenTwits_.append (twits);
		}

		UpdateReady_ = true;
	}
Пример #10
0
bool Viewport::touch_event(QTouchEvent *event)
{
	QList<QTouchEvent::TouchPoint> touchPoints = event->touchPoints();

	if (touchPoints.count() != 2) {
		pinch_zoom_active_ = false;
		return false;
	}

	const QTouchEvent::TouchPoint &touchPoint0 = touchPoints.first();
	const QTouchEvent::TouchPoint &touchPoint1 = touchPoints.last();

	if (!pinch_zoom_active_ ||
	    (event->touchPointStates() & Qt::TouchPointPressed)) {
		pinch_offset0_ = (view_.offset() + view_.scale() * touchPoint0.pos().x()).convert_to<double>();
		pinch_offset1_ = (view_.offset() + view_.scale() * touchPoint1.pos().x()).convert_to<double>();
		pinch_zoom_active_ = true;
	}

	double w = touchPoint1.pos().x() - touchPoint0.pos().x();
	if (abs(w) >= 1.0) {
		const double scale =
			fabs((pinch_offset1_ - pinch_offset0_) / w);
		double offset = pinch_offset0_ - touchPoint0.pos().x() * scale;
		if (scale > 0)
			view_.set_scale_offset(scale, offset);
	}

	if (event->touchPointStates() & Qt::TouchPointReleased) {
		pinch_zoom_active_ = false;

		if (touchPoint0.state() & Qt::TouchPointReleased) {
			// Primary touch released
			drag_release();
		} else {
			// Update the mouse down fields so that continued
			// dragging with the primary touch will work correctly
			mouse_down_point_ = touchPoint0.pos().toPoint();
			drag();
		}
	}

	return true;
}
Пример #11
0
KnobSpin::KnobSpin(const QString &title, double min, double max, double step, QWidget *parent):
    QWidget(parent)
{
  QFont font("Helvetica", 10);

  knob_ = new QwtKnob(this);
  knob_->setFont(font);
  knob_->setRange(min, max);
  QwtScaleDiv scaleDiv =
      knob_->scaleEngine()->divideScale(min, max, 5, 3);
  QList<double> ticks = scaleDiv.ticks(QwtScaleDiv::MajorTick);
  if ( ticks.size() > 0 && ticks[0] > min )
  {
      if ( ticks.first() > min )
          ticks.prepend(min);
      if ( ticks.last() < max )
          ticks.append(max);
  }
  scaleDiv.setTicks(QwtScaleDiv::MajorTick, ticks);
  knob_->setScale(scaleDiv);

  knob_->setKnobWidth(150);
  knob_->setStep(step);

  spin_ = new QDoubleSpinBox(this);
  spin_->setRange(min, max);
  spin_->setSingleStep(step);

  font.setBold(true);
  label_ = new QLabel(title, this);
  label_->setFont(font);
  label_->setAlignment(Qt::AlignTop | Qt::AlignHCenter);

  setSizePolicy(QSizePolicy::MinimumExpanding,
      QSizePolicy::MinimumExpanding);

  connect(spin_, SIGNAL(valueChanged(double)),
          this, SIGNAL(valueChanged(double)));

  connect(knob_, SIGNAL(valueChanged(double)),
          spin_, SLOT(setValue(double)) );
  connect(spin_, SIGNAL(valueChanged(double)),
          knob_, SLOT(setValue(double)) );
}
Пример #12
0
void TreeModel::setupModelData(const QStringList &lines, TreeItem *parent)
{
    QList<TreeItem*> parents;
    QList<int> indentations;
    parents << parent;
    indentations << 0;

    int number = 0;

    while (number < lines.count()) {
        int position = 0;
        while (position < lines[number].length()) {
            if (lines[number].at(position) != ' ')
                break;
            ++position;
        }

        QString lineData = lines[number].mid(position).trimmed();

        if (!lineData.isEmpty()) {
            // Read the column data from the rest of the line.
            QStringList columnStrings = lineData.split("\t", QString::SkipEmptyParts);
            QVector<QVariant> columnData;
            for (int column = 0; column < columnStrings.count(); ++column)
                columnData << columnStrings[column];

            if (position > indentations.last()) {
                // The last child of the current parent is now the new parent
                // unless the current parent has no children.

                if (parents.last()->childCount() > 0) {
                    parents << parents.last()->child(parents.last()->childCount()-1);
                    indentations << position;
                }
            } else {
                while (position < indentations.last() && parents.count() > 0) {
                    parents.pop_back();
                    indentations.pop_back();
                }
            }

            // Append a new item to the current parent's list of children.
            TreeItem *parent = parents.last();
            parent->insertChildren(parent->childCount(), 1, rootItem->columnCount());
            for (int column = 0; column < columnData.size(); ++column)
                parent->child(parent->childCount() - 1)->setData(column, columnData[column]);
        }

        ++number;
    }
}
Пример #13
0
bool QgsComposerTextTable::getFeatureAttributes( QList<QgsAttributeMap>& attributeMaps )
{
  attributeMaps.clear();

  QList< QStringList >::const_iterator rowIt = mRowText.constBegin();
  QStringList currentStringList;
  for ( ; rowIt != mRowText.constEnd(); ++rowIt )
  {
    currentStringList = *rowIt;

    attributeMaps.push_back( QgsAttributeMap() );
    for ( int i = 0; i < currentStringList.size(); ++i )
    {
      attributeMaps.last().insert( i, QVariant( currentStringList.at( i ) ) );
    }
  }

  return true;
}
Пример #14
0
// first use RideFile::startTime, then Measure then fallback to Global Setting
static double
getWeight(const MainWindow *main, const RideFile *ride)
{
    // ride
    double weight;
    if ((weight = ride->getTag("Weight", "0.0").toDouble()) > 0) {
        return weight;
    }
#if 0
    // withings?
    QList<SummaryMetrics> measures = main->metricDB->getAllMeasuresFor(QDateTime::fromString("Jan 1 00:00:00 1900"), ride->startTime());
    if (measures.count()) {
        return measures.last().getText("Weight", "0.0").toDouble();
    }
#endif

    // global options
    return appsettings->cvalue(main->cyclist, GC_WEIGHT, "75.0").toString().toDouble(); // default to 75kg
}
Пример #15
0
void QHelpProjectDataPrivate::readFiles()
{
	while (!atEnd()) {
		readNext();
		if (isStartElement()) {
			if (name() == QLatin1String("file"))
                filterSectionList.last().addFile(readElementText());
			else
				raiseUnknownTokenError();
		} else if (isEndElement()) {
			if (name() == QLatin1String("file"))
				continue;
			else if (name() == QLatin1String("files"))
				break;
			else
				raiseUnknownTokenError();
		}
	}
}
Пример #16
0
QList<RRefPoint> RPolylineData::getReferencePoints(RS::ProjectionRenderingHint hint) const {
    Q_UNUSED(hint)

    QList<RRefPoint> ret = RRefPoint::toRefPointList(getVertices());
    if (!ret.isEmpty()) {
        // mark start and end points:
        ret.first().setStart(true);
        ret.last().setEnd(true);
    }
    for (int i=0; i<countSegments(); i++) {
        if (isArcSegmentAt(i)) {
            QSharedPointer<RArc> arc = getSegmentAt(i).dynamicCast<RArc>();
            if (!arc.isNull()) {
                ret.append(RRefPoint(arc->getMiddlePoint(), RRefPoint::Secondary));
            }
        }
    }
    return ret;
}
Пример #17
0
	void startHandleRequest(ZhttpRequest *req, int basePathStart, const QByteArray &asPath, const DomainMap::Entry &route)
	{
		Session *s = new Session(this);
		s->req = req;

		QUrl uri = req->requestUri();

		QByteArray encPath = uri.encodedPath();
		s->path = encPath.mid(basePathStart);

		QList<QByteArray> parts = s->path.split('/');
		if(!parts.isEmpty() && parts.last().startsWith("jsonp"))
		{
			if(uri.hasQueryItem("callback"))
			{
				s->jsonpCallback = uri.queryItemValue("callback").toUtf8();
				uri.removeAllQueryItems("callback");
			}
			else if(uri.hasQueryItem("c"))
			{
				s->jsonpCallback = uri.queryItemValue("c").toUtf8();
				uri.removeAllQueryItems("c");
			}
		}

		s->asUri = uri;
		s->asUri.setScheme((s->asUri.scheme() == "https") ? "wss" : "ws");
		if(!asPath.isEmpty())
			s->asUri.setEncodedPath(asPath);
		else
			s->asUri.setEncodedPath(encPath.mid(0, basePathStart));

		s->route = route;

		connect(req, SIGNAL(readyRead()), SLOT(req_readyRead()));
		connect(req, SIGNAL(bytesWritten(int)), SLOT(req_bytesWritten(int)));
		connect(req, SIGNAL(error()), SLOT(req_error()));

		sessions += s;
		sessionsByRequest.insert(s->req, s);

		processRequestInput(s);
	}
Пример #18
0
void VMdEditor::contextMenuEvent(QContextMenuEvent *p_event)
{
    QMenu *menu = createStandardContextMenu();
    menu->setToolTipsVisible(true);

    VEditTab *editTab = dynamic_cast<VEditTab *>(parent());
    Q_ASSERT(editTab);
    if (editTab->isEditMode()) {
        const QList<QAction *> actions = menu->actions();

        if (textCursor().hasSelection()) {
            initCopyAsMenu(actions.isEmpty() ? NULL : actions.last(), menu);
        } else {
            QAction *saveExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/save_exit.svg"),
                                               tr("&Save Changes And Read"),
                                               menu);
            saveExitAct->setToolTip(tr("Save changes and exit edit mode"));
            connect(saveExitAct, &QAction::triggered,
                    this, [this]() {
                        emit m_object->saveAndRead();
                    });

            QAction *discardExitAct = new QAction(VIconUtils::menuIcon(":/resources/icons/discard_exit.svg"),
                                                  tr("&Discard Changes And Read"),
                                                  menu);
            discardExitAct->setToolTip(tr("Discard changes and exit edit mode"));
            connect(discardExitAct, &QAction::triggered,
                    this, [this]() {
                        emit m_object->discardAndRead();
                    });

            menu->insertAction(actions.isEmpty() ? NULL : actions[0], discardExitAct);
            menu->insertAction(discardExitAct, saveExitAct);
        }

        if (!actions.isEmpty()) {
            menu->insertSeparator(actions[0]);
        }
    }

    menu->exec(p_event->globalPos());
    delete menu;
}
Пример #19
0
InputEvent InputEvent::randomizeEvent() const
{
  qsrand(QTime::currentTime().msec()); // seed with number of msec should be random enough :)
	QList<word> locs = words2();
  word last = locs.takeLast();
  //Shuffle words
  int i,n;
  n = (locs.end()-locs.begin());
  for (i=n-1; i>0; --i) {
    int rand = int(qrand()/static_cast<double>( RAND_MAX ) * (i+1));
    qSwap (locs[i],locs[rand]); 
  }
  //Insert last word randomly
  int lastIns = int(qrand()/static_cast<double>( RAND_MAX ) * n);
  if(lastIns == locs.size()){
    locs.append(last);
  } else {
    //Have to move the spaces after the shuffled last to the new last
    word &trueLast = locs.last();
    int end = trueLast.keys.size()-1;
    while(end > 0 && trueLast.keys.at(end).isSpace()) --end;
    end++;
    int size = trueLast.keys.size()-end;
    last.keys += trueLast.keys.mid(end,size);
    last.times += trueLast.times.mid(end,size);
    last.error += trueLast.error.mid(end,size);

    trueLast.keys.remove(end,size);
    trueLast.times.remove(end,size);
    trueLast.error.remove(end,size);
    locs.insert(lastIns,last);
  }

  QString keys;
  QVector<int> times;
  QVector<bool> errors;

  foreach(word w,locs){
    keys += w.keys;
    times += w.times;
    errors += w.error;
  }
Пример #20
0
void AssignLayers::run(Graph &graph)
{
    emit setStatusMsg("Assigning layers...");

    // copy the nodes to a linked list
    QLinkedList<AbstractNode*> vertices;
    for(AbstractNode* v : graph.getNodes()) {
        vertices.append(v);
    }

    QSet<AbstractNode*> U;
    QSet<AbstractNode*> Z;
    QList<QList<AbstractNode*>> layers;

    //add the first layer
    int currentLayer = 0;
    layers.append(QList<AbstractNode*>());
    while(!vertices.isEmpty()) {
        AbstractNode* selected = nullptr;
        for(AbstractNode* v : vertices) {
            if(Z.contains(v->getPredecessors().toSet())) {
                selected = v;
                break;
            }
        }

        if(selected != nullptr) {
            selected->setLayer(currentLayer);
            layers.last().append(selected);
            U.insert(selected);
            vertices.removeOne(selected);
        } else {
            currentLayer++;
            layers.append(QList<AbstractNode*>());
            Z.unite(U);
        }
    }

    graph.setLayers(layers);
    graph.repaintLayers();
    emit setStatusMsg("Assigning layers... Done!");
}
Пример #21
0
void MainWindow::on_quantifierAddPushButton_clicked()
{
    QList<QAbstractSpinBox *> sbList = ui->quantifierValuesGroupBox->findChildren<QAbstractSpinBox *>();
    bool ok = true;
    QList<double> values;
    for (int i = 0; i < sbList.size(); i++) {
        double val = sbList.at(i)->text().toDouble();
        if (i > 0 && values.last() > val) {
            ok = false;
        }
        values << val;
    }
    if (!ok) {
        QString err = "problem with values";
        qDebug() << err;
        ui->statusBar->showMessage(err, 2000);
        return;
    }
    Range r = (ui->quantAbsRadioButton->isChecked() ? Absolute : Relative);
    const QString name = ui->quantifierNameLineEdit->text();
    if (name.isNull() || name.isEmpty()) {
        QString err = "problem with name";
        qDebug() << err;
        ui->statusBar->showMessage(err, 2000);
        return;
    }
    if (ui->quantifiersListWidget->findItems(name, Qt::MatchFixedString).size() > 0) {
        QString err = "such item already exists";
        qDebug() << err;
        ui->statusBar->showMessage(err, 2000);
        return;
    }
    Quantifier q(name, values, r, (mFunctionType == Triangle ? "TRIANGLE" : "TRAPEZOID"), this);
    //qDebug() << q << (void *)q << qobject_cast<QObject *>(q);
    QVariant v = QVariant::fromValue(q);
    QListWidgetItem *item = new QListWidgetItem(q.quantName());
    item->setData(Qt::UserRole, v);
    ui->quantifiersListWidget->addItem(item);
    ui->statusBar->showMessage(QString("quantifier \"%1\" added successfully").arg(name), 2000);
    QTextStream stream(stdout);
    stream << (q) << endl;
}
Пример #22
0
void NorNode::inputsUpdated( qint64 pTimeStamp )
{
	NodeControlBase::inputsUpdated( pTimeStamp );

	QList<fugio::PinVariantIterator>	ItrLst;
	int									ItrMax = 0;

	for( QSharedPointer<fugio::PinInterface> P : mNode->enumInputPins() )
	{
		ItrLst << fugio::PinVariantIterator( P );

		ItrMax = std::max( ItrMax, ItrLst.last().count() );
	}

	if( !ItrMax )
	{
		return;
	}

	bool		UpdateOutput = mPinOutput->alwaysUpdate();

	variantSetCount( mValOutput, ItrMax, UpdateOutput );

	for( int i = 0 ; i < ItrMax ; i++ )
	{
		bool		OutVal;

		for( int j = 0 ; j < ItrLst.size() ; j++ )
		{
			bool	NewVal = ItrLst.at( j ).index( i ).toBool();

			OutVal = ( !j ? NewVal : OutVal | NewVal );
		}

		variantSetValue<bool>( mValOutput, i, !OutVal, UpdateOutput );
	}

	if( UpdateOutput )
	{
		pinUpdated( mPinOutput );
	}
}
Пример #23
0
/*!
  Remove ticks from a list, that are not inside an interval

  \param ticks Tick list
  \param interval Interval

  \return Stripped tick list
*/
QList<double> QwtScaleEngine::strip( const QList<double>& ticks,
    const QwtInterval &interval ) const
{
    if ( !interval.isValid() || ticks.count() == 0 )
        return QList<double>();

    if ( contains( interval, ticks.first() )
        && contains( interval, ticks.last() ) )
    {
        return ticks;
    }

    QList<double> strippedTicks;
    for ( int i = 0; i < ticks.count(); i++ )
    {
        if ( contains( interval, ticks[i] ) )
            strippedTicks += ticks[i];
    }
    return strippedTicks;
}
void tst_QNmeaPositionInfoSource::startUpdates_expectLatestUpdateOnly()
{
    // If startUpdates() is called and an interval has been set, if multiple'
    // updates are in the buffer, only the latest update should be emitted

    QNmeaPositionInfoSource source(m_mode);
    QNmeaPositionInfoSourceProxyFactory factory;
    QNmeaPositionInfoSourceProxy *proxy = static_cast<QNmeaPositionInfoSourceProxy*>(factory.createProxy(&source));

    QSignalSpy spyUpdate(proxy->source(), SIGNAL(positionUpdated(QGeoPositionInfo)));
    proxy->source()->setUpdateInterval(500);
    proxy->source()->startUpdates();

    QList<QDateTime> dateTimes = createDateTimes(3);
    for (int i=0; i<dateTimes.count(); i++)
        proxy->feedUpdate(dateTimes[i]);

    QTRY_COMPARE(spyUpdate.count(), 1);
    QCOMPARE(spyUpdate[0][0].value<QGeoPositionInfo>().timestamp(), dateTimes.last());
}
Пример #25
0
/**-------------------------------------------------------------------------------------------
// gets the length of datas
// description:
//      this is a helper function, which calculates the count of data to send onto the canbus.
//      getting this value is done very simple: the last occurence of a value different than
//      zero is the last data-field... this means: if one would send data like:
//      0x12 0x45 0x00, the length is only 2 because 0x00 will not be sent :-( to avoid
//      such troubles, the gui supports an additional field, where the user can force to send
//      a number of bytes (in this case 3)
//------------------------------------------------------------------------------------------*/
int CANFestivalGui::getLength( QList<QLineEdit*>& theList )
{
    QLineEdit*  theLine;
    uint i = theList.length();

    theLine = theList.last( );
    while( ( theLine->text( ).toInt( ) == 0 ) || ( theLine->text( ).isEmpty( ) ) ) {
        if(i > 0) {
            i--;
            theLine = theList.at(i);
        } else {
            break;
        }
    }

    if( i == 0 )
        i = 1;

    return i;
}
Пример #26
0
void CMakeProjectVisitorTest::testVariables()
{
    QFETCH(QString, input);
    QFETCH(QStringList, result);
    
    QStringList name;
    QList<CMakeProjectVisitor::IntPair> variables =CMakeProjectVisitor::parseArgument(input);
    
//     qDebug() << "kakakaka" << result << variables;
    QCOMPARE(result.count(), variables.count());
    if(!variables.isEmpty())
        QCOMPARE(1, variables.last().level);
    
    foreach(const CMakeProjectVisitor::IntPair& v, variables)
    {
        QString name=input.mid(v.first+1, v.second-v.first-1);
        if(!result.contains(name))
            qDebug() << "not a var:" << name;
        QVERIFY(result.contains(name));
    }
Пример #27
0
void QEglFSWindow::setVisible(bool visible)
{
    QList<QEGLPlatformWindow *> windows = screen()->windows();

    if (window()->type() != Qt::Desktop) {
        if (visible) {
            screen()->addWindow(this);
        } else {
            screen()->removeWindow(this);
            windows = screen()->windows();
            if (windows.size())
                windows.last()->requestActivateWindow();
        }
    }

    QWindowSystemInterface::handleExposeEvent(window(), window()->geometry());

    if (visible)
        QWindowSystemInterface::flushWindowSystemEvents();
}
Пример #28
0
void SpreadSheet::actionSum()
{
    int row_first = 0;
    int row_last = 0;
    int row_cur = 0;

    int col_first = 0;
    int col_last = 0;
    int col_cur = 0;

    QList<QTableWidgetItem*> selected = table->selectedItems();

    if (!selected.isEmpty()) {
        QTableWidgetItem *first = selected.first();
        QTableWidgetItem *last = selected.last();
        row_first = table->row(first);
        row_last = table->row(last);
        col_first = table->column(first);
        col_last = table->column(last);
    }

    QTableWidgetItem *current = table->currentItem();

    if (current) {
        row_cur = table->row(current);
        col_cur = table->column(current);
    }

    QString cell1 = encode_pos(row_first, col_first);
    QString cell2 = encode_pos(row_last, col_last);
    QString out = encode_pos(row_cur, col_cur);

    if (runInputDialog(tr("Sum cells"), tr("First cell:"), tr("Last cell:"),
                       QString("%1").arg(QChar(0x03a3)), tr("Output to:"),
                       &cell1, &cell2, &out)) {
        int row;
        int col;
        decode_pos(out, &row, &col);
        table->item(row, col)->setText(tr("sum %1 %2").arg(cell1, cell2));
    }
}
Пример #29
0
void paintBBoxes(Mat& img, QString bboxFilePath, int drawBest)
{
    //paint directly all rectangles
    QFile file(bboxFilePath);
    if (!file.open(QIODevice::ReadOnly))
        return;

    QTextStream in(&file);
    QList<RectWithScore> boundingBoxes;    

    while (!in.atEnd())
    {
        QString line = in.readLine(); // 1:153.0629;116.1167;173.1750;189.0091;7.3548;
        if (line.startsWith('<'))
            continue;

        line = line.remove(0, 2); //remove first 2 characters
        QStringList values = line.split(";");
        Point pt1(values[0].toFloat()*2, values[1].toFloat()*2); //*2 because coordinates are scaled for 320x240 images
        Point pt2(values[2].toFloat()*2, values[3].toFloat()*2);
        Rect rect(pt1, pt2);
        float score = values[4].toFloat();        
        RectWithScore rctScore(rect, score);
        boundingBoxes.append(rctScore);

    }    

    //sort list by score (ascending)
    qSort(boundingBoxes);
    float maxScore = boundingBoxes.last().second;
    float threshold = maxScore * T_FACTOR;

    for (int i=boundingBoxes.count()-1; i>boundingBoxes.count()-1-drawBest && i>=0; i--)
    {
        if (boundingBoxes[i].second < threshold)
            continue;

        Rect dilated = dilateRectangle(boundingBoxes[i].first, DILATION);
        rectangle(img, dilated, 255);
    }
}
Пример #30
0
void VNote::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    if(newnote == false){
        if(getNotetype() == ScoreViewModel::whole || getNotetype() == ScoreViewModel::half || getNotetype() == ScoreViewModel::quarter || getNotetype() == ScoreViewModel::eighth){
           setCursor(Qt::OpenHandCursor);

           this->setPos(shadow->pos());

           //qDebug() << "After note pos" << this->pos();
           //qDebug() << "After note scenepos" << this->scenePos();

           if(this->parentItem() != 0){ // if not shadow, update scorepos

               QList <QGraphicsItem *> colList = this->scene()->collidingItems(shadow);
               VStaff *tempparent = (VStaff *)this->parentItem();

               VStaffLine *colStaffLine = (VStaffLine *)colList.last();

               if(staffpos != tempparent->getVstafflines().indexOf(colStaffLine)){
                   this->setScorepos(tempparent->getVstafflines().indexOf(colStaffLine));
                   accent = Accent::none;
                   emit this->vNotePosChanging(this);
               }

               this->scene()->update();
           }

           if(shadow != NULL){
               delete shadow;
               shadow = NULL;
           }

        }


        this->scene()->update();
        //qDebug() << this->pos();
    }

    QGraphicsItem::mouseReleaseEvent(event);
}