コード例 #1
0
ファイル: tsanalitics.cpp プロジェクト: Zaher220/Termospiro
void tsanalitics::approximate(){
    int i=0;
    QVector<int> vec;
    ts_extremums->remove(0,ts_extremums->size());
    ts_extremums->clear();
    ts_vol_exts->remove(0,ts_extremums->size());
    ts_vol_exts->clear();
    ts_exhls->remove(0,ts_exhls->size());
    ts_exhls->clear();
    if(ts_row_data->size()!=0){
        QVector<int> *df = new QVector<int>;
        for(i=0;i<ts_row_data->size()-1;i++){
            if ( abs(ts_row_data->at(i))>5){
                vec.push_back(i);
            }else{
                if(vec.size()>15){
                    vec.remove(0,vec.size());
                    vec.clear();
                }
            }
            df->push_back(ts_row_data->at(i+1)-ts_row_data->at(i));
        }
        for(i=0;i<ts_row_data->size();i++){
            extremum *extr = new extremum;
            extr->y = ts_row_data->at(i);
            extr->x = i;
            ts_vol_exts->push_back(*extr);
        }
        for(i=0;i<ts_vol_exts->size()-1;i++){
            if(ts_vol_exts->at(i).y!=0 && ts_vol_exts->at(i+1).y!=0){
                if(ts_vol_exts->at(i+1).y<ts_vol_exts->at(i).y){
                    ts_vol_exts->remove(i,1);
                    if (i>0)
                        i--;
                }else{
                    if(ts_vol_exts->size()<=i+1){
                        ts_vol_exts->remove(i+1,1);
                    }
                }
            }
        }
        for(i=0;i<ts_vol_exts->size();i++){//отсеиваем мелкие колебания
            if(ts_vol_exts->at(i).y!=0 && ts_vol_exts->at(i).y>-20){
                ts_vol_exts->remove(i,1);
            }
        }
        for(i=0;i<ts_vol_exts->size()-1;i++){//убираем двойные нули
            if(ts_vol_exts->at(i).y==0 && ts_vol_exts->at(i+1).y==0){
                ts_vol_exts->remove(i,1);
                if (i>0)
                    i--;
            }
        }
        //qDebug()<<ts_vol_exts->size()<<"size -+------";
        if(ts_vol_exts->size()>0){
            for(i=1;i<ts_vol_exts->size()-1;i++){
                if(ts_vol_exts->at(i).y!=0 && ts_vol_exts->at(i+1).y==0 && ts_vol_exts->at(i-1).y==0){
                    exhalation *ex = new exhalation;
                    ex->start=ts_vol_exts->at(i-1).x;
                    ex->end=ts_vol_exts->at(i).x;
                    ex->vol=ts_vol_exts->at(i).y;
                    ts_exhls->push_back(*ex);
                }
            }
        }
    }
}
コード例 #2
0
void QAlphaPaintEngine::flushAndInit(bool init)
{
    Q_D(QAlphaPaintEngine);
    Q_ASSERT(d->m_pass == 0);

    if (d->m_pic) {
        d->m_picpainter->end();

        // set clip region
        d->m_alphargn = d->m_alphargn.intersected(QRect(0, 0, d->m_pdev->width(), d->m_pdev->height()));

        // just use the bounding rect if it's a complex region..
        QVector<QRect> rects = d->m_alphargn.rects();
        if (rects.size() > 10) {
            QRect br = d->m_alphargn.boundingRect();
            d->m_alphargn = QRegion(br);
            rects.clear();
            rects.append(br);
        }

        d->m_cliprgn = d->m_alphargn;

        // now replay the QPicture
        ++d->m_pass; // we are now doing pass #2

        // reset states
        gccaps = d->m_savedcaps;

        painter()->save();
        d->resetState(painter());

        // make sure the output from QPicture is unscaled
        QTransform mtx;
        mtx.scale(1.0f / (qreal(d->m_pdev->logicalDpiX()) / qreal(qt_defaultDpiX())),
                  1.0f / (qreal(d->m_pdev->logicalDpiY()) / qreal(qt_defaultDpiY())));
        painter()->setTransform(mtx);
        painter()->drawPicture(0, 0, *d->m_pic);

        d->m_cliprgn = QRegion();
        d->resetState(painter());

        // fill in the alpha images
        for (int i=0; i<rects.size(); ++i)
            d->drawAlphaImage(rects.at(i));

        d->m_alphargn = QRegion();

        painter()->restore();

        --d->m_pass; // pass #2 finished

        cleanUp();
    }

    if (init) {
        gccaps = PaintEngineFeatures(AllFeatures & ~QPaintEngine::ObjectBoundingModeGradients);

        d->m_pic = new QPicture();
        d->m_pic->d_ptr->in_memory_only = true;
        d->m_picpainter = new QPainter(d->m_pic);
        d->m_picengine = d->m_picpainter->paintEngine();

        // When newPage() is called and the m_picpainter is recreated
        // we have to copy the current state of the original printer
        // painter back to the m_picpainter
        d->m_picpainter->setPen(painter()->pen());
        d->m_picpainter->setBrush(painter()->brush());
        d->m_picpainter->setBrushOrigin(painter()->brushOrigin());
        d->m_picpainter->setFont(painter()->font());
        d->m_picpainter->setOpacity(painter()->opacity());
        d->m_picpainter->setTransform(painter()->combinedTransform());
        d->m_picengine->syncState();
        QPainterState &state = *d->m_picpainter->d_func()->state;
        QPainter *oldPainter = state.painter;
        state = *painter()->d_func()->state;
        state.painter = oldPainter;
    }
}
コード例 #3
0
ファイル: qdrawutil.cpp プロジェクト: eaglezzb/wtlcontrols
void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
                      const QPalette &pal, bool sunken,
                      int lineWidth, const QBrush *fill)
{
    if (w == 0 || h == 0)
        return;
    if (!(w > 0 && h > 0 && lineWidth >= 0)) {
        qWarning("qDrawShadePanel: Invalid parameters");
    }
    QColor shade = pal.dark().color();
    QColor light = pal.light().color();
    if (fill) {
        if (fill->color() == shade)
            shade = pal.shadow().color();
        if (fill->color() == light)
            light = pal.midlight().color();
    }
    QPen oldPen = p->pen();                        // save pen
    QVector<QLineF> lines;
    lines.reserve(2*lineWidth);

    if (sunken)
        p->setPen(shade);
    else
        p->setPen(light);
    int x1, y1, x2, y2;
    int i;
    x1 = x;
    y1 = y2 = y;
    x2 = x+w-2;
    for (i=0; i<lineWidth; i++) {                // top shadow
        lines << QLineF(x1, y1++, x2--, y2++);
    }
    x2 = x1;
    y1 = y+h-2;
    for (i=0; i<lineWidth; i++) {                // left shado
        lines << QLineF(x1++, y1, x2++, y2--);
    }
    p->drawLines(lines);
    lines.clear();
    if (sunken)
        p->setPen(light);
    else
        p->setPen(shade);
    x1 = x;
    y1 = y2 = y+h-1;
    x2 = x+w-1;
    for (i=0; i<lineWidth; i++) {                // bottom shadow
        lines << QLineF(x1++, y1--, x2, y2--);
    }
    x1 = x2;
    y1 = y;
    y2 = y+h-lineWidth-1;
    for (i=0; i<lineWidth; i++) {                // right shadow
        lines << QLineF(x1--, y1++, x2--, y2);
    }
    p->drawLines(lines);
    if (fill)                                // fill with fill color
        p->fillRect(x+lineWidth, y+lineWidth, w-lineWidth*2, h-lineWidth*2, *fill);
    p->setPen(oldPen);                        // restore pen
}
コード例 #4
0
ファイル: window.cpp プロジェクト: assoc/vector
void Window::keyPressEvent(QKeyEvent* event){
    int key = event->key();
    int s = list.size();
    if (key == Qt::Key_H){
        QMessageBox::about(this,tr("Help"),tr(
            "VGedit :: rev.1\n\nKeys:\n[1] Select\n[2] Line\n"
            "[3] Polygon (doubleclick to finish)\n[4] Rhombus\n[5] Circle\n"
            "[6] Curved line (3 points)\n[F]ill toggle\n[C]lone selected objects\n[Del]ete selected objects\n"
            "[Esc] Stop drawing / remove selection\n[O]pen / [S]ave file\n"
            "[ArrowUP] Increase width\n[ArrowDOWN] Decrease width\n\nAlex Y & Max Ch"));
    }else if (key == Qt::Key_O){
        QString fileName = QFileDialog::getOpenFileName(this, tr("Open"), "", tr("VG file (*.vg)"));
        if (!fileName.isNull()){
            QFile file(fileName);
            if (file.open(QIODevice::ReadOnly)){
               QTextStream io(&file);
               list.clear();
               while (!io.atEnd()){
                  QString line = io.readLine();
                  QStringList core = line.split(";");
                  if (core.size() != 4){continue;}
                  item temp;
                  temp.shape = (Shape)core[0].toInt();
                  temp.selected = 0;
                  temp.width = core[1].toInt();
                  temp.fill = core[2].toInt();
                  QStringList points = core[3].split(" ");
                  for (int i = 0; i < points.size(); i++){
                      QStringList xy = points[i].split(",");
                      if (xy.size() == 2){
                          temp.ps.append(QPoint(xy[0].toInt(),xy[1].toInt()));
                      }
                  }
                  if (((temp.shape == Line || temp.shape == Poly || temp.shape == Diamond || temp.shape == Circle) && temp.ps.size() > 1) ||
                       (temp.shape == Curve && temp.ps.size() > 2)){list.append(temp);}
               }
               file.close();
               update();
            }else{QMessageBox::critical(this, tr("Error"), tr("Can't open this file"));}
        }
    }else if (key == Qt::Key_S){
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save"), "", tr("VG file (*.vg)"));
        if (!fileName.isNull()){
            QFile file(fileName);
            if (file.open(QIODevice::WriteOnly)){
               QTextStream io(&file);
               for (int i = 0; i < s; i++){
                   io << QString("%1;%2;%3;").arg(list[i].shape).arg(list[i].width).arg(list[i].fill);
                   int p = list[i].ps.size();
                   for (int j = 0; j < p; j++){
                       io << QString("%1,%2 ").arg(list[i].ps[j].x()).arg(list[i].ps[j].y());
                   }
                   io << QString("\n");
               }
               file.close();
               QMessageBox::information(this, tr("Save"), tr("File saved"));
            }else{QMessageBox::critical(this, tr("Error"), tr("Can't write this file"));}
        }
    }else if (key == Qt::Key_Escape){
        for (int i = 0; i < s; i++){list[i].selected = 0;}
        if (hasMouseTracking() && tool.shape != None){
            tool.ps.clear();
            setMouseTracking(false);
        }
        update();
    }else if (key == Qt::Key_Delete){
        for (int i = 0; i < s; i++){if (list[i].selected){list.remove(i); i--; s--;}}
        update();
    }else if (key == Qt::Key_C){
        for (int i = 0; i < s; i++){if (list[i].selected){list.append(list[i]); list[i].selected = 0;}}
        update();
    }else if (key == Qt::Key_Up && tool.width < 16){tool.width++;}
    else if (key == Qt::Key_Down && tool.width > 1){tool.width--;}
    else if (key == Qt::Key_F){tool.fill = !tool.fill;}
    else if (key == Qt::Key_1){tool.shape = None;}
    else if (key == Qt::Key_2){tool.shape = Line;}
    else if (key == Qt::Key_3){tool.shape = Poly;}
    else if (key == Qt::Key_4){tool.shape = Diamond;}
    else if (key == Qt::Key_5){tool.shape = Circle;}
    else if (key == Qt::Key_6){tool.shape = Curve;}
    if (key >= 0x31 && key <= 0x36){
        tool.ps.clear();
        update();
        setMouseTracking(false);
    }
    setNewTitle();
}
コード例 #5
0
    void Pager::paintEvent(QPaintEvent * event)
    {
        QFrame::paintEvent(event);

        if (d->images.size() == 0) { return; }

        // Maximum bounding box of a single page image
        QSize box = clampedBoundingBox();

        // In parametric equation of a circle, the offset from the centre is:
        //     x = a sin t
        // Spread determines how the index of page maps to the above t.

        double h = (double) box.height();
        double w = (double) box.width();
        double a = (width() - w - d->marginLeft - d->marginRight - (d->orientation == Qt::Vertical && d->scrollBar->isVisible() ? d->scrollBar->width() : 0)) / 2.0;
        double _1 = asin(w/a);
        double s = spread();
        double t1 = _1 + s * ((_PI / 2) - _1);

        int limitGrace = 5;
        //int upperLimit = (int) (d->guiIndex + _PI / (2.0 * t1)) + limitGrace + 1; // FIXME shuffle
        int upperLimit = (int) (d->guiIndex + width() / w + 1);
        //int lowerLimit = (int) (d->guiIndex - _PI / (2.0 * t1)) - limitGrace; // FIXME shuffle
        int lowerLimit = (int) (d->guiIndex - width() / w - 1);
        QPainter painter(this);
        painter.setClipRect(rect().adjusted(0, 1, -1, 0));
        painter.setRenderHint(QPainter::Antialiasing, true);
        painter.setRenderHint(QPainter::TextAntialiasing, true);
        painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
        QFont f(painter.font());
        f.setPixelSize(9);
        painter.setFont(f);
        painter.translate(width() / 2, 0);
        painter.translate(-box.width() / 2, 0);
        // FIXME shuffle
        double lower = a;
        double upper = (count() - 1) * w - lower;
        double clamp = qBound(lower, d->guiIndex * w, upper);
        painter.translate(-clamp, 0);
        // end FIXME shuffle
        painter.translate(0, d->marginTop);

        painter.setPen(Qt::NoPen);
        if (isActiveWindow())
        {
            painter.setPen(QApplication::palette().highlight().color());
            painter.setBrush(QApplication::palette().highlight());
        }
        else
        {
            int gray = qGray(QApplication::palette().highlight().color().rgb());
            painter.setPen(QColor(gray, gray, gray));
            painter.setBrush(QColor(gray, gray, gray));
        }

        double radius = 4.0;
        double transientWidth = 0.0;
        double transientHeight = 0.0;
        double transientLabelWidth = 0.0;
        double transientLabelBottom = 0.0;
        if (d->images.size() == 1)
        {
            QSize imageSize = d->images[0].size();
            imageSize.scale(box, Qt::KeepAspectRatio);
            transientWidth = imageSize.width();
            transientHeight = imageSize.height();
            if (d->drawLabels && !labelAt(0).isEmpty())
            {
                QRect labelRect(QPoint((box.width() - transientWidth) / 2.0, radius), QPoint(box.width() - (box.width() - transientWidth) / 2.0, 12 + radius));
                QString elidedLabel = painter.fontMetrics().elidedText(labelAt(0), Qt::ElideMiddle, labelRect.width());
                QRect bb(painter.fontMetrics().boundingRect(labelRect, Qt::AlignCenter, elidedLabel));
                transientLabelWidth = (double) bb.width();
                transientLabelBottom = (double) bb.bottom();
            }
        }
        else
        {
            int previousIndex = clampIndex((int) floor(d->guiIndex));
            int nextIndex = clampIndex((int) ceil(d->guiIndex));
            QSize previousSize = box;
            if (!d->images[previousIndex].isNull())
            {
                previousSize = d->images[previousIndex].size();
                previousSize.scale(box, Qt::KeepAspectRatio);
            }
            QSize nextSize = box;
            if (!d->images[nextIndex].isNull())
            {
                nextSize = d->images[nextIndex].size();
                nextSize.scale(box, Qt::KeepAspectRatio);
            }
            transientWidth = previousSize.width() + (nextSize.width() - previousSize.width()) * (d->guiIndex - previousIndex);
            transientHeight = previousSize.height() + (nextSize.height() - previousSize.height()) * (d->guiIndex - previousIndex);
            if (d->drawLabels && !labelAt(previousIndex).isEmpty() && !labelAt(nextIndex).isEmpty())
            {
                double previousLabelWidth = 0.0;
                double previousLabelBottom = 0.0;
                {
                    QRect labelRect(0, box.height() + radius, previousSize.width(), 12);
                    QString elidedLabel = painter.fontMetrics().elidedText(labelAt(previousIndex), Qt::ElideMiddle, labelRect.width());
                    QRect bb(painter.fontMetrics().boundingRect(labelRect, Qt::AlignCenter, elidedLabel));
                    previousLabelWidth = (double) bb.width();
                    previousLabelBottom = (double) bb.bottom();
                }
                double nextLabelWidth = 0.0;
                double nextLabelBottom = 0.0;
                {
                    QRect labelRect(0, box.height() + radius, nextSize.width(), 12);
                    QString elidedLabel = painter.fontMetrics().elidedText(labelAt(nextIndex), Qt::ElideMiddle, labelRect.width());
                    QRect bb(painter.fontMetrics().boundingRect(labelRect, Qt::AlignCenter, elidedLabel));
                    nextLabelWidth = (double) bb.width();
                    nextLabelBottom = (double) bb.bottom();
                }
                transientLabelWidth = previousLabelWidth + (nextLabelWidth - previousLabelWidth) * (d->guiIndex - previousIndex);
                transientLabelBottom = previousLabelBottom + (nextLabelBottom - previousLabelBottom) * (d->guiIndex - previousIndex);
            }
        }
        painter.drawRoundedRect(QRectF(d->guiIndex * w + (box.width() - transientWidth) / 2.0 - radius, box.height() - transientHeight - radius, transientWidth + radius * 2, transientHeight + radius * 2), radius, radius);
        if (d->drawLabels && transientLabelWidth > 0.0 && transientLabelBottom > 0.0)
        {
            painter.drawRoundedRect(QRectF(d->guiIndex * w + (box.width() - transientLabelWidth) / 2.0 - radius, box.height(), transientLabelWidth + radius * 2, transientLabelBottom - box.height() + radius / 2.0), radius, radius);
        }

        painter.setPen(Qt::NoPen);
        QPen pen(QColor(115, 115, 115));
        pen.setJoinStyle(Qt::MiterJoin);
        pen.setWidthF(0.5);
        painter.setPen(pen);
        painter.setBrush(Qt::NoBrush);

        static QVector< double > sin_ts; // FIXME Make a member, not a static variable
        sin_ts.resize(count());

        // Iterate through pages
        double offset = 0.0;
        for (int i = (int) ceil(d->guiIndex); i < count(); ++i)
        {
            if (i < lowerLimit || i > upperLimit) continue;

            double preModifier = d->indexPreModifiers.value(i, 0.0);
            double postModifier = d->indexPostModifiers.value(i, 0.0);
            offset += preModifier;
            if (preModifier >= 0.0)
            {
                double t = (i - (d->guiIndex - offset)) * t1;
                t = qBound(-_PI/2.0, t, _PI/2);
                sin_ts[i] = sin(t);
            }
            else
            {
                sin_ts[i] = 10.0;
            }
            offset += postModifier;
        }

        offset = 0.0;
        for (int i = (int) ceil(d->guiIndex) - 1; i >= 0; --i)
        {
            if (i < lowerLimit || i > upperLimit) continue;

            double preModifier = d->indexPreModifiers.value(i, 0.0);
            double postModifier = d->indexPostModifiers.value(i, 0.0);
            offset += postModifier;
            if (preModifier >= 0.0)
            {
                double t = (i - (d->guiIndex + offset)) * t1;
                t = qBound(-_PI/2.0, t, _PI/2);
                sin_ts[i] = sin(t);
            }
            else
            {
                sin_ts[i] = 10.0;
            }
            offset += preModifier;
        }

        for (int i = 0; i < d->guiIndex; ++i)
        {
            if (i < lowerLimit || i > upperLimit) continue;
            double sin_t = sin_ts.at(i);
            if (sin_t > 1.0) continue;

            double opacity = 1.0;
            if (d->transitionTimes.contains(i) && !d->transitionTimes[i].isNull())
            {
                opacity *= d->transitionTimes[i].elapsed() / 500.0;
            }
            if (i < lowerLimit + limitGrace)
            {
                // opacity *= (i - lowerLimit) / (double) limitGrace; // FIXME shuffle
            }
            painter.setOpacity(opacity);
            QPixmap image = d->images[i].isNull() ? QPixmap(":/images/pager_loading.png") : d->images[i];
            QSize size = image.size();
            size.scale(box, Qt::KeepAspectRatio);
            //double x = sin_t * (a + (w - size.width()) / 2.0) + (w - size.width()) / 2.0; // FIXME shuffle
            double x = w * i + (w - size.width()) / 2.0;
            double y = h - size.height();
            QRect rect((int) x, (int) y, size.width(), size.height());
            painter.drawPixmap(rect, image);
            painter.drawRect(rect);

            if (d->drawLabels)
            {
                QString label = labelAt(i);
                if (!label.isEmpty())
                {
                    QRect labelRect(rect.bottomLeft() + QPoint(0, radius), rect.bottomRight() + QPoint(0, 12 + radius));
                    QString elidedLabel = painter.fontMetrics().elidedText(label, Qt::ElideMiddle, rect.width());

                    painter.save();
                    painter.setPen(QColor(0, 0, 0));

                    QFontMetrics fm(painter.font());

                    QSize numSize = fm.boundingRect(elidedLabel).size();
                    double lozengeRadius = 1 + numSize.height() / 2.0;
                    numSize += QSize(numSize.height(), 0);
                    QRect numRect(0, 0, numSize.width() + 2, numSize.height() + 2);

                    numRect.moveCenter(rect.center());
                    numRect.moveBottom(rect.bottom() + radius + 1);

                    painter.setBrush(Qt::yellow);
                    painter.setPen(QColor(140, 140, 0));
                    painter.drawRoundedRect(numRect, lozengeRadius, lozengeRadius);

                    painter.setPen(Qt::black);
                    painter.drawText(numRect, Qt::AlignCenter, elidedLabel);

                    painter.restore();

                }
            }

            if (d->hasAnnotation.value(i, 0) > 0)
            {
                drawAnnotationTag(&painter, rect);
            }

            if (!d->spotlightsHidden && !d->searchHits.isEmpty())
            {
                drawSearchHits(&painter, d->searchHits.value(i, 0), rect);
            }

            painter.setOpacity(1.0);
        }

        for (int i = count() - 1; i >= d->guiIndex; --i)
        {
            if (i < lowerLimit || i > upperLimit) continue;
            double sin_t = sin_ts.at(i);
            if (sin_t > 1.0) continue;

            double opacity = 1.0;
            if (d->transitionTimes.contains(i) && !d->transitionTimes[i].isNull())
            {
                opacity *= d->transitionTimes[i].elapsed() / 500.0;
            }
            if (i > upperLimit - limitGrace)
            {
                // opacity *= (limitGrace + i - upperLimit) / (double) limitGrace; // FIXME shuffle
            }
            painter.setOpacity(opacity);
            QPixmap image = d->images[i].isNull() ? QPixmap(":/images/pager_loading.png") : d->images[i];
            QSize size = image.size();
            size.scale(box, Qt::KeepAspectRatio);
            //double x = sin_t * (a + (w - size.width()) / 2.0) + (w - size.width()) / 2.0; // FIXME shuffle
            double x = w * i + (w - size.width()) / 2.0;
            double y = h - size.height();
            QRect rect((int) x, (int) y, size.width(), size.height());
            painter.drawPixmap(rect, image);
            painter.drawRect(rect);

            if (d->drawLabels)
            {
                QString label = labelAt(i);
                if (!label.isEmpty())
                {
                    QRect labelRect(rect.bottomLeft() + QPoint(0, radius), rect.bottomRight() + QPoint(0, 12 + radius));
                    QString elidedLabel = painter.fontMetrics().elidedText(label, Qt::ElideMiddle, labelRect.width());
                    painter.save();
                    painter.setPen(QColor(200, 200, 200));
                    painter.setPen(QColor(0, 0, 0));
                    painter.drawText(labelRect, Qt::AlignCenter, elidedLabel);
                    painter.restore();
                }
            }

            if (d->hasAnnotation.value(i, 0) > 0)
            {
                drawAnnotationTag(&painter, rect);
            }

            if (!d->spotlightsHidden && !d->searchHits.isEmpty())
            {
                drawSearchHits(&painter, d->searchHits.value(i, 0), rect);
            }

            painter.setOpacity(1.0);
        }

        sin_ts.clear();
    }
コード例 #6
0
ファイル: ct08.cpp プロジェクト: mtab3/qct08
void CT08::QGetData( int ch, int num, QVector<double> &data )
{
  int cnt = 0;
  data.clear();

  //  QString cmd = QString( "GSCRDX?%1%2%3%4%5" )
  int Num = num;
  if ( num > 9999 ) {
    Num = ceil( ((double)Num) / 1000. );
  } else {
    Num -= 1;     // データ個数は Num 個、なので読み出し番地指定は 0〜Num-1
  }
    
  QString cmd = QString( "GSCRDXH?%1%2%3%4%5" )
    .arg( ch,     2, 10, QChar( '0' ) )     // 指定チャンネル (ch) から
    .arg( ch,     2, 10, QChar( '0' ) )     // 指定チャンネル (ch) までの、要は ch だけの
    .arg( (int)1, 2, 10, QChar( '0' ) )     // タイマーも読み出して(0:w/o, 1:w timer)
    .arg( (int)0, 4, 10, QChar( '0' ) )     // 0 番目から
    .arg( Num,    4, 10, QChar( '0' ) );    // num 番目までのデータを読みだす
  if ( num > 9999 )
    cmd += "K";
  SendACmd( cmd );

  bool Finished = false;
  QTime eTime;
  eTime.start();  // measure total time to elapsed in the following loop 
  while(( cnt < num )&&( !Finished )) {
    qDebug() << "waitForReadyRead" << ss->bytesAvailable() << cnt << num;
    // ここでデータがなるべく多く受信バッファに溜るのを待つ。
    int oldLen = 0, newLen;
    if ( ! ss->waitForReadyRead( 50 ) ) {
      if ( eTime.elapsed() > 1000 )
	Finished = true;
    }
    while( ( newLen = ss->bytesAvailable() ) != oldLen ) {
      oldLen = newLen;
      ss->waitForReadyRead( 50 );
    }
    
    double time0 = 0;
    double time = 0;
    qDebug() << "in QGetData : num = " << num;
    while( ! ss->atEnd() ) {
      QString Rbuf = ss->readLine().simplified();
      if ( Rbuf == "EOF" ) {
	Finished = true;
	qDebug() << "normally break by EOF";
	break;
      }
      QStringList vals = Rbuf.remove( ' ' ).split( ',' );
      if ( vals.count() == 2 ) {
	time = (double)vals[1].toInt( NULL, 16 ) / 1e6;
	if ( cnt < num ) {   // The number of data is 'num'
	  if ( time != time0 ) {
	    data << (double)vals[0].toInt( NULL, 16 ) / ( time - time0 );
	    time0 = time;
	  }
	}
	cnt++;
      }
    }
    qDebug() << "in QGetData : data.count() = " << data.count();
  }
  qDebug() << "-----------------------";
}
コード例 #7
0
ファイル: qgsgeometrygapcheck.cpp プロジェクト: dwsilk/QGIS
void QgsGeometryGapCheck::collectErrors( const QMap<QString, QgsFeaturePool *> &featurePools, QList<QgsGeometryCheckError *> &errors, QStringList &messages, QgsFeedback *feedback, const LayerFeatureIds &ids ) const
{
  if ( feedback )
    feedback->setProgress( feedback->progress() + 1.0 );

  QVector<QgsGeometry> geomList;


  QMap<QString, QgsFeatureIds> featureIds = ids.isEmpty() ? allLayerFeatureIds( featurePools ) : ids.toMap();
  const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds, compatibleGeometryTypes(), nullptr, mContext, true );
  for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
  {
    geomList.append( layerFeature.geometry() );

    if ( feedback && feedback->isCanceled() )
    {
      geomList.clear();
      break;
    }
  }

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

  std::unique_ptr< QgsGeometryEngine > geomEngine = QgsGeometryCheckerUtils::createGeomEngine( nullptr, mContext->tolerance );
  geomEngine->prepareGeometry();

  // Create union of geometry
  QString errMsg;
  std::unique_ptr<QgsAbstractGeometry> unionGeom( geomEngine->combine( geomList, &errMsg ) );
  if ( !unionGeom )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // Get envelope of union
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( unionGeom.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  std::unique_ptr<QgsAbstractGeometry> envelope( geomEngine->envelope( &errMsg ) );
  if ( !envelope )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // Buffer envelope
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( envelope.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  QgsAbstractGeometry *bufEnvelope = geomEngine->buffer( 2, 0, GEOSBUF_CAP_SQUARE, GEOSBUF_JOIN_MITRE, 4. );  //#spellok  //#spellok
  envelope.reset( bufEnvelope );

  // Compute difference between envelope and union to obtain gap polygons
  geomEngine = QgsGeometryCheckerUtils::createGeomEngine( envelope.get(), mContext->tolerance );
  geomEngine->prepareGeometry();
  std::unique_ptr<QgsAbstractGeometry> diffGeom( geomEngine->difference( unionGeom.get(), &errMsg ) );
  if ( !diffGeom )
  {
    messages.append( tr( "Gap check: %1" ).arg( errMsg ) );
    return;
  }

  // For each gap polygon which does not lie on the boundary, get neighboring polygons and add error
  for ( int iPart = 0, nParts = diffGeom->partCount(); iPart < nParts; ++iPart )
  {
    std::unique_ptr<QgsAbstractGeometry> gapGeom( QgsGeometryCheckerUtils::getGeomPart( diffGeom.get(), iPart )->clone() );
    // Skip the gap between features and boundingbox
    const double spacing = context()->tolerance;
    if ( gapGeom->boundingBox().snappedToGrid( spacing ) == envelope->boundingBox().snappedToGrid( spacing ) )
    {
      continue;
    }

    // Skip gaps above threshold
    if ( ( mGapThresholdMapUnits > 0 && gapGeom->area() > mGapThresholdMapUnits ) || gapGeom->area() < mContext->reducedTolerance )
    {
      continue;
    }

    QgsRectangle gapAreaBBox = gapGeom->boundingBox();

    // Get neighboring polygons
    QMap<QString, QgsFeatureIds> neighboringIds;
    const QgsGeometryCheckerUtils::LayerFeatures layerFeatures( featurePools, featureIds.keys(), gapAreaBBox, compatibleGeometryTypes(), mContext );
    for ( const QgsGeometryCheckerUtils::LayerFeature &layerFeature : layerFeatures )
    {
      const QgsGeometry geom = layerFeature.geometry();
      if ( QgsGeometryCheckerUtils::sharedEdgeLength( gapGeom.get(), geom.constGet(), mContext->reducedTolerance ) > 0 )
      {
        neighboringIds[layerFeature.layer()->id()].insert( layerFeature.feature().id() );
        gapAreaBBox.combineExtentWith( layerFeature.geometry().boundingBox() );
      }
    }

    if ( neighboringIds.isEmpty() )
    {
      continue;
    }

    // Add error
    double area = gapGeom->area();
    errors.append( new QgsGeometryGapCheckError( this, QString(), QgsGeometry( gapGeom.release() ), neighboringIds, area, gapAreaBBox ) );
  }
}
コード例 #8
0
ファイル: qjdmainwindow.cpp プロジェクト: xtfllbl/Flow2
/// TODO:名称和路径需要联系起来
// 不能使用QHash ,会出现string相同的情况,那用什么方法呢
// QMultiMap??
void QJDMainWindow::setHomeDir(QString homePath)
{
    areaWidget->clear();

    /// 第一层 -- 工区
    QDir dir1;

    // 这个需要能设置,程序需要有settings.ini
    dir1.setPath(homePath);
    QStringList dirLev1;
    dirLev1<<dir1.entryList(QDir::NoDotAndDotDot|QDir::Dirs);
    //    qDebug()<<dir1.count(); // 包含./..

    /// 第二层 -- 线, 目前要向里面加入data文件夹,data文件夹与flow并列并且继续有往下的选择,可以不用descname
    QStringList areaStringList;
    QStringList areaPathList;
    QStringList lineStringList;
    QStringList linePathList;

    QVector<QStringList> flowStringList;
    QVector<QStringList> flowPathList;

    QVector<QVector<QStringList> > dataStringList;
    QVector<QVector<QStringList> >  dataPathList;
    for(int i=0; i<dirLev1.count(); i++)
    {
        // 遍历
        QDir dir2;
        QString dir2path=dir1.path()+"/"+dirLev1.at(i);
        dir2.setPath(dir2path);
        QStringList dirLev2;
        dirLev2=dir2.entryList(QDir::NoDotAndDotDot|QDir::Dirs);

        // 解析 DescName -- 工区名称
        QFile file2;
        file2.setFileName(dir2path+"/DescName");
        if(!file2.exists())
        {
            continue;
        }
        areaPathList<<dir2path;

        file2.open(QFile::ReadOnly);
        QTextStream stream2(&file2);
        QString areatmp=stream2.readAll();
        areatmp.chop(1);
        areaStringList<<areatmp;   // 路径就是dir2path
        //        qDebug()<<dir2path;
        file2.close();

        /// 第三层 -- 流程/Data, 同一层的data文件夹需要特殊处理
        for(int j=0; j<dirLev2.count(); j++)
        {
            QDir dir3;
            QString dir3path=dir2.path()+"/"+dirLev2.at(j);
            dir3.setPath(dir3path);
            QStringList dirLev3;
            dirLev3=dir3.entryList(QDir::NoDotAndDotDot|QDir::Dirs);  // 线名

            // 解析 DescName -- 线名称
            QFile file3;
            file3.setFileName(dir3path+"/DescName");
            if(!file3.exists())
            {
                continue;
            }
            linePathList<<dir3path;
            file3.open(QFile::ReadOnly);
            QTextStream stream3(&file3);
            QString linetmp=stream3.readAll();
            linetmp.chop(1);
            lineStringList<<linetmp;
            file3.close();
            //            qDebug()<<"line::"<<lineStringList;

            /// 第四层 -- 具体流程
            flowStringList.resize(dirLev2.count());
            flowPathList.resize(dirLev2.count());
            dataStringList.resize(dirLev2.count());
            dataPathList.resize(dirLev2.count());
            for(int k=0; k<dirLev3.count(); k++)
            {
                // 应当没有文件夹了,只剩下文件了
                QDir dir4;
                QString dir4path=dir3.path()+"/"+dirLev3.at(k);
                dir4.setPath(dir4path);
                QStringList dirLev4;
                dirLev4=dir4.entryList(QDir::NoDotAndDotDot|QDir::Files);  // 文件名列表了
                flowPathList[j]<<dir4path;
                /// 底下应当有个记录流程xml文件

                // 解析 DescName -- 线名称
                QFile file4;
                file4.setFileName(dir4path+"/DescName");
                if(!file4.exists())
                {
                    continue;
                }
                file4.open(QFile::ReadOnly);
                QTextStream stream4(&file4);
                QString flowtmp=stream4.readAll();
                flowtmp.chop(1);
                flowStringList[j]<<flowtmp;  // 只有在流程里才会有,其他的文件夹内不会有这个
                file4.close();
                //                qDebug()<<"flow::"<<flowStringList;

                /// 第五层 -- 数据存放,不应当再像前面一样完全扫描了.需要列出文件类型目录即可
                //! !! 如何准确放到某条线下面去,每条线都有,目前还是没有解决这个问题
                // 也就是说需要二维数组来确定
                if(flowtmp=="Data")
                {
                    dataStringList[j].resize(dirLev3.count());
                    dataPathList[j].resize(dirLev3.count());
                    for(int l=0; l<dirLev4.count(); l++)
                    {
                        // 应当没有文件夹了,只剩下文件了
                        QDir dir5;
                        dir5.setPath(dir4.path());
                        QStringList dirLev5;
                        dirLev5=dir5.entryList(QDir::NoDotAndDotDot|QDir::AllDirs);  // 文件名列表了
                        //                        qDebug()<<dir4.path()<<"dirLev5::"<<dirLev5;  // 怎么是空的??
                        dataStringList[j][k].append(dirLev5);
                        /// 底下应当有个记录流程xml文件

                        for(int m=0; m<dirLev5.size(); m++)
                        {
                            QString dataPath=dir4.path()+"/"+dirLev5.at(m);
                            dataPathList[j][k].append(dataPath);
                        }
                    }
                    // dataString为空 path为data descName的path
                    //                    qDebug()<<"!!!!!!!!!!!!!!!!!!!!!!!!!!"<<dirLev4.count()<<dataStringList;
                }
            }
        }
        //        qDebug()<<"\nstart set:::"<<areaStringList.at(i)<<lineStringList<<flowStringList;
        //        qDebug()<<"Data:::"<<dataStringList;

        setAreaWidget(areaStringList.at(i),areaPathList.at(i),lineStringList,
                      linePathList,flowStringList,flowPathList,dataStringList,dataPathList);

        /// 清理
        flowStringList.clear();
        flowPathList.clear();
        lineStringList.clear();
        linePathList.clear();
        dataStringList.clear();
        dataPathList.clear();
    }

    if(!areaStringList.isEmpty())
    {
        //        qDebug()<<areaWidget->topLevelItem(0)->text(0);
        areaWidget->setCurrentItem(areaWidget->topLevelItem(0));
        areaWidget->returnPath(areaWidget->currentItem(),areaWidget->currentColumn());
    }
}
コード例 #9
0
ファイル: sqlitedriver.cpp プロジェクト: Nikoli/quite-rss
bool SQLiteResultPrivate::fetchNext(SqlCachedResult::ValueCache &values, int idx, bool initialFetch)
{
    int res;
    int i;

    if (skipRow) {
        // already fetched
        Q_ASSERT(!initialFetch);
        skipRow = false;
        for(int i=0;i<firstRow.count();i++)
            values[i]=firstRow[i];
        return skippedStatus;
    }
    skipRow = initialFetch;

    if(initialFetch) {
        firstRow.clear();
        firstRow.resize(sqlite3_column_count(stmt));
    }

    if (!stmt) {
        q->setLastError(QSqlError(QCoreApplication::translate("SQLiteResult", "Unable to fetch row"),
                                  QCoreApplication::translate("SQLiteResult", "No query"), QSqlError::ConnectionError));
        q->setAt(QSql::AfterLastRow);
        return false;
    }
    res = sqlite3_step(stmt);

    switch(res) {
    case SQLITE_ROW:
        // check to see if should fill out columns
        if (rInf.isEmpty())
            // must be first call.
            initColumns(false);
        if (idx < 0 && !initialFetch)
            return true;
        for (i = 0; i < rInf.count(); ++i) {
            switch (sqlite3_column_type(stmt, i)) {
            case SQLITE_BLOB:
                values[i + idx] = QByteArray(static_cast<const char *>(
                            sqlite3_column_blob(stmt, i)),
                            sqlite3_column_bytes(stmt, i));
                break;
            case SQLITE_INTEGER:
                values[i + idx] = sqlite3_column_int64(stmt, i);
                break;
            case SQLITE_FLOAT:
                switch(q->numericalPrecisionPolicy()) {
                    case QSql::LowPrecisionInt32:
                        values[i + idx] = sqlite3_column_int(stmt, i);
                        break;
                    case QSql::LowPrecisionInt64:
                        values[i + idx] = sqlite3_column_int64(stmt, i);
                        break;
                    case QSql::LowPrecisionDouble:
                    case QSql::HighPrecision:
                    default:
                        values[i + idx] = sqlite3_column_double(stmt, i);
                        break;
                };
                break;
            case SQLITE_NULL:
                values[i + idx] = QVariant(QVariant::String);
                break;
            default:
                values[i + idx] = QString(reinterpret_cast<const QChar *>(
                            sqlite3_column_text16(stmt, i)),
                            sqlite3_column_bytes16(stmt, i) / sizeof(QChar));
                break;
            }
        }
        return true;
    case SQLITE_DONE:
        if (rInf.isEmpty())
            // must be first call.
            initColumns(true);
        q->setAt(QSql::AfterLastRow);
        sqlite3_reset(stmt);
        return false;
    case SQLITE_CONSTRAINT:
    case SQLITE_ERROR:
        // SQLITE_ERROR is a generic error code and we must call sqlite3_reset()
        // to get the specific error message.
        res = sqlite3_reset(stmt);
        q->setLastError(qMakeError(access, QCoreApplication::translate("SQLiteResult",
                        "Unable to fetch row"), QSqlError::ConnectionError, res));
        q->setAt(QSql::AfterLastRow);
        return false;
    case SQLITE_MISUSE:
    case SQLITE_BUSY:
    default:
        // something wrong, don't get col info, but still return false
        q->setLastError(qMakeError(access, QCoreApplication::translate("SQLiteResult",
                        "Unable to fetch row"), QSqlError::ConnectionError, res));
        sqlite3_reset(stmt);
        q->setAt(QSql::AfterLastRow);
        return false;
    }
    return false;
}
コード例 #10
0
ファイル: traceloader.cpp プロジェクト: is00hcw/apitrace
void TraceLoader::parseTrace()
{
    QList<ApiTraceFrame*> frames;
    ApiTraceFrame *currentFrame = 0;
    int frameCount = 0;
    QStack<ApiTraceCall*> groups;
    QVector<ApiTraceCall*> topLevelItems;
    QVector<ApiTraceCall*> allCalls;
    quint64 binaryDataSize = 0;

    int lastPercentReport = 0;

    trace::Call *call = m_parser.parse_call();
    while (call) {
        //std::cout << *call;
        if (!currentFrame) {
            currentFrame = new ApiTraceFrame();
            currentFrame->number = frameCount;
            ++frameCount;
        }
        ApiTraceCall *apiCall =
            apiCallFromTraceCall(call, m_helpHash, currentFrame, groups.isEmpty() ? 0 : groups.top(), this);
        allCalls.append(apiCall);
        if (groups.count() == 0) {
            topLevelItems.append(apiCall);
        }
        if (call->flags & trace::CALL_FLAG_MARKER_PUSH) {
            groups.push(apiCall);
        } else if (call->flags & trace::CALL_FLAG_MARKER_POP) {
            groups.top()->finishedAddingChildren();
            groups.pop();
        }
        if (!groups.isEmpty()) {
            groups.top()->addChild(apiCall);
        }
        if (apiCall->hasBinaryData()) {
            QByteArray data =
                apiCall->arguments()[apiCall->binaryDataIndex()].toByteArray();
            binaryDataSize += data.size();
        }
        if (call->flags & trace::CALL_FLAG_END_FRAME) {
            allCalls.squeeze();
            topLevelItems.squeeze();
            if (topLevelItems.count() == allCalls.count()) {
                currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
            } else {
                currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
            }
            allCalls.clear();
            groups.clear();
            topLevelItems.clear();
            frames.append(currentFrame);
            currentFrame = 0;
            binaryDataSize = 0;
            if (frames.count() >= FRAMES_TO_CACHE) {
                emit framesLoaded(frames);
                frames.clear();
            }
            if (m_parser.percentRead() - lastPercentReport >= 5) {
                emit parsed(m_parser.percentRead());
                lastPercentReport = m_parser.percentRead();
            }
        }
        delete call;
        call = m_parser.parse_call();
    }

    //last frames won't have markers
    //  it's just a bunch of Delete calls for every object
    //  after the last SwapBuffers
    if (currentFrame) {
        allCalls.squeeze();
        if (topLevelItems.count() == allCalls.count()) {
            currentFrame->setCalls(allCalls, allCalls, binaryDataSize);
        } else {
            currentFrame->setCalls(topLevelItems, allCalls, binaryDataSize);
        }
        frames.append(currentFrame);
        currentFrame = 0;
    }
    if (frames.count()) {
        emit framesLoaded(frames);
    }
}
コード例 #11
0
void BikerHttpRequestProcessor::processRequest()
{
    std::cerr << "processing request..." << std::endl;
    
    QRegExp numberRegExp("(\\d+(?:.\\d+)?)");
    
    //Es wird nur GET unterstützt, der Rest nicht. Bei was anderem: Grantig sein und 405 antworten.
    if (_requestType != "GET")
    {
        this->send405();
        return;
    }
    if (_requestPath.contains(".."))
    {
        //".." im Pfad ist ein falscher Request. Damit könnte man ins Dateisystem gelangen.
        std::cerr << "\"..\" in request: not allowed." << std::endl;
        this->send400();
    }
    
    std::cerr << "request file: " << _requestPath << std::endl;
    
    if (_requestPath.startsWith("/files/"))
    {
        if (! ProgramOptions::getInstance()->webserver_no_serve_files)
        {
            //"/files/" entfernen!
            QString _myRequestPath = _requestPath.remove(0, 7);
            QDir mainDir((ProgramOptions::getInstance()->webserver_public_html_folder).c_str());
            if ((ProgramOptions::getInstance()->webserver_public_html_folder == "") || !mainDir.exists())
            {
                this->send404();
                return;
            }
            QFile file(QString(ProgramOptions::getInstance()->webserver_public_html_folder.c_str()) + "/" + _myRequestPath);
            QDir dir(QString(ProgramOptions::getInstance()->webserver_public_html_folder.c_str()) + "/" + _myRequestPath);
            
            //Wenn die Datei existiert, und alle sie lesen dürfen (nicht nur
            //    Benutzer oder Gruppe): Datei senden. Sonst: 404 Not found.
            if ((!dir.exists()) && file.exists() && (file.permissions() & QFile::ReadOther))
            {
                std::cerr << "serving file: \"" << file.fileName() << "\"" << std::endl;
                this->sendFile(file);
            }
            else
            {
                if (dir.exists())
                    std::cerr << "file is a directory: \"" << file.fileName() << "\". Not serving." << std::endl;
                else if (!file.exists())
                    std::cerr << "file not found: \"" << file.fileName() << "\". Not serving." << std::endl;
                else if (file.permissions() & QFile::ReadOther)
                    std::cerr << "file does not have read permissions for everybody: \"" << file.fileName() << "\". Not serving." << std::endl;
                
                //In jedem Fall: 404 senden.
                this->send404();
            }
            return;
        }
        else
        {   //Dateien ausliefern durch Einstellungen verboten: Nicht ausliefern.
            std::cerr << "webserver configured not to serve files." << std::endl;
            this->send404();
            return;
        }
    }
    else
    {
        /**
         * @todo RegExp nur einmal erzeugen und dann wiederverwenden!
         */
        QRegExp cloudmadeApiKeyRegExp("^/([\\da-fA-F]{1,64})/(?:api|API)/0.(\\d)");
        //QRegExp cloudmadeApiPointListRegExp("^/(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})),(?:\\[(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))(?:,(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))){0,20}\\],)?(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))");
        QRegExp cloudmadeApiPointListRegExp("^/(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})),(?:\\[(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))(?:,(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16})){0,200}\\],)?(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))");
        QRegExp cloudmadeApiPointListExtractor("(?:(\\d{1,3}.\\d{1,16}),(\\d{1,3}.\\d{1,16}))");
        QRegExp cloudmadeApiRouteTypeRegExp("^/([a-zA-Z0-9]{1,64})(?:/([a-zA-Z0-9]{1,64}))?.(gpx|GPX|js|JS)$");
        
        QString apiKey="";
        int apiVersion=0;
        QVector<GPSPosition> routePointList;
        QString routeType="";
        QString routeModifier="";
        QString routeDataType="";
        
        int position=0;
        if ((position=cloudmadeApiKeyRegExp.indexIn(_requestPath)) != -1)
        {
            apiKey = cloudmadeApiKeyRegExp.cap(1).toLower();
            apiVersion = cloudmadeApiKeyRegExp.cap(2).toInt();
            //API-Key gefunden. Falls uns der interessiert, hier was damit machen!
            
            if (ProgramOptions::getInstance()->webserver_apikey != "")
            {
                if (ProgramOptions::getInstance()->webserver_apikey != apiKey.toStdString())
                {
                    std::cerr << "api key \"" << apiKey << "\" is not valid." << std::endl;
                    this->send403();
                    return;
                }
            }
            
            if (apiVersion != 3)
            {
                std::cerr << "requested api version 0." << apiVersion << ", which is not supported." << std::endl;
                this->send405();
                return;
            }
            
            position += cloudmadeApiKeyRegExp.cap(0).length();
        }
        else
        {
            this->send400();
            return;
        }
        position+=cloudmadeApiPointListRegExp.indexIn(_requestPath.mid(position));
        if (cloudmadeApiPointListRegExp.cap(0).length() != 0)
        {
            //Punktliste gefunden. Auswerten!
            //Neue RegExp zum Punkte herausholen...
            cloudmadeApiPointListExtractor.indexIn(cloudmadeApiPointListRegExp.cap(0));
            QString strLat, strLon;
            routePointList.clear();
            for (int pos=0; pos>=0; pos=cloudmadeApiPointListExtractor.indexIn(cloudmadeApiPointListRegExp.cap(0), cloudmadeApiPointListExtractor.cap(0).length()+pos))
            {
                strLat = cloudmadeApiPointListExtractor.cap(1);
                strLon = cloudmadeApiPointListExtractor.cap(2);
                GPSPosition point(strLat.toDouble(), strLon.toDouble());
                routePointList << point;
            }
            
            position += cloudmadeApiPointListRegExp.cap(0).length();
        }
        else
        {
            this->send400();
            return;
        }
        position+=cloudmadeApiRouteTypeRegExp.indexIn(_requestPath.mid(position));
        if (cloudmadeApiRouteTypeRegExp.cap(0).length() != 0)
        {
            routeType = cloudmadeApiRouteTypeRegExp.cap(1).toLower();
            routeModifier = cloudmadeApiRouteTypeRegExp.cap(2).toLower();
            routeDataType = cloudmadeApiRouteTypeRegExp.cap(3).toLower();
            //Routentyp gefunden. Auswerten!
        }
        else
        {
            this->send400();
            return;
        }
        
        //this->send102();
        
        boost::shared_ptr<RoutingMetric> metric;
        boost::shared_ptr<Router> router;
        boost::shared_ptr<DatabaseConnection> dbA;
        boost::shared_ptr<DatabaseConnection> dbB;
        boost::shared_ptr<AltitudeProvider> altitudeProvider;
        
        #ifdef ZZIP_FOUND
            altitudeProvider.reset(new SRTMProvider());
        #else
            altitudeProvider.reset(new ZeroAltitudeProvider());
        #endif
        
        if ((routeType == "bicycle") || (routeType == "bike"))
        {
            //altitudeProvider.reset(new ZeroAltitudeProvider());
            
            //Routingmetrik festlegen anhand der Benutzerwahl
            if ((routeModifier == "euclidean"))
            {
                metric.reset(new EuclideanRoutingMetric(altitudeProvider));
            }
            else if ((routeModifier == "simpleheight") || (routeModifier == "shortest"))
            {
                float detourPerHeightMeter = 100.0f;
                if (numberRegExp.indexIn(_parameterMap["detourperheightmeter"]) != -1)
                {
                    detourPerHeightMeter = numberRegExp.cap(1).toFloat();
                }
                metric.reset(new SimpleHeightRoutingMetric(altitudeProvider, detourPerHeightMeter));
            }
            else if (routeModifier == "advancedheight")
            {
                float punishment = 1.0f;
                float detourPerHeightMeter = 200.0f;
                if (numberRegExp.indexIn(_parameterMap["punishment"]) != -1)
                {
                    punishment = numberRegExp.cap(1).toFloat();
                }
                if (numberRegExp.indexIn(_parameterMap["detourperheightmeter"]) != -1)
                {
                    detourPerHeightMeter = numberRegExp.cap(1).toFloat();
                }
                metric.reset(new AdvancedHeightRoutingMetric(altitudeProvider, detourPerHeightMeter, punishment));
            }
            else if (routeModifier == "simplepower")
            {
                double weight = 90.0;
                double efficiency = 3 * weight;
                
                if (numberRegExp.indexIn(_parameterMap["weight"]) != -1)
                    weight = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["efficiency"]) != -1)
                    efficiency = numberRegExp.cap(1).toDouble();
                metric.reset(new SimplePowerRoutingMetric(altitudeProvider, weight, efficiency));
            }
            else if ((routeModifier == "power") || (routeModifier == "") || (routeModifier == "fastest"))
            {
                double weight = 90.0;
                //double maxPower = 140.0;
                double maxPower = 150.0;
                double minSpeed = 2.5;
                double pushBikeSpeed = 0.5;
                double haltungskorrekturfaktor = 0.4;
                double maxSpeed = -1.0;
                double noCyclewayPunishmentFactor = 5;
                
                if (numberRegExp.indexIn(_parameterMap["weight"]) != -1)
                    weight = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["maxpower"]) != -1)
                    maxPower = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["minspeed"]) != -1)
                    minSpeed = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["maxspeed"]) != -1)
                    maxSpeed = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["pushbikespeed"]) != -1)
                    pushBikeSpeed = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["nocyclewaypunishmentfactor"]) != -1)
                    noCyclewayPunishmentFactor = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["haltungskorrekturfaktor"]) != -1)
                    haltungskorrekturfaktor = numberRegExp.cap(1).toDouble();
                metric.reset(new PowerRoutingMetric(altitudeProvider, weight, maxPower, minSpeed, pushBikeSpeed, haltungskorrekturfaktor, noCyclewayPunishmentFactor ,maxSpeed));
            }
            else if ((routeModifier == "biketourpower") || (routeModifier == "biketour"))
            {
                double weight = 90.0;
                //double maxPower = 140.0;
                double maxPower = 100.0;
                double minSpeed = 2.5;
                double pushBikeSpeed = 0.5;
                double haltungskorrekturfaktor = 0.4;
                double maxSpeed = -1.0;
                double noCyclewayPunishmentFactor = 7;
                
                if (numberRegExp.indexIn(_parameterMap["weight"]) != -1)
                    weight = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["maxpower"]) != -1)
                    maxPower = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["minspeed"]) != -1)
                    minSpeed = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["maxspeed"]) != -1)
                    maxSpeed = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["pushbikespeed"]) != -1)
                    pushBikeSpeed = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["nocyclewaypunishmentfactor"]) != -1)
                    noCyclewayPunishmentFactor = numberRegExp.cap(1).toDouble();
                if (numberRegExp.indexIn(_parameterMap["haltungskorrekturfaktor"]) != -1)
                    haltungskorrekturfaktor = numberRegExp.cap(1).toDouble();
                metric.reset(new BikeTourPowerRoutingMetric(altitudeProvider, weight, maxPower, minSpeed, pushBikeSpeed, haltungskorrekturfaktor, noCyclewayPunishmentFactor ,maxSpeed));
            }
            else
            {
                std::cerr << "routeModifier \"" << routeModifier << "\" not supported." << std::endl;
                this->send405();
                return;
            }
        }
        else if (routeType == "car")
        {
            //TODO
            this->send405();
            return;
        }
        else if (routeType == "foot")
        {
            if ((routeModifier == "euclidean") || (routeModifier == "") || (routeModifier == "shortest") || (routeModifier == "fastest"))
            {
                metric.reset(new EuclideanRoutingMetric(altitudeProvider));
            }
        }
        else
        {
            std::cerr << "requested routeType=" << routeType << ", which is not supported." << std::endl;
            this->send405();
            return;
        }
        
        #ifdef SPATIALITE_FOUND
            if (ProgramOptions::getInstance()->dbBackend == "spatialite")
            {
                dbA.reset(new SpatialiteDatabaseConnection());
                dbB.reset(new SpatialiteDatabaseConnection());
            }
            else 
        #endif
        if (ProgramOptions::getInstance()->dbBackend == "sqlite")
        {
            dbA.reset(new SQLiteDatabaseConnection());
            dbB.reset(new SQLiteDatabaseConnection());
        }
        //Datenbank ist die globale DB...
        dbA->open(ProgramOptions::getInstance()->dbFilename.c_str());
        dbB->open(ProgramOptions::getInstance()->dbFilename.c_str());
        
        //TODO: Testen, ob das mit dem Cache überhaupt was bringt...
        dbA = boost::shared_ptr<DatabaseConnection>(new DatabaseRAMCache(dbA, ProgramOptions::getInstance()->dbCacheSize));
        dbB = boost::shared_ptr<DatabaseConnection>(new DatabaseRAMCache(dbB, ProgramOptions::getInstance()->dbCacheSize));
        
        //Routingalgorithmus heraussuchen, je nach Angabe. Standard: Mehrthread-A* oder Mehrthread-Dijkstra - je nach Metrik.
        if (_parameterMap["algorithm"] == "multithreadeddijkstra")
            router.reset(new MultithreadedDijkstraRouter(dbA, dbB, metric));
        else if (_parameterMap["algorithm"] == "dijkstra")
            router.reset(new DijkstraRouter(dbA, metric));
        else if (_parameterMap["algorithm"] == "astar")
            router.reset(new AStarRouter(dbA, metric));
        else if (_parameterMap["algorithm"] == "multithreadedastar")
            router.reset(new MultithreadedAStarRouter(dbA, dbB, metric));
        else
        {
            if (metric->getMeasurementUnit() == DISTANCE)
                router.reset(new MultithreadedAStarRouter(dbA, dbB, metric));
            else
                router.reset(new MultithreadedDijkstraRouter(dbA, dbB, metric));
        }
        
        //Route berechnen
        GPSRoute route = router->calculateShortestRoute(routePointList);
        //Keine Route gefunden? 404 senden.
        if (route.isEmpty())
        {
            std::cerr << "no route found." << std::endl;
            this->send404();
            return;
        }
        else
        {
            std::cerr << "found route." << std::endl
                << "  length: " << route.calcLength()/1000.0 << "km" << std::endl
                << "  duration: " << route.getDuration()/60.0 << "min" << std::endl
                << "  has " << route.getSize() << " points." << std::endl;
        }
        
        //Antwort entsprechend des Routentypen senden.
        if (routeDataType == "gpx")
            this->sendFile(route.exportGPXString(altitudeProvider));
        else if (routeDataType == "js")
            this->sendFile(route.exportJSONString());
        else
            std::cerr << "route datatype \"" << routeDataType  << 
                "\" not supported." << std::endl;
        return;
    }
}
コード例 #12
0
void TestImport::csvImport_data()
{
    QTest::addColumn<QString>("csv");
    QTest::addColumn<char>("separator");
    QTest::addColumn<char>("quote");
    QTest::addColumn<QString>("encoding");
    QTest::addColumn<int>("numfields");
    QTest::addColumn<QVector<QVector<QByteArray>>>("result");

    QVector<QVector<QByteArray>> result;
    result.append(QVector<QByteArray>() << "a" << "b" << "c");
    result.append(QVector<QByteArray>() << "d" << "e" << "f");
    result.append(QVector<QByteArray>() << "g" << "h" << "i");
    QTest::newRow("commas_noquotes") << "a,b,c\nd,e,f\ng,h,i\n"
                                     << ','
                                     << (char)0
                                     << "UTF-8"
                                     << 3
                                     << result;
    QTest::newRow("semicolons_noquotes") << "a;b;c\nd;e;f\ng;h;i\n"
                                         << ';'
                                         << (char)0
                                         << "UTF-8"
                                         << 3
                                         << result;
    QTest::newRow("commas_doublequotes") << "\"a\",\"b\",\"c\"\n\"d\",\"e\",\"f\"\n\"g\",\"h\",\"i\"\n"
                                         << ','
                                         << '"'
                                         << "UTF-8"
                                         << 3
                                         << result;
    QTest::newRow("noquotes_butquotesset") << "a,b,c\nd,e,f\ng,h,i\n"
                                           << ','
                                           << '"'
                                           << "UTF-8"
                                           << 3
                                           << result;
    QTest::newRow("windowslinebreaks") << "a,b,c\r\nd,e,f\r\ng,h,i\r\n"
                                       << ','
                                       << (char)0
                                       << "UTF-8"
                                       << 3
                                       << result;
    QTest::newRow("oldmaclinebreaks")  << "a,b,c\rd,e,f\rg,h,i\r"
                                       << ','
                                       << (char)0
                                       << "UTF-8"
                                       << 3
                                       << result;

    result.clear();
    result.append(QVector<QByteArray>() << "a" << "b" << "");
    result.append(QVector<QByteArray>() << "c" << "");
    result.append(QVector<QByteArray>() << "d" << "" << "e");
    result.append(QVector<QByteArray>() << "");
    result.append(QVector<QByteArray>() << "" << "" << "f");
    QTest::newRow("emptyvalues") << "a,b,\nc,\nd,,e\n\n,,f"
                                     << ','
                                     << (char)0
                                     << "UTF-8"
                                     << 3
                                     << result;

    result.clear();
    result.append(QVector<QByteArray>() << "a" << "b" << "c");
    QTest::newRow("oneline") << "a,b,c"
                             << ','
                             << (char)0
                             << "UTF-8"
                             << 3
                             << result;

    result.clear();
    result.append(QVector<QByteArray>() << "a,a\"" << "b" << "c");
    result.append(QVector<QByteArray>() << "d" << "e" << "\"\"f,f");
    QTest::newRow("manyquotes") << "\"a,a\"\"\",\"b\",\"c\"\n\"d\",\"e\",\"\"\"\"\"f,f\"\n"
                                << ','
                                << '"'
                                << "UTF-8"
                                << 3
                                << result;

    result.clear();
    result.append(QVector<QByteArray>() << QByteArray("\xC2\xAE") << QByteArray("\xC9\x85") << QByteArray("\xC6\x89"));
    QString csv = QString::fromUtf8("\xC2\xAE") + "," + QString::fromUtf8("\xC9\x85") + "," + QString::fromUtf8("\xC6\x89") + "\n";
    QTest::newRow("utf8chars") << csv
                               << ','
                               << (char)0
                               << "UTF-8"
                               << 3
                               << result;

    result.clear();
    result.append(QVector<QByteArray>() << QByteArray("\u4E18") << QByteArray("\u4E26") << QByteArray("\u4E4B"));
    QString csv2 = QString::fromUtf8("\u4E18") + "," + QString::fromUtf8("\u4E26") + "," + QString::fromUtf8("\u4E4B") + "\n";
    QTest::newRow("utf16chars") << csv2
                               << ','
                               << (char)0
                               << "UTF-16"
                               << 3
                               << result;
}
コード例 #13
0
ファイル: rtdb_api.cpp プロジェクト: radtek/isoftstone
void CRtTable::getTableRecs(QVector< QVariantList >& vecRows)
{
	vecRows.clear();
	QString strSQL = getAllField();
	getRecsBySQL(strSQL,vecRows);
}
コード例 #14
0
void DistanceToAtom::compute(const QVector<QVector3D> &pointsOriginal, float cutoff)
{
    if(pointsOriginal.size() == 0) {
        qDebug() << "DistanceToAtom::compute WARNING: input vector is empty.";
        return;
    }

    QElapsedTimer timer;
    timer.start();

    float min = 1e90;
    float max = -1e90;
    for(const QVector3D &point : pointsOriginal) {
        min = std::min(min, point[0]);
        min = std::min(min, point[1]);
        min = std::min(min, point[2]);

        max = std::max(max, point[0]);
        max = std::max(max, point[1]);
        max = std::max(max, point[2]);
    }
    max += 1e-5;
    const float systemSize = max - min;

    // Now translate all points
    QVector<QVector3D> points = pointsOriginal;
    for(QVector3D &point : points) {
        point[0] -= min;
        point[1] -= min;
        point[2] -= min;
    }
    float cellSize;
    CellList cellList = buildCellList(points, systemSize, cutoff, cellSize);
    const int numCells = cellList.size(); // Each index should be identical


    m_values.clear();
    m_values.resize(m_numberOfRandomVectors);
    m_randomNumbers.resize(3*m_numberOfRandomVectors);


    for(int i=0; i<3*m_numberOfRandomVectors; i++) {
        m_randomNumbers[i] = floatRandom(0, systemSize);
    }

    const float oneOverCellSize = 1.0/cellSize;

#pragma omp parallel for num_threads(8)
    for(int i=0; i<m_numberOfRandomVectors; i++) {
        const float x = m_randomNumbers[3*i+0];
        const float y = m_randomNumbers[3*i+1];
        const float z = m_randomNumbers[3*i+2];

        const int cx = x * oneOverCellSize;
        const int cy = y * oneOverCellSize;
        const int cz = z * oneOverCellSize;
        float minimumDistanceSquared = 1e10;
        const float minimumDistanceSquared0 = minimumDistanceSquared;

        // Loop through all 27 cells with size=cutoff
        for(int dx=-1; dx<=1; dx++) {
            for(int dy=-1; dy<=1; dy++) {
                for(int dz=-1; dz<=1; dz++) {
                    const vector<QVector3D> &pointsInCell = cellList[periodic(cx+dx, numCells)][periodic(cy+dy, numCells)][periodic(cz+dz, numCells)];
                    const int numberOfPointsInCell = pointsInCell.size();

                    for(int j=0; j<numberOfPointsInCell; j++) {
                        // const QVector3D &point = points[pointIndex];
                        const QVector3D &point = pointsInCell[j];

                        float dx = x - point[0];
                        float dy = y - point[1];
                        float dz = z - point[2];
                        if(dx < -0.5*systemSize) dx += systemSize;
                        else if(dx > 0.5*systemSize) dx -= systemSize;

                        if(dy < -0.5*systemSize) dy += systemSize;
                        else if(dy > 0.5*systemSize) dy -= systemSize;

                        if(dz < -0.5*systemSize) dz += systemSize;
                        else if(dz > 0.5*systemSize) dz -= systemSize;
                        const float distanceSquared = dx*dx + dy*dy + dz*dz;
                        if(distanceSquared < minimumDistanceSquared) minimumDistanceSquared = distanceSquared;
                    }
                }
            }
        }

        if(minimumDistanceSquared == minimumDistanceSquared0) {
            minimumDistanceSquared = -1;
        }

        m_values[i] = float(minimumDistanceSquared);
    }

    m_randomNumbers.clear();
    points.clear();

    // qDebug() << "DTO finished after " << timer.elapsed() << " ms.";
    m_isValid = true;

    //    if(pointsOriginal.size() == 0) {
    //        qDebug() << "DistanceToAtom::compute WARNING: input vector is empty.";
    //        return;
    //    }

    //    float min = 1e90;
    //    float max = -1e90;
    //    for(const QVector3D &point : pointsOriginal) {
    //        min = std::min(min, point[0]);
    //        min = std::min(min, point[1]);
    //        min = std::min(min, point[2]);

    //        max = std::max(max, point[0]);
    //        max = std::max(max, point[1]);
    //        max = std::max(max, point[2]);
    //    }
    //    max += 1e-5;
    //    const float systemSize = max - min;

    //    // Now translate all points
    //    QVector<QVector3D> points = pointsOriginal;
    //    for(QVector3D &point : points) {
    //        point[0] -= min;
    //        point[1] -= min;
    //        point[2] -= min;
    //    }

    //    float cellSize;
    //    CellList cellList = buildCellList(points, systemSize, cutoff, cellSize);
    //    const int numCells = cellList.size(); // Each index should be identical

    //    const float voxelSize = systemSize / m_size;
    //    for(int i=0; i<m_size; i++) {
    //        for(int j=0; j<m_size; j++) {
    //            for(int k=0; k<m_size; k++) {
    //                const QVector3D voxelCenter((i+0.5)*voxelSize, (j+0.5)*voxelSize, (k+0.5)*voxelSize);
    //                float minimumDistanceSquared0 = 1e10;
    //                float minimumDistanceSquared = 1e10;
    //                // Find the cell list where this position belongs and loop through all cells around
    //                const int cx = voxelCenter[0] / cellSize;
    //                const int cy = voxelCenter[1] / cellSize;
    //                const int cz = voxelCenter[2] / cellSize;

    //                // Loop through all 27 cells with size=cutoff
    //                for(int dx=-1; dx<=1; dx++) {
    //                    for(int dy=-1; dy<=1; dy++) {
    //                        for(int dz=-1; dz<=1; dz++) {
    //                            const vector<int> &pointsInCell = cellList[periodic(cx+dx, numCells)][periodic(cy+dy, numCells)][periodic(cz+dz, numCells)];
    //                            for(const int &pointIndex : pointsInCell) {
    //                                const QVector3D &point = points[pointIndex];

    //                                const float distanceSquared = periodicDistanceSquared(point, voxelCenter, systemSize);
    //                                minimumDistanceSquared = std::min(minimumDistanceSquared, distanceSquared);
    //                            }
    //                        }
    //                    }
    //                }
    //                if(minimumDistanceSquared == minimumDistanceSquared0) {
    //                    minimumDistanceSquared = -1;
    //                }
    //                setValue(i,j,k,float(minimumDistanceSquared));
    //            }
    //        }
    //    }

    //    m_isValid = true;
}