当前位置: 首页>>代码示例>>C++>>正文


C++ QVector::at方法代码示例

本文整理汇总了C++中QVector::at方法的典型用法代码示例。如果您正苦于以下问题:C++ QVector::at方法的具体用法?C++ QVector::at怎么用?C++ QVector::at使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QVector的用法示例。


在下文中一共展示了QVector::at方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: drawKillerSudokuCages

void PuzzlePrinter::drawKillerSudokuCages (const SKGraph* graph,
                                           const QVector<int> & edges)
{
    // Killer Sudokus have cages AND groups: so the cages are drawn differently.
    // We keep the outer wall of the cage on our left and draw a dashed line
    // just inside that boundary.  This reduces ugly criss-crossing of lines.
    //
    // Directions and related arrays are all in clockwise order.
    enum  Direction {East, South, West, North, nDirections};
    const Direction rightTurn [nDirections] = {South, West, North, East};
    const Direction leftTurn [nDirections]  = {North, East, South, West};
    const int       wallOnLeft [nDirections] =
			    {1 << Above, 1 << Right, 1 << Below, 1 << Left};
    const int       wallAhead [nDirections] =
			    {1 << Right, 1 << Below, 1 << Left, 1 << Above};

    const int       deltaX  [nDirections] = {+1, 0, -1, 0};
    const int       deltaY  [nDirections] = {0, +1, 0, -1};

    int   cellInc [nDirections] = {graph->order(), +1, -graph->order(), -1};
    int   offset    = (m_sCell + 6) / 12;
    int   longSide  = m_sCell;
    int   shortSide = m_sCell - offset - offset;

    m_p->setPen (m_dashes);

    for (int n = 0; n < graph->cageCount(); n++) {
	int topLeft = graph->cageTopLeft(n);
	int cell    = topLeft;
	int edge    = edges.at (cell);
	int startX  = m_topX + m_sCell * graph->cellPosX (cell) + offset;
	int startY  = m_topY + m_sCell * graph->cellPosY (cell) + offset;
	int dx      = 0;
	int dy      = 0;
	QLine line (startX, startY, startX, startY);
	Direction direction = East;

	// Keep drawing until we get back to the starting cell and direction.
	do {
	    // If there is a wall on the left, follow it.
	    if (edge & wallOnLeft [direction]) {
		if (edge & wallAhead [direction]) {
		    // Go to wall (shortSide), draw line, turn right, new line.
		    dx = deltaX [direction] * shortSide;
		    dy = deltaY [direction] * shortSide;
		    line.setLine (line.x1(), line.y1(),
				  line.x2() + dx, line.y2() + dy);
		    m_p->drawLine (line);
		    direction = rightTurn [direction];
		    line.setLine (line.x2(), line.y2(), line.x2(), line.y2());
		}
		else {
		    // Extend to start of next cell (longSide).
		    dx = deltaX [direction] * longSide;
		    dy = deltaY [direction] * longSide;
		    line.setLine (line.x1(), line.y1(),
				  line.x2() + dx, line.y2() + dy);
		    cell = cell + cellInc [direction];
		    edge = edges.at (cell);
		}
	    }
	    // Else, if there is no wall on the left ...
	    else {
		// Draw line, turn left, new line, go to start of next cell.
		m_p->drawLine (line);
		direction = leftTurn [direction];
		dx = deltaX [direction] * (longSide - shortSide);
		dy = deltaY [direction] * (longSide - shortSide);
		line.setLine (line.x2(), line.y2(),
			      line.x2() + dx, line.y2() + dy);
		cell = cell + cellInc [direction];
		edge = edges.at (cell);

	    }
	} while (! ((cell == topLeft) && (direction == East)));
    }	// Draw next cage.
}
开发者ID:KDE,项目名称:ksudoku,代码行数:77,代码来源:puzzleprinter.cpp

示例2: postTouchEvent

bool TouchExtensionGlobal::postTouchEvent(QTouchEvent *event, Surface *surface)
{
    const QList<QTouchEvent::TouchPoint> points = event->touchPoints();
    const int pointCount = points.count();
    if (!pointCount)
        return false;

    QPointF surfacePos = surface->pos();
    wl_client *surfaceClient = surface->resource()->client();
    uint32_t time = m_compositor->currentTimeMsecs();
    const int rescount = m_resources.count();

    for (int res = 0; res < rescount; ++res) {
        wl_resource *target = m_resources.at(res);
        if (target->client != surfaceClient)
            continue;

        // We will use no touch_frame type of event, to reduce the number of
        // events flowing through the wire. Instead, the number of points sent is
        // included in the touch point events.
        int sentPointCount = 0;
        for (int i = 0; i < pointCount; ++i) {
            if (points.at(i).state() != Qt::TouchPointStationary)
                ++sentPointCount;
        }

        for (int i = 0; i < pointCount; ++i) {
            const QTouchEvent::TouchPoint &tp(points.at(i));
            // Stationary points are never sent. They are cached on client side.
            if (tp.state() == Qt::TouchPointStationary)
                continue;

            uint32_t id = tp.id();
            uint32_t state = (tp.state() & 0xFFFF) | (sentPointCount << 16);
            uint32_t flags = (tp.flags() & 0xFFFF) | (int(event->device()->capabilities()) << 16);

            QPointF p = tp.pos() - surfacePos; // surface-relative
            int x = toFixed(p.x());
            int y = toFixed(p.y());
            int nx = toFixed(tp.normalizedPos().x());
            int ny = toFixed(tp.normalizedPos().y());
            int w = toFixed(tp.rect().width());
            int h = toFixed(tp.rect().height());
            int vx = toFixed(tp.velocity().x());
            int vy = toFixed(tp.velocity().y());
            uint32_t pressure = uint32_t(tp.pressure() * 255);

            wl_array *rawData = 0;
            QVector<QPointF> rawPosList = tp.rawScreenPositions();
            int rawPosCount = rawPosList.count();
            if (rawPosCount) {
                rawPosCount = qMin(maxRawPos, rawPosCount);
                rawData = &m_rawdata_array;
                rawData->size = rawPosCount * sizeof(float) * 2;
                float *p = m_rawdata_ptr;
                for (int rpi = 0; rpi < rawPosCount; ++rpi) {
                    const QPointF &rawPos(rawPosList.at(rpi));
                    // This will stay in screen coordinates for performance
                    // reasons, clients using this data will presumably know
                    // what they are doing.
                    *p++ = float(rawPos.x());
                    *p++ = float(rawPos.y());
                }
            }

            qt_touch_extension_send_touch(target,
                                          time, id, state,
                                          x, y, nx, ny, w, h,
                                          pressure, vx, vy,
                                          flags, rawData);
        }

        return true;
    }

    return false;
}
开发者ID:stskeeps,项目名称:qtwayland,代码行数:77,代码来源:qwltouch.cpp

示例3: main

int main(int argc, char **argv)
{
    //serializeUnserializeTest();
    srand(time(NULL));
    QGuiApplication app(argc, argv);
    
    QSurfaceFormat format;
    format.setSamples(16);
    
    paramCamera* c=new paramCamera();
    
    QTimer* calendar = new QTimer;

    //Add ressources
    PlyMeshReader plyReader;


    QString spring(":/springtree.ply");QString sp_name("SpringTree");
    QString summer(":/summertree.ply");QString su_name("SummerTree");
    QString autumn(":/autumntree.ply");QString au_name("AutumnTree");
    QString winter(":/wintertree.ply");QString wi_name("WinterTree");
    AssetManager::getInstance().loadMesh(sp_name,&plyReader,spring);
    AssetManager::getInstance().loadMesh(su_name,&plyReader,summer);
    AssetManager::getInstance().loadMesh(au_name,&plyReader,autumn);
    AssetManager::getInstance().loadMesh(wi_name,&plyReader,winter);

    QVector<GameWindow*> window;

    //if big file set content
    if(FileManager::getInstance().haveBigFile()) {
        qDebug() << "Saved GameWindow";
        window = FileManager::getInstance().load();
        qDebug() << "after load"<< window.size();
    }
    else {
        //Default four
        qDebug() << "Default GameWindow";
        for(int i = 0; i < 4; i++)
        {
            if (i == 0)
                window.append(new GameWindow());
            else
                window.append(new GameWindow(30));
            Terrain* terrain = new Terrain();
            terrain->loadHeightmap(":/heightmap-1.png");
            window.at(i)->setSeason(i);
            window.at(i)->setTerrain(terrain);
            window.at(i)->c = c;
        }

    }

    for(int i=0; i<window.size(); ++i) {
        qDebug() << "t-"<<i;
        FileManager::getInstance().link(window[i]);
        window[i]->setFormat(format);
        window[i]->resize(500,375);
        int x = i%2;
        int y = i>>1;

        window[i]->setPosition(x*500,y*450);
        window[i]->show();
        calendar->connect(calendar, SIGNAL(timeout()),window[i], SLOT(updateSeason()));
    }
    
    calendar->start(20);

    int appResult = app.exec();
    //AssetManager::getInstance().purge();
    return appResult;
}
开发者ID:TsubameDono,项目名称:tp7,代码行数:71,代码来源:main.cpp

示例4: loadData

void QmlProfilerEventsModelProxy::loadData(qint64 rangeStart, qint64 rangeEnd)
{
    clear();

    qint64 qmlTime = 0;
    qint64 lastEndTime = 0;
    QHash <int, QVector<qint64> > durations;

    const bool checkRanges = (rangeStart != -1) && (rangeEnd != -1);

    const QVector<QmlProfilerDataModel::QmlEventData> &eventList
            = d->modelManager->qmlModel()->getEvents();
    const QVector<QmlProfilerDataModel::QmlEventTypeData> &typesList
            = d->modelManager->qmlModel()->getEventTypes();

    // used by binding loop detection
    QStack<const QmlProfilerDataModel::QmlEventData*> callStack;
    callStack.push(0); // artificial root

    for (int i = 0; i < eventList.size(); ++i) {
        const QmlProfilerDataModel::QmlEventData *event = &eventList[i];
        const QmlProfilerDataModel::QmlEventTypeData *type = &typesList[event->typeIndex];

        if (!d->acceptedTypes.contains(type->rangeType))
            continue;

        if (checkRanges) {
            if ((event->startTime + event->duration < rangeStart)
                    || (event->startTime > rangeEnd))
                continue;
        }

        // update stats
        QmlEventStats *stats = &d->data[event->typeIndex];

        stats->duration += event->duration;
        if (event->duration < stats->minTime)
            stats->minTime = event->duration;
        if (event->duration > stats->maxTime)
            stats->maxTime = event->duration;
        stats->calls++;

        // for median computing
        durations[event->typeIndex].append(event->duration);

        // qml time computation
        if (event->startTime > lastEndTime) { // assume parent event if starts before last end
            qmlTime += event->duration;
            lastEndTime = event->startTime + event->duration;
        }


        //
        // binding loop detection
        //
        const QmlProfilerDataModel::QmlEventData *potentialParent = callStack.top();
        while (potentialParent
               && !(potentialParent->startTime + potentialParent->duration > event->startTime)) {
            callStack.pop();
            potentialParent = callStack.top();
        }

        // check whether event is already in stack
        for (int ii = 1; ii < callStack.size(); ++ii) {
            if (callStack.at(ii)->typeIndex == event->typeIndex) {
                d->eventsInBindingLoop.insert(event->typeIndex);
                break;
            }
        }

        callStack.push(event);

        d->modelManager->modelProxyCountUpdated(d->modelId, i, eventList.count()*2);
    }

    // post-process: calc mean time, median time, percentoftime
    int i = d->data.size();
    int total = i * 2;

    for (QHash<int, QmlEventStats>::iterator it = d->data.begin(); it != d->data.end(); ++it) {
        QmlEventStats* stats = &it.value();
        if (stats->calls > 0)
            stats->timePerCall = stats->duration / (double)stats->calls;

        QVector<qint64> eventDurations = durations[it.key()];
        if (!eventDurations.isEmpty()) {
            qSort(eventDurations);
            stats->medianTime = eventDurations.at(eventDurations.count()/2);
        }

        stats->percentOfTime = stats->duration * 100.0 / qmlTime;
        d->modelManager->modelProxyCountUpdated(d->modelId, i++, total);
    }

    // set binding loop flag
    foreach (int typeIndex, d->eventsInBindingLoop)
        d->data[typeIndex].isBindingLoop = true;

    // insert root event
    QmlEventStats rootEvent;
//.........这里部分代码省略.........
开发者ID:michaelc37,项目名称:qt-creator,代码行数:101,代码来源:qmlprofilereventsmodelproxy.cpp

示例5: calculateBpm

double BeatUtils::calculateBpm(const QVector<double>& beats, int SampleRate,
                               int min_bpm, int max_bpm) {
    /*
     * Let's compute the average local
     * BPM for N subsequent beats.
     * The average BPMs are
     * added to a list from which the statistical
     * median is computed
     *
     * N=12 seems to work great; We coincide with Traktor's
     * BPM value in many case but not worse than +-0.2 BPM
     */
    /*
     * Just to demonstrate how you would count the beats manually
     *
     *    Beat numbers:   1  2  3  4   5  6  7  8    9
     *    Beat positions: ?  ?  ?  ?  |?  ?  ?  ?  | ?
     *
     * Usually one measures the time of N beats. One stops the timer just before
     * the (N+1)th beat begins.  The BPM is then computed by 60*N/<time needed
     * to count N beats (in seconds)>
     *
     * Although beat tracking through QM is promising, the local average BPM of
     * 4 beats varies frequently by +-2 BPM.  Somtimes there N subsequent beats
     * in the grid that are computed wrongly by QM.
     *
     * Their local BPMs can be considered as outliers which would influence the
     * BPM computation negatively. To exclude outliers, we select the median BPM
     * over a window of N subsequent beats.

     * To do this, we take the average local BPM for every N subsequent
     * beats. We then sort the averages and take the middle to find the median
     * BPM.
     */

    if (beats.size() < 2) {
        return 0;
    }

    // If we don't have enough beats for our regular approach, just divide the #
    // of beats by the duration in minutes.
    if (beats.size() <= N) {
        return 60.0 * (beats.size()-1) * SampleRate / (beats.last() - beats.first());
    }

    QMap<double, int> frequency_table;
    QList<double> average_bpm_list = computeWindowedBpmsAndFrequencyHistogram(
        beats, N, 1, SampleRate, &frequency_table);

    // Get the median BPM.
    qSort(average_bpm_list);
    const double median = computeSampleMedian(average_bpm_list);

    /*
     * Okay, let's consider the median an estimation of the BPM To not soley
     * rely on the median, we build the average weighted value of all bpm values
     * being at most +-1 BPM from the median away.  Please note, this has
     * improved the BPM: While relying on median only we may have a deviation of
     * about +-0.2 BPM, taking into account BPM values around the median leads
     * to deviation of +- 0.05 Please also note that this value refers to
     * electronic music, but to be honest, the BPM detection of Traktor and Co
     * work best with electronic music, too. But BPM detection for
     * non-electronic music isn't too bad.
     */

    //qDebug() << "BPM range between " << min_bpm << " and " << max_bpm;

    // a subset of the 'frequency_table', where the bpm values are +-1 away from
    // the median average BPM.
    QMap<double, int> filtered_bpm_frequency_table;
    const double filterWeightedAverageBpm = computeFilteredWeightedAverage(
        frequency_table, median, kBpmFilterTolerance, &filtered_bpm_frequency_table);

    if (sDebug) {
        qDebug() << "Statistical median BPM: " << median;
        qDebug() << "Weighted Avg of BPM values +- 1BPM from the media"
                 << filterWeightedAverageBpm;
    }

    /*
     * Although we have a minimal deviation of about +- 0.05 BPM units compared
     * to Traktor, this deviation may cause the beat grid to look unaligned,
     * especially at the end of a track.  Let's try to get the BPM 'perfect' :-)
     *
     * Idea: Iterate over the original beat set where some detected beats may be
     * wrong. The beat is considered 'correct' if the beat position is within
     * epsilon of a beat grid obtained by the global BPM.
     *
     * If the beat turns out correct, we can compute the error in BPM units.
     * E.g., we can check the original beat position after 60 seconds. Ideally,
     * the approached beat is just a couple of samples away, i.e., not worse
     * than 0.05 BPM units.  The distance between these two samples can be used
     * for BPM error correction.
     */

     double perfect_bpm = 0;
     double firstCorrectBeatSample = beats.first();
     bool foundFirstCorrectBeat = false;

     int counter = 0;
//.........这里部分代码省略.........
开发者ID:Alppasa,项目名称:mixxx,代码行数:101,代码来源:beatutils.cpp

示例6: setValues

void GraphParamGlobal::setValues(QVector<double> val)
{
    for (int i = 0; i < qMin(this->nbPoints, val.size()); i++)
        dValues[i] = val.at(i);
}
开发者ID:UIKit0,项目名称:polyphone,代码行数:5,代码来源:dialog_paramglobal.cpp

示例7: calcCentr

void MainWindow::calcCentr()
{
    QVector<double> results;
    results = getResults(0,0);
    double max = 0.0;
    int tmp = 0;
//floy
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            FloydCentr.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }

    }
//dijk
    max = 0.0;
    tmp = 0;
    results = getResults(1,0);
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            DijkstraCentr.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }
    }
//rand
    max = 0.0;
    tmp = 0;
    results = getResults(2,0);
    qDebug() << "size" << results.size();
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            RandCentr.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }
    }

    //// TIME
    ///
    max = 0.0;
    tmp = 0;
    results = getResults(0,1);

    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            FloydCentrTime.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }

    }
    max = 0.0;
    tmp = 0;
    results = getResults(1,1);
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            DijkstraCentrTime.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }
    }

    max = 0.0;
    tmp = 0;
    results = getResults(2,1);
    for(int i = 0; i < results.size(); i++) {
        tmp++;
        max+=(double)results.at(i);
        if(tmp == SAMPLE_SIZE) {
            max /= SAMPLE_SIZE;
            RandCentrTime.push_back((double)max);
            max = 0.0;
            tmp = 0;
        }
    }
}
开发者ID:Vodogrey,项目名称:Diameter_of_a_graph,代码行数:93,代码来源:MainWindow.cpp

示例8: performSetLength

/*! \void XCLProcessor::performSetLength(XCLSyntaxExpression* expr, QVector<XCLProcessParameter> param,XCLParsingItem* item)
 *  \brief Sets the length of the XCLSyntaxExpression \a expr to the value given by the parameters of the method.
 *  \param expr A pointer to the XCLSyntaxExpression, the processing method will be performed on.
 *  \param param A list of parameters for this method.
 *  \param item A pointer to the parent XCLParsingItem.
 *  \exception XCLException 


**/
void XCLProcessor::performSetLength(XCLSyntaxExpression* expr, QVector<XCLProcessParameter> param,FileParserState& item)
{
    _UINT32 count=0;
    QString count2; // referenced or calculated value as QString

    BOOL isBigEndian;
    QString interpretation;
try
{
    //Value and DataType is given   
    if(param.size()==2)
    {
        XCLProcessParameter p1=param.at(0); //the value
        XCLProcessParameter p2=param.at(1); //the data type

        QString type = p2.getValue(item.index);

        //value has to be calculated
        if (p1.getValueType() == XCLProcessParameter::MATHEX)
        {
        
            XCLCalculator calc;
            count2 = calc.parseExpression(p1.getValue(), item.index);
           
        //    count=XCLStringConverter::string2Number<_UINT32>(count2,"uint64",expr->getIsBigEndian()); //something funny returns here ???
            count=count2.toInt();
        }
        else
        {   
            XCLInputNormalizer normalizer;
            isBigEndian = (item.index.get(p1.getValueReference()))->at(0)->getIsBigEndian();
            interpretation = (item.index.get(p1.getValueReference()))->at(0)->getInterpretation();

            if (isBigEndian)
            {
       

		QByteArray ba = p1.getValueAsBA(&item.index);

		count = (normalizer.normalizeValue((UCHAR*)ba.data(),ba.size(),interpretation, isBigEndian)->toInt());
                //count = p1.getValue(item.index).toLong();
            }
            else
            {
         

		QByteArray ba = p1.getValueAsBA(&item.index);

		count = (normalizer.normalizeValue((UCHAR*)ba.data(),ba.size(),interpretation, isBigEndian)->toInt());

            }            
        }

        _UINT8 typeLength = getTypeLength(type);
     

        expr->setLength(count*typeLength);
     

    }
    else if (param.size()==1)
    {
        XCLProcessParameter p=param.at(0);
        
        //value has to be calculated
        if (p.getValueType() == XCLProcessParameter::MATHEX)
        {
            XCLCalculator calc;
            count = calc.parseExpression(p.getValue(), item.index);
       
            expr->setLength(count);
        }
        else
        {
            _UINT32 num1=p.getValue(item.index).toLong();
      
            expr->setLength(num1); 
    
        }

    }
    else
    {
throw XCLException("Possible candidates for setLength are: setLength( length ) or setLength( count , type )\n");

    }
}
catch(XCLException exception)
{
exception.message();
throw XCLException("XCLProcessor couln´t execute setLength()\n");
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:

示例9: performSetName

void XCLProcessor::performSetName(XCLSyntaxExpression* expr, QVector<XCLProcessParameter> param,FileParserState& item)
{
  XCLProcessParameter p=param.at(0);

  expr->setName(p.getValue(item.index));
}
开发者ID:,项目名称:,代码行数:6,代码来源:

示例10: main

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
	QStringList args = a.arguments();
	if (args.size() < 3) {
		QStringList usage;
		usage << args.at(0)
			  << "[train data]"
			  << "[test data]";
		qFatal("Too few arguments. Usage:\n%s\n", usage.join(" ").toStdString().c_str());
	}

	QFile trainFile(args.at(1));
	if (!trainFile.open(QIODevice::ReadOnly)) {
		qFatal("Failed to open train file %s.\n", trainFile.fileName().toStdString().c_str());
	}
	QFile testFile(args.at(2));
	if (!testFile.open(QIODevice::ReadOnly)) {
		qFatal("Failed to open test file %s.\n", testFile.fileName().toStdString().c_str());
	}

    QElapsedTimer loadTimer;
    loadTimer.start();
    FeatureImporter trainFeatures;
    FeatureImporter testFeatures;
#pragma omp sections
    {
#pragma omp section
        {
            trainFeatures.open(&trainFile);
        }
#pragma omp section
        {
            testFeatures.open(&testFile);
        }
    }
    int loadMsecs = loadTimer.elapsed();
    qDebug() << "loading took" << loadMsecs << "msecs";

	trainFile.close();
	testFile.close();

	QVector<QString> hash;
    QVector<qint8> trainClasses;
	for (int i = 0; i < trainFeatures.labels().size(); i++) {
        qint8 index = hash.indexOf(trainFeatures.labels().at(i));
		if (index == -1) {
			QString dbg("Appending label \"%1\" to hash at position %2. It has now value \"%3\"");
			hash.append(trainFeatures.labels().at(i));
			index = hash.size() - 1;
			//qDebug() << dbg.arg(trainFeatures.labels().at(i), QString::number(index), hash.at(index));
		}
		trainClasses.append(index);
	}

    ClassifierInterface *ci = new CpuClassifier();
    QVector<QVector<int> > classes;
    qDebug() << "starting classification";
    QList<int> k;

    bool ok = true;
    int i = 50;
    if (args.size() >= 4) {
        i = qMax(0, args.at(3).toInt(&ok));
    } else {
        ok = false;
    }
    if (!ok) {
        qDebug() << "no k given, assuming k = 50";
        i = 50;
    }
    qDebug() << "initial k:" << i;
    for (; i >= 1; i--) {
        k.append(i);
    }
    QElapsedTimer timer;
    timer.start();
	classes = ci->classify(trainFeatures.features(), testFeatures.features(),
						   trainClasses.constData(), NULL,
						   testFeatures.featuresPerItem(),
						   trainFeatures.itemCount(), testFeatures.itemCount(),
                           k);
    delete ci;
	int msecs = timer.elapsed();
	qDebug() << "calculations took" << msecs << "msecs";
    for (int w = 0; w < classes.size(); w++) {
        int correct = 0;
        QVector<QVector<qreal> > confusionMatrix;
        confusionMatrix.resize(hash.size());
        for (int i = 0; i < confusionMatrix.size(); i++) {
            confusionMatrix[i].resize(hash.size());
        }
        for (int i = 0; i < classes.at(w).size(); i++) {
            /*qDebug() << i;
            qDebug() << classes.at(i);
            qDebug() << hash.at(classes.at(i));
            qDebug() << testFeatures.labels().at(i);*/
            confusionMatrix[hash.indexOf(testFeatures.labels().at(i))][classes.at(w).at(i)]++;
            /*if (hash.at(classes.at(w).at(i)) == QString("5")) {
                qDebug() << "is 5, should be " << testFeatures.labels().at(i);
//.........这里部分代码省略.........
开发者ID:janisozaur,项目名称:Rozpoznawanie-obraz-w,代码行数:101,代码来源:main.cpp

示例11: encode

KisImageBuilder_Result CSVSaver::encode(const QUrl &uri,const QString &filename)
{
    int idx;
    int start, end;
    KisNodeSP node;
    QByteArray ba;
    KisKeyframeSP keyframe;
    QVector<CSVLayerRecord*> layers;

    KisImageAnimationInterface *animation = m_image->animationInterface();

    //open the csv file for writing
    QFile f(uri.toLocalFile());
    if (!f.open(QIODevice::WriteOnly)) {
        return KisImageBuilder_RESULT_NOT_LOCAL;
    }

    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));

    //DataStream instead of TextStream for correct line endings
    QDataStream stream(&f);

    QString path = filename;

    if (path.right(4).toUpper() == ".CSV")
        path = path.left(path.size() - 4);

    path.append(".frames");

    //create directory

    QDir dir(path);
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    //according to the QT docs, the slash is a universal directory separator
    path.append("/");

    m_image->lock();
    node = m_image->rootLayer()->firstChild();

    //TODO: correct handling of the layer tree.
    //for now, only top level paint layers are saved

    idx = 0;

    while (node) {
        if (node->inherits("KisPaintLayer")) {
            KisPaintLayer* paintLayer = dynamic_cast<KisPaintLayer*>(node.data());
            CSVLayerRecord* layerRecord = new CSVLayerRecord();
            layers.prepend(layerRecord); //reverse order!

            layerRecord->name = paintLayer->name();
            layerRecord->name.replace(QRegExp("[\"\\r\\n]"), "_");

            if (layerRecord->name.isEmpty())
                layerRecord->name= QString("Unnamed-%1").arg(idx);

            layerRecord->visible = (paintLayer->visible()) ? 1 : 0;
            layerRecord->density = (float)(paintLayer->opacity()) / OPACITY_OPAQUE_U8;
            layerRecord->blending = convertToBlending(paintLayer->compositeOpId());
            layerRecord->layer = paintLayer;
            layerRecord->channel = paintLayer->projection()->keyframeChannel();
            layerRecord->last = "";
            layerRecord->frame = 0;
            idx++;
        }
        node = node->nextSibling();
    }

    KisTimeRange range = animation->fullClipRange();

    start = (range.isValid()) ? range.start() : 0;

    if (!range.isInfinite()) {
        end = range.end();

        if (end < start) end = start;
    } else {
        //undefined length, searching for the last keyframe
        end = start;

        for (idx = 0; idx < layers.size(); idx++) {
            keyframe = layers.at(idx)->channel->lastKeyframe();

            if ( (!keyframe.isNull()) && (keyframe->time() > end) )
                end = keyframe->time();
        }
    }

    //create temporary doc for exporting
    QScopedPointer<KisDocument> exportDoc(KisPart::instance()->createDocument());
    createTempImage(exportDoc.data());

    KisImageBuilder_Result retval= KisImageBuilder_RESULT_OK;

    if (!m_batchMode) {
        emit m_doc->statusBarMessage(i18n("Saving CSV file..."));
        emit m_doc->sigProgress(0);
        connect(m_doc, SIGNAL(sigProgressCanceled()), this, SLOT(cancel()));
//.........这里部分代码省略.........
开发者ID:mudithkr,项目名称:krita,代码行数:101,代码来源:csv_saver.cpp

示例12: drawHyper

void trakkermodel::drawHyper(float hyper_a, float hyper_c, int rotation ){


    double x1t,x2t,y1t,y2t, x1tm, x2tm, y1tm, y2tm ;

    int hyp1x =   0; // variables to translate proper hyperbolas
    int hyp1y = -29;
    float i;

    QVector<float> x;
    QVector<float> y1;
    QVector<float> y2;
    QVector<float> xShifted;

    sigDrawLine(10,-50,-29,50,-29,'k');  // triangle
    sigDrawLine(10,-50,-29,0 , 56,'k');
    sigDrawLine(10,  0, 56,50,-29,'k');

    sigDrawLine(10,  -2, 0,2,0,'k');
    sigDrawLine(10,  0, -2,0,2,'k');



    //calculation
    if ( hyper_a  > 0 ){
        for (i = 0 ; i < 200; i++){  // i and x are prescaled in meter so 'i' is iterated by 10cm
            x.append(i/10 + hyper_a);
            y1.append(   sqrt(   abs( (hyper_c*hyper_c - hyper_a*hyper_a )*(   (x.at(i)*x.at(i))/(hyper_a*hyper_a) -1 ) )    ));
            y2.append( - sqrt(   abs( (hyper_c*hyper_c - hyper_a*hyper_a )*(   (x.at(i)*x.at(i))/(hyper_a*hyper_a) -1 ) )    ));
        }
    }else{
        if (hyper_a  < 0 ){
            for (i = 0 ; i < 200; i = i++){
                x.append(-i/10 + hyper_a);
                y1.append(   sqrt(   abs( (hyper_c*hyper_c - hyper_a*hyper_a )*(  (x.at(i)*x.at(i))/(hyper_a*hyper_a) -1 ) )    ));
                y2.append( - sqrt(   abs( (hyper_c*hyper_c - hyper_a*hyper_a )*(  (x.at(i)*x.at(i))/(hyper_a*hyper_a) -1 ) )    ));
            }
        }else{  // hyper_a = 0;
            x.append(0);
            x.append(0);

            y1.append(0);
            y1.append(-500);
            y2.append(0);
            y2.append(500);


        }

    }

    for (i = 0 ; i < x.size() ; i++){
        xShifted.append( x.at(i) + 10*hyper_a );
    }



    //drawing
    switch (rotation){
    case 0:

            for (i = 0 ; i < xShifted.size() -1 ; i++){
                sigDrawLine(10 , -10*xShifted.at(i) +hyp1x ,10* y1.at(i) +hyp1y,- 10*xShifted.at(i+1)+hyp1x ,10*  y1.at(i+1)+hyp1y , 'b');
                sigDrawLine(10 , -10*xShifted.at(i) +hyp1x ,10* y2.at(i) +hyp1y,- 10*xShifted.at(i+1)+hyp1x ,10*  y2.at(i+1)+hyp1y , 'b');
            }
            break;

    case 120:
            x2t  = (10*xShifted.at(0)+hyp1x) * (-0.5) - (10*y1.at(0)+hyp1y)* 0.866 ;
            x2tm = x2t;
            y2t  = (10*xShifted.at(0)+hyp1x) * 0.866  + (10*y1.at(0)+hyp1y)*(-0.5) ;
            y2tm = y2t;

            for (i = 0 ; i < xShifted.size() -1 ; i++){
                x1t  = x2t;
                x1tm = x2tm;

                x2t  = (10*xShifted.at(i+1)+hyp1x) * (-0.5) - (10*y1.at(i+1)+hyp1y)* 0.866 ;
                x2tm = (10*xShifted.at(i+1)+hyp1x) * (-0.5) - (10*y2.at(i+1)+hyp1y)* 0.866 ;

                y1t  = y2t;
                y1tm = y2tm;

                y2t  = (10*xShifted.at(i+1)+hyp1x) * 0.866  + (10*y1.at(i+1)+hyp1y)*(-0.5) ;
                y2tm = (10*xShifted.at(i+1)+hyp1x) * 0.866  + (10*y2.at(i+1)+hyp1y)*(-0.5) ;
                sigDrawLine(10, x1t  ,y1t  ,x2t  ,y2t  , 'r');
                sigDrawLine(10, x1tm ,y1tm ,x2tm ,y2tm , 'r');
            }
            break;

    case 240:
            x2t  = (-10*xShifted.at(0)+hyp1x) * (-0.5) + (10*y1.at(0)+hyp1y)*0.866 ;
            x2tm = x2t;
            y2t  = (-10*xShifted.at(0)+hyp1x) *(-0.866)  + (10*y1.at(0)+hyp1y)*(-0.5) ;
            y2tm = y2t;

            for (i = 0 ; i < xShifted.size() -1 ; i++){
                x1t  = x2t;
                x1tm = x2tm;

//.........这里部分代码省略.........
开发者ID:zienek,项目名称:trakker,代码行数:101,代码来源:trakkermodel.cpp

示例13: exceptionVector

void tst_ExceptionSafety::exceptionVector() {

    {
        QVector<FlexibleThrowerSmall> vector;
        QVector<FlexibleThrowerSmall> vector2;
        QVector<FlexibleThrowerSmall> vector3;

        for (int i = 0; i<10; i++)
            vector.append( FlexibleThrowerSmall(i) );

        try {
            throwType = ThrowAtCopy;
            vector.append( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector.prepend( FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector.insert( 8, FlexibleThrowerSmall(10));
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.at(8).value(), 8 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector3 = vector;
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(0).value(), 0 );
        QCOMPARE( vector3.at(7).value(), 7 );
        QCOMPARE( vector3.size(), 10 );

        try {
            throwType = ThrowAtCopy;
            vector3.append( FlexibleThrowerSmall(11) );
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(0).value(), 0 );
        QCOMPARE( vector3.at(7).value(), 7 );

        try {
            vector2.clear();
            vector2.append( FlexibleThrowerSmall(11));
            throwType = ThrowAtCopy;
            vector3 = vector+vector2;
        } catch (...) {
        }
        QCOMPARE( vector.at(0).value(), 0 );
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        // check that copy on write works atomar
        vector2.clear();
        vector2.append( FlexibleThrowerSmall(11));
        vector3 = vector+vector2;
        try {
            throwType = ThrowAtCreate;
            vector3[7]=FlexibleThrowerSmall(12);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );
        QCOMPARE( vector3.at(7).value(), 7 );
        QCOMPARE( vector3.size(), 11 );

        try {
            throwType = ThrowAtCreate;
            vector.resize(15);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowAtCreate;
            vector.resize(15);
        } catch (...) {
        }
        QCOMPARE( vector.at(7).value(), 7 );
        QCOMPARE( vector.size(), 10 );

        try {
            throwType = ThrowLater;
//.........这里部分代码省略.........
开发者ID:Mr-Kumar-Abhishek,项目名称:qt,代码行数:101,代码来源:tst_exceptionsafety.cpp

示例14: drawAttrib

void PainterThread::drawAttrib(QPainter *p, Attributes *attrib)
{
    if (attrib->getType() == TObsAgent)
        return;

    //---- Desenha o atributo
    p->begin(attrib->getImage());

    p->setPen(Qt::NoPen); //defaultPen);

	//@RAIAN: Desenhando a vizinhanca
	if (attrib->getType() == TObsNeighborhood)
	{
		QColor color(Qt::white);
                QVector<QMap<QString, QList<double> > > *neighborhoods = attrib->getNeighValues();
		QVector<ObsLegend> *vecLegend = attrib->getLegend();

		QPen pen = p->pen();
		pen.setStyle(Qt::SolidLine);
		pen.setWidth(attrib->getWidth());

        // int random = qrand() % 256;
		double xCell = -1.0, yCell = -1.0;

		for (int pos = 0; pos < neighborhoods->size(); pos++)
		{
            QMap<QString, QList<double> > neigh = neighborhoods->at(pos);

			xCell = attrib->getXsValue()->at(pos);
			yCell = attrib->getYsValue()->at(pos);

			if ((xCell >= 0) && (yCell >=0))
			{
                QMap<QString, QList<double> >::Iterator itNeigh = neigh.begin();

				while (itNeigh != neigh.end())
				{
					QString neighID = itNeigh.key();
					QList<double> neighbor = itNeigh.value();

					double xNeigh = neighbor.at(0);
					double yNeigh = neighbor.at(1);
					double weight = neighbor.at(2);

					if (vecLegend->isEmpty())
					{
						weight = weight - attrib->getMinValue();
						double c = weight * attrib->getVal2Color();
						if (c >= 0 && c <= 255)
						{
							color.setRgb(c, c, c);
						}
						else
						{
							color.setRgb(255, 255, 255);
						}

						pen.setColor(color);
					}
					else
					{
						for (int j = 0; j < vecLegend->size(); j++)
						{
							ObsLegend leg = vecLegend->at(j);
							if (attrib->getGroupMode() == 3)
							{
								if (weight == leg.getTo().toDouble())
								{
									pen.setColor(leg.getColor());
									break;
								}
							}
							else
							{
								if ((leg.getFrom().toDouble() <= weight) && (weight < leg.getTo().toDouble()))
								{
									pen.setColor(leg.getColor());
									break;
								}
							}
						}
					}
					p->setPen(pen);

					if ((xNeigh >= 0) && (yNeigh >= 0))
					{
						drawNeighborhood(p, xCell, yCell, xNeigh, yNeigh);
					}

					itNeigh++;
				}
			}
		}
	}
	//@RAIAN: FIM
	else
	{
		if (attrib->getDataType() == TObsNumber)
		{
			QColor color(Qt::white);
//.........这里部分代码省略.........
开发者ID:avancinirodrigo,项目名称:terrame,代码行数:101,代码来源:painterThread.cpp

示例15: exec

bool QSQLiteResult::exec()
{
    const QVector<QVariant> values = boundValues();

    d->skippedStatus = false;
    d->skipRow = false;
    d->rInf.clear();
    clearValues();
    setLastError(QSqlError());

    int res = sqlite3_reset(d->stmt);
    if (res != SQLITE_OK) {
        setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                     "Unable to reset statement"), QSqlError::StatementError, res));
        d->finalize();
        return false;
    }
    int paramCount = sqlite3_bind_parameter_count(d->stmt);
    if (paramCount == values.count()) {
        for (int i = 0; i < paramCount; ++i) {
            res = SQLITE_OK;
            const QVariant value = values.at(i);

            if (value.isNull()) {
                res = sqlite3_bind_null(d->stmt, i + 1);
            } else {
                switch (value.type()) {
                case QVariant::ByteArray: {
                    const QByteArray *ba = static_cast<const QByteArray*>(value.constData());
                    res = sqlite3_bind_blob(d->stmt, i + 1, ba->constData(),
                                            ba->size(), SQLITE_STATIC);
                    break; }
                case QVariant::Int:
                    res = sqlite3_bind_int(d->stmt, i + 1, value.toInt());
                    break;
                case QVariant::Double:
                    res = sqlite3_bind_double(d->stmt, i + 1, value.toDouble());
                    break;
                case QVariant::UInt:
                case QVariant::LongLong:
                    res = sqlite3_bind_int64(d->stmt, i + 1, value.toLongLong());
                    break;
                case QVariant::String: {
                    // lifetime of string == lifetime of its qvariant
                    const QString *str = static_cast<const QString*>(value.constData());
                    res = sqlite3_bind_text16(d->stmt, i + 1, str->utf16(),
                                              (str->size()) * sizeof(QChar), SQLITE_STATIC);
                    break; }
                default: {
                    QString str = value.toString();
                    // SQLITE_TRANSIENT makes sure that sqlite buffers the data
                    res = sqlite3_bind_text16(d->stmt, i + 1, str.utf16(),
                                              (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
                    break; }
                }
            }
            if (res != SQLITE_OK) {
                setLastError(qMakeError(d->access, QCoreApplication::translate("QSQLiteResult",
                             "Unable to bind parameters"), QSqlError::StatementError, res));
                d->finalize();
                return false;
            }
        }
    } else {
        setLastError(QSqlError(QCoreApplication::translate("QSQLiteResult",
                        "Parameter count mismatch"), QString(), QSqlError::StatementError));
        return false;
    }
    d->skippedStatus = d->fetchNext(d->firstRow, 0, true);
    if (lastError().isValid()) {
        setSelect(false);
        setActive(false);
        return false;
    }
    setSelect(!d->rInf.isEmpty());
    setActive(true);
    return true;
}
开发者ID:,项目名称:,代码行数:78,代码来源:


注:本文中的QVector::at方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。