Exemple #1
0
int main(int argc, const char* argv[]) {

    QElapsedTimer startupTime;
    startupTime.start();

    int exitCode;
    {
        QSettings::setDefaultFormat(QSettings::IniFormat);
        Application app(argc, const_cast<char**>(argv), startupTime);

        QTranslator translator;
        translator.load("interface_en");
        app.installTranslator(&translator);
        exitCode = app.exec();
    }
    return exitCode;
}
Exemple #2
0
void MainWindow::saveHistogram(QStringList listImages)
{
    QDir dir;
    int size = listImages.length();

    this->edit->append("Saving histograms");

    QElapsedTimer timer;
    timer.start();

    // PARALLEL CODE

    int i;
    QString xml;
    QString xml_path;
    QString image;
    QString image_path;
    Histogram *h;
    QList<Histogram*> list_hist;

    //#pragma omp parallel firstprivate(list_hist) shared(list_images)
    #pragma omp parallel shared(list_images, list_hist)
    {
        #pragma omp for private(i, xml, xml_path, image, image_path, h)
        for(i = 0; i < size; i++)
        {
            xml = "hist_"+ QString("%1").arg(this->imageID + (i+1), 6, 10, QChar('0')) + ".xml";
            xml_path = dir.absolutePath() + "/" + this->HistFolder+"/"+ xml;

            image = list_images[i];
            image_path = dir.absolutePath() + "/" + this->ImageFolder + "/" + image;

            h = new Histogram(image.toStdString(), image_path.toStdString(), xml_path.toStdString());
            list_hist.append(h);
        }
        //cout << "Fi de la tasca pel fil " << omp_get_thread_num() << endl;
        #pragma omp barrier
    }
    this->list_hist = list_hist;

    // END PARALLEL CODE

    this->edit->append("Save complete.");
    this->edit->append("Time: " + QString::number(timer.elapsed()) + "milliseconds");
    cout << "End copy histograms" << endl;
}
bool QLlcpSocketPrivate::waitForBound(int msecs)
{
    if (m_state == QLlcpSocket::BoundState)
        return true;

    QElapsedTimer timer;
    timer.start();
    while (m_state != QLlcpSocket::BoundState && (msecs == -1 || timer.elapsed() < msecs)) {
        if (!m_socketRequestor->waitForDBusSignal(qMax(msecs - timer.elapsed(), qint64(0))))
            return false;
    }

    // Possibly not needed.
    QCoreApplication::sendPostedEvents(this, QEvent::MetaCall);

    return m_state == QLlcpSocket::BoundState;
}
Exemple #4
0
/*!
    Process pending events that match \a flags for a maximum of \a
    maxTime milliseconds, or until there are no more events to
    process, whichever is shorter.
    This function is especially useful if you have a long running
    operation and want to show its progress without allowing user
    input, i.e. by using the \l ExcludeUserInputEvents flag.

    \bold{Notes:}
    \list
    \o This function does not process events continuously; it
       returns after all available events are processed.
    \o Specifying the \l WaitForMoreEvents flag makes no sense
       and will be ignored.
    \endlist
*/
void QEventLoop::processEvents(ProcessEventsFlags flags, int maxTime)
{
    Q_D(QEventLoop);
    if (!d->threadData->eventDispatcher)
        return;

    QElapsedTimer start;
    start.start();
    if (flags & DeferredDeletion)
        QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
    while (processEvents(flags & ~WaitForMoreEvents)) {
        if (start.elapsed() > maxTime)
            break;
        if (flags & DeferredDeletion)
            QCoreApplication::sendPostedEvents(0, QEvent::DeferredDelete);
    }
}
Exemple #5
0
void OTF2ExportFunctor::exportTrace(Trace * trace, const QString& path,
                                    const QString& filename)
{
    std::cout << "Exporting " << filename.toStdString().c_str() << std::endl;
    QElapsedTimer traceTimer;
    qint64 traceElapsed;

    traceTimer.start();

    OTF2Exporter * exporter = new OTF2Exporter(trace);
    exporter->exportTrace(path, filename);

    traceElapsed = traceTimer.nsecsElapsed();
    RavelUtils::gu_printTime(traceElapsed, "Total export time: ");

    emit(done());
}
void MainWindow::GOMNE_fixed_q()
{
    QElapsedTimer tgomne;
    tgomne.start();
    RobotTraj();
    Init();

    par->isinside=0;

    par->nb_beacon = ui->BeaconSpinBox->value();
    //cout<<"q"<<par->q<<endl;
    ui->EpsilonSpinBox->setValue(1);
    for (uint i=0;i<100;i++){
       par->err[i] = 0.2;
    }
    ui->ErrSpinBox_1->setValue(par->err[0]);
    ui->ErrSpinBox_2->setValue(par->err[1]);
    ui->ErrSpinBox_3->setValue(par->err[2]);
    ui->ErrSpinBox_4->setValue(par->err[3]);
    ui->ErrSpinBox_5->setValue(par->err[4]);

    //epsilon<0.01 check is just to stop the algorithm when it doesnt find a solution to not freeze the window
    while(par->isinside!=1 && par->epsilon_sivia>0.01){
        if(par->in_perhaps==0){
            par->q--;
            ui->InterSpinBox->setValue(par->q);
            Sivia sivia(*R,par);
            //cout<<"q--"<<endl;
        }
        if(par->in_perhaps==1){
            par->epsilon_sivia/=2;
            Sivia sivia(*R,par);
            ui->EpsilonSpinBox->setValue(par->epsilon_sivia);
        }
    }
    SLAM(step);
    repaint();

    if (timeinfo){
        QString mess = "Execution time : ";
        mess.append(QString::number(tgomne.elapsed()));mess.append(" ms");
        QMessageBox::information(this,"Info",mess);
    }
    ui->InterSpinBox->setValue(par->q);
}
Exemple #7
0
void MainWindow::on_action_write_triggered()
{
    QString xlsFile = QFileDialog::getExistingDirectory(this);
    if(xlsFile.isEmpty())
        return;
    xlsFile += "/excelRWByCztr1988.xls";
    QElapsedTimer timer;
    timer.start();
    if(m_xls.isNull())
        m_xls.reset(new ExcelBase);
    m_xls->create(xlsFile);
    qDebug()<<"create cost:"<<timer.elapsed()<<"ms";timer.restart();
    QList< QList<QVariant> > m_datas;
    for(int i=0;i<1000;++i)
    {
        QList<QVariant> rows;
        for(int j=0;j<100;++j)
        {
            rows.append(i*j);
        }
        m_datas.append(rows);
    }
    m_xls->setCurrentSheet(1);
    timer.restart();
    m_xls->writeCurrentSheet(m_datas);
    qDebug()<<"write cost:"<<timer.elapsed()<<"ms";timer.restart();
    m_xls->save();
}
QNetworkReply* AdBlockManager::block(const QNetworkRequest &request)
{
#ifdef ADBLOCK_DEBUG
    QElapsedTimer timer;
    timer.start();
#endif
    const QString urlString = request.url().toEncoded().toLower();
    const QString urlDomain = request.url().host().toLower();
    const QString urlScheme = request.url().scheme().toLower();

    if (!isEnabled() || !canRunOnScheme(urlScheme)) {
        return 0;
    }

    foreach (AdBlockSubscription* subscription, m_subscriptions) {
        const AdBlockRule* blockedRule = subscription->match(request, urlDomain, urlString);

        if (blockedRule) {
            QVariant v = request.attribute((QNetworkRequest::Attribute)(QNetworkRequest::User + 100));
            WebPage* webPage = static_cast<WebPage*>(v.value<void*>());
            if (WebPage::isPointerSafeToUse(webPage)) {
                if (!canBeBlocked(webPage->url())) {
                    return 0;
                }

                webPage->addAdBlockRule(blockedRule, request.url());
            }

            AdBlockBlockedNetworkReply* reply = new AdBlockBlockedNetworkReply(subscription, blockedRule, this);
            reply->setRequest(request);

#ifdef ADBLOCK_DEBUG
            qDebug() << "BLOCKED: " << timer.elapsed() << blockedRule->filter() << request.url();
#endif

            return reply;
        }
    }

#ifdef ADBLOCK_DEBUG
    qDebug() << timer.elapsed() << request.url();
#endif

    return 0;
}
Exemple #9
0
void TestController::platformRunUntil(bool& condition, double timeout)
{
    if (qgetenv("QT_WEBKIT2_DEBUG") == "1" || timeout == m_noTimeout) {
        // Never timeout if we are debugging or not meant to timeout.
        while (!condition)
            QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, 50);
        return;
    }

    int timeoutInMSecs = timeout * 1000;
    QElapsedTimer timer;
    timer.start();
    while (!condition) {
        if (timer.elapsed() > timeoutInMSecs)
            return;
        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents, timeoutInMSecs - timer.elapsed());
    }
}
static QByteArray _readDtmData( QgsRasterDataProvider *provider, const QgsRectangle &extent, int res )
{
  QElapsedTimer t;
  t.start();

  // TODO: use feedback object? (but GDAL currently does not support cancelation anyway)
  QgsRasterBlock *block = provider->block( 1, extent, res, res );

  QByteArray data;
  if ( block )
  {
    block->convert( Qgis::Float32 ); // currently we expect just floats
    data = block->data();
    data.detach();  // this should make a deep copy
    delete block;
  }
  return data;
}
Exemple #11
0
    void decorateBatch()
    {
        if (m_tc.isNull())
            return;

        QElapsedTimer t;
        t.start();

        do {
            m_tc = m_tc.document()->find(m_re, m_tc, QTextDocument::FindBackward);
            if (m_tc.isNull())
                return;

            decorate(&m_tc);
        } while ( t.elapsed() < 20 );

        m_timerDecorate.start();
    }
QFuture<PlaylistItemPtr> PlaylistBackend::GetPlaylistItems(int playlist) {
  QMutexLocker l(db_->Mutex());
  QElapsedTimer timer;
  timer.start();
  QList<SqlRow> rows = GetPlaylistRows(playlist);

  // it's probable that we'll have a few songs associated with the
  // same CUE so we're caching results of parsing CUEs
  std::shared_ptr<NewSongFromQueryState> state_ptr(new NewSongFromQueryState());

  QFuture<PlaylistItemPtr> test =  QtConcurrent::mapped(
      rows, std::bind(&PlaylistBackend::NewPlaylistItemFromQuery, this, _1,
                      state_ptr));
  test.waitForFinished();
  QTextStream out(stdout);
  out << "TTIMER: " << timer.elapsed() << "\n";
  return test;
}
/*
 * Render the contents of this window. First polish, then sync, render
 * then finally swap.
 *
 * Note: This render function does not implement aborting
 * the render call when sync step results in no scene graph changes,
 * like the threaded renderer does.
 */
void QSGWindowsRenderLoop::renderWindow(QQuickWindow *window)
{
    RLDEBUG("renderWindow");
    QQuickWindowPrivate *d = QQuickWindowPrivate::get(window);

    if (!d->isRenderable())
        return;

    if (!m_gl->makeCurrent(window))
        return;

    QSG_RENDER_TIMING_SAMPLE(time_start);

    RLDEBUG(" - polishing");
    d->polishItems();
    QSG_RENDER_TIMING_SAMPLE(time_polished);

    RLDEBUG(" - syncing");
    d->syncSceneGraph();
    QSG_RENDER_TIMING_SAMPLE(time_synced);

    RLDEBUG(" - rendering");
    d->renderSceneGraph(window->size());
    QSG_RENDER_TIMING_SAMPLE(time_rendered);

    RLDEBUG(" - swapping");
    m_gl->swapBuffers(window);
    QSG_RENDER_TIMING_SAMPLE(time_swapped);

    RLDEBUG(" - frameDone");
    d->fireFrameSwapped();

#ifndef QSG_NO_RENDER_TIMING
        if (qsg_render_timing) {
            qDebug("WindowsRenderLoop(t=%d): window=%p, polish=%d ms, sync=%d ms, render=%d ms, swap=%d ms",
                   int(qsg_render_timer.elapsed()),
                   window,
                   int((time_polished - time_start)/1000000),
                   int((time_synced - time_polished)/1000000),
                   int((time_rendered - time_synced)/1000000),
                   int((time_swapped - time_rendered)/1000000));
        }
        if (QQmlProfilerService::enabled) {
            QQmlProfilerService::sceneGraphFrame(
                        QQmlProfilerService::SceneGraphWindowsPolishFrame,
                        time_polished - time_start
                        );

            QQmlProfilerService::sceneGraphFrame(
                        QQmlProfilerService::SceneGraphRenderLoopFrame,
                        time_synced - time_polished,
                        time_rendered - time_synced,
                        time_swapped - time_rendered
                        );
        }
#endif
}
void DavaGLWidget::Render()
{
	QElapsedTimer frameTimer;
	frameTimer.start();

	DAVA::QtLayer::Instance()->ProcessFrame();

	qint64 waitUntilNextFrameMs = (qint64) minFrameTimeMs - frameTimer.elapsed();

	if(waitUntilNextFrameMs <= 0)
	{
		// our render is too slow to reach maxFPS,
		// so we can wait a minimum time
		waitUntilNextFrameMs = 1;
	}

	QTimer::singleShot(waitUntilNextFrameMs, this, SLOT(Render()));
}
int main(int argc, char *argv[]){
    static qint64 vTime = 0;

    QElapsedTimer et;
    et.start();

    QApplication a(argc, argv);

    game = new Game();

    game->show();

    vTime += et.nsecsElapsed();
    qDebug() << "time elapsed for app launch:" << vTime << "ns";


    return a.exec();
}
void Predspracovanie::on_pushButton_6_clicked()//500ppi
{
    QElapsedTimer timer;
    timer.start();

    this->calculateOrientations(this->mat,globBlockSize);

    this->adaptive_segmentation(this->mat,globBlockSize,0.161,-0.5,0.975,0.009);
    mat_po_normal = this->normalisation(this->mat,20,5);
    binarizacia(this->mat_po_normal);
    this->calculateOrientations(this->mat_po_normal,globBlockSize);
    this->gaborFilter(globBlockSize);
    binarizacia(this->mat_filtrovana);
    thinning(this->kostra,this->mat_filtrovana);
    bitwise_not(this-> mat_filtrovana, this->mat_filtrovana);

    ui->cas->setText(QString::number(timer.elapsed()) + "ms");
}
Exemple #17
0
/* Once all the average RGB values found for both sub-images and each block in the main image,
 * this function finds the color difference between
*/
QStringList* PhotoMosaic::colorDifference(RGB* dirArr, int dirArrSize, RGB* mainArr, int mainArrSize, int precision) const
{
    qDebug() << "in colordifference";
    QStringList *list = new QStringList(); // size of i,

    QElapsedTimer timer;
    timer.start();
    int pos = 0;

    int percentageDone = 0;
    int onePercent = mainArrSize / 100;
    int count = onePercent;
    qDebug() << onePercent;
    for (int i = 0; i < mainArrSize; i = i + precision) {
        // display percentage of the work is done.
        if (i >= count) {
            percentageDone++;
            count += onePercent;
            qDebug() << percentageDone;
        }

        //Calculate the average euclidean distances for each picture in the sub-picture directory.
        //based on the precision, divide each block further by precision.
        //this can theoratically increase the accuracy (as long as there are enough mosaics to choose from.
        double min = 255 * precision * precision; // it should be 255 * (precision * precision)
        for (int j = 0; j < dirArrSize; j = j + precision) {
            double sum = 0;
            for (int x = 0; x < precision; x++) {
                sum += euclideanDistanceRGB(mainArr[i + x], dirArr[j + x]);
            }

            if (sum < min) {
                min = sum;
                pos = j / precision;
            }
            sum = 0;
        }
        QString picName = QString::number(pos);
        list->append(picName);
    }

    qDebug() << "COLOR DIFFERENCE Took" << timer.elapsed() << "milliseconds";
    return list;
}
void BleFileSource::run()
{
    BleAssert(!m_fileName.isEmpty());

    // m_fileName = "rtsp://218.204.223.237:554/live/1/0547424F573B085C/gsfp90ef4k0a6iap.sdp";
    CvCapture* capture = cvCreateFileCapture(m_fileName.toStdString().c_str());
    BleAssert(capture);

    IplImage* frame;
    while(!m_stop)
    {
        QElapsedTimer elapsedTimer;
        elapsedTimer.start();

        frame = cvQueryFrame(capture);
        if(!frame) break ;

        m_modifyMutex.lock();           // start lock

        BleImage be;
        be.width = frame->width;
        be.height = frame->height;

        be.data = new char[frame->imageSize];
        memcpy(be.data, frame->imageData, frame->imageSize);

        be.dataSize = frame->imageSize;
        be.format = BleImage_Format_BGR24;

        m_image = be;

        m_modifyMutex.unlock();        // end unlock

        int elapsedMs = elapsedTimer.elapsed();
        int needSleepMs = m_interval - elapsedMs;
        if (needSleepMs < 0) {
            needSleepMs = 0;
        }
        msleep(needSleepMs);
    }
    cvReleaseCapture(&capture);

    log_trace("BleFileSource Thread exit normally.");
}
Exemple #19
0
int main(int argc, char **argv)
{
    QLocale::setDefault(QLocale::C);

    //Scene registrations
    SceneRegister<SceneImage> regsceneimage("image");

    try
    {
        QApplication app(argc, argv);

        QStringList args = app.arguments();
        if (args.length() != 3)
            throw QString("Usage: %1 <scene.csd> <out.png>").arg(args.at(0));

        Render r;

        QElapsedTimer timer;
        timer.start();

        Scene scene(args.at(1));

        cout << "Parsing time: " <<
            r.showTime(timer.elapsed()).toStdString() << endl;

        Window win;
        win.resize(scene.width(), scene.height());
        win.show();
        win.setFileName(args.at(2));
        QFuture<void> retthread = QtConcurrent::run(render, &r, &win, &scene);

        int ret = app.exec();
        r.lock();
        r.quit();
        r.unlock();
        retthread.waitForFinished();
        return ret;
    }
    catch (const QString &s)
    {
        cerr << s.toStdString() << endl;
        return EXIT_FAILURE;
    }
}
bool QRPIJpegHandler::read(QImage* image)
{
  if (device())
  {

    m_dec_request.buffer_width = 0;
    m_dec_request.buffer_height = 0;
    m_dec_request.input_size = device()->read((char*)encodedInBuf, sizeof(encodedInBuf));

    QElapsedTimer timer;
    timer.start();

    BRCMJPEG_STATUS_T status = brcmjpeg_process(m_decoder, &m_dec_request);

    if (status == BRCMJPEG_SUCCESS)
    {

      for (int i = 0; i < m_dec_request.height; i++)
      {
        memcpy(image->scanLine(i), decodedBuf + m_dec_request.buffer_width * i * 4,
               m_dec_request.buffer_width * 4);
      }

      //*image = decodedImage;
      qDebug() << QDateTime::currentDateTime().toMSecsSinceEpoch()
               << "QRPIJpegHandler : decoded a"
               << m_dec_request.width << "x" << m_dec_request.height
               << "image in" << timer.elapsed() << "ms";

      return true;
    }
    else
    {
      qWarning() << "QRPIJpegHandler : Decoding failed with status" << status;
      return false;
    }

  }
  else
  {
    qDebug() << "QRPIJpegHandler : read() was called with NULL device";
    return false;
  }
}
Exemple #21
0
// the entry point for painting
qint64 SceneXrender::paint(QRegion damage, ToplevelList toplevels)
{
    QElapsedTimer renderTimer;
    renderTimer.start();

    createStackingOrder(toplevels);

    int mask = 0;
    QRegion updateRegion, validRegion;
    paintScreen(&mask, damage, QRegion(), &updateRegion, &validRegion);

    m_backend->showOverlay();

    m_backend->present(mask, updateRegion);
    // do cleanup
    clearStackingOrder();

    return renderTimer.nsecsElapsed();
}
void OutputModelTest::benchAddLongLine()
{
    // see also: https://bugs.kde.org/show_bug.cgi?id=295361
    const int objects = 100; // *.o files
    const int libs = 20; // -l...
    const int libPaths = 20; // -L...
    QString line = "g++ -m64 -Wl,-rpath,/home/gabo/md/qt/lib -o bin/flap_ui";
    for(int i = 0; i < objects; ++i) {
        line += QString(" .obj/file%1.o").arg(i);
    }
    for(int i = 0; i < libPaths; ++i) {
        line += QString(" -Lsome/path/to/lib%1").arg(i);
    }
    for(int i = 0; i < libs; ++i) {
        line += QString(" -lsomelib%1").arg(i);
    }

    KDevelop::OutputModel model(KUrl("/tmp/build-foo"));

    qRegisterMetaType<QModelIndex>("QModelIndex");
    QSignalSpy spy(&model, SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int)));

    QElapsedTimer totalTime;
    totalTime.start();

    QStringList lines;
    lines << line;
    QBENCHMARK {
        model.appendLines(lines);
        while(model.rowCount() != lines.count()) {
            QCoreApplication::instance()->processEvents();
        }
    }

    QVERIFY(model.rowCount() == lines.count());
    const qint64 elapsed = totalTime.elapsed();

    qDebug() << "ms elapsed to add lines: " << elapsed;
    qDebug() << "total number of added lines: " << lines.count();
    const double avgUiLockup = double(elapsed) / spy.count();
    qDebug() << "average UI lockup in ms: " << avgUiLockup;
    QVERIFY(avgUiLockup < 200);
}
Exemple #23
0
/*!
  Executes a previously prepared SQL query. Returns \c true if the query
  executed successfully; otherwise returns \c false.

  Note that the last error for this query is reset when exec() is
  called.

  \sa prepare(), bindValue(), addBindValue(), boundValue(), boundValues()
*/
bool QSqlQuery::exec()
{
#ifdef QT_DEBUG_SQL
    QElapsedTimer t;
    t.start();
#endif
    d->sqlResult->resetBindCount();

    if (d->sqlResult->lastError().isValid())
        d->sqlResult->setLastError(QSqlError());

    bool retval = d->sqlResult->exec();
#ifdef QT_DEBUG_SQL
    qDebug().nospace() << "Executed prepared query (" << t.elapsed() << "ms, "
                       << d->sqlResult->size() << " results, " << d->sqlResult->numRowsAffected()
                       << " affected): " << d->sqlResult->lastQuery();
#endif
    return retval;
}
void MainWindow::convert()
{
    emit this->started();

    QtConcurrent::run([&]{
        QElapsedTimer t;
        t.start();
        Book currentBook;
        for(int i = 0; i < ui->listWidget->count(); ++i)
        {
            currentBook.setSource(ui->listWidget->item(i)->text());
            currentBook.convert();
            emit completed((i*100)/ui->listWidget->count());
        }
        qDebug()<<t.nsecsElapsed();
        emit this->finished();
    });

}
Exemple #25
0
//
// Creates an array of random numbers, calls on merge sort, and
// times its execution.
//
void testMergeSortSeq (int size) {
    QElapsedTimer myTimer;
    qDebug() << "Running sequential merge sort...";
    qDebug() << "================================";

    int *a = new int[size];

    // Fill array with random numbers
    srand(time(0));
    for (int i=0; i<size; i++)  a[i] = rand() % 100000  ;

    myTimer.start();
    merge_sort_common(a, 0, size-1);

    qDebug() << "Total time elapsed: "<< myTimer.elapsed() << "miliseconds";
    qDebug() << "Verification:" << (verification(a,0,size-1)?"ok":"error") << endl;

    return;
}
bool QLlcpSocketPrivate::waitForConnected(int msecs)
{
    if (m_state != QLlcpSocket::ConnectingState)
        return m_state == QLlcpSocket::ConnectedState;

    QElapsedTimer timer;
    timer.start();
    while (m_state == QLlcpSocket::ConnectingState && (msecs == -1 || timer.elapsed() < msecs)) {
        if (!m_socketRequestor->waitForDBusSignal(qMax(msecs - timer.elapsed(), qint64(0)))) {
            setSocketError(QLlcpSocket::UnknownSocketError);
            break;
        }
    }

    // Possibly not needed.
    QCoreApplication::sendPostedEvents(this, QEvent::MetaCall);

    return m_state == QLlcpSocket::ConnectedState;
}
Exemple #27
0
void Cam::newFrame() {
   timer.start();
   frame.fill(Qt::blue);
   QPainter p{&frame};
   p.setFont({"Helvetica", 48});
   p.setPen(Qt::white);
   p.drawText(frame.rect(), Qt::AlignCenter,
              QStringLiteral("Hello,\nWorld!\n%1").arg(
                 QTime::currentTime().toString(QStringLiteral("hh:mm:ss.zzz"))));
}
void autobots_toutiao::onStart()
{  
  control_status = true;

  //QString interval = ui.lineEdit_interval->text();
  int nseconds = 10;//interval.toInt();
  int count = 0;

  while(control_status)
  {
    QNetworkCookieJar* cookie = new QNetworkCookieJar(this);

    network.GetManager().setCookieJar(cookie);

    QString temp = QStringLiteral("第");

    count ++; 

    QString temp2;
    temp2.setNum(count);

    ui.lineEdit_msg->setText(temp + temp2);

    GetContent();

    // 1.获取验证码
    QString pid;
    QString str = GetValidateCode(pid);

//     QElapsedTimer t;
//     t.start();
//     while(t.elapsed()<1000)  
//       QCoreApplication::processEvents();

    // 2.发送请求
    SubmitVote(str, pid);

    QElapsedTimer t;
    t.restart();
    while(t.elapsed()<nseconds*1000)  
      QCoreApplication::processEvents();
  }
}
Exemple #29
0
bool MainWindow::copyDirectoryFiles(const QString &fromDir, const QString &toDir, bool coverFileIfExist)
{
    if(isPathExcept(fromDir))
        return true;
    // 流逝时间计算
    static QElapsedTimer et;
    et.start();

    QDir sourceDir(fromDir);
    QDir targetDir(toDir);
    if(!targetDir.exists()){    /** 如果目标目录不存在,则进行创建 */
        if(!targetDir.mkdir(targetDir.path()))
        {
            qDebug() << "mkdir " + targetDir.filePath(sourceDir.dirName()) + " failed";
        }
    }

    QFileInfoList fileInfoList = sourceDir.entryInfoList();

    foreach(QFileInfo fileInfo, fileInfoList)
    {
        if(fileInfo.fileName() == "." || fileInfo.fileName() == "..")
            continue;

        if(fileInfo.isDir())
        {   /**< 当为目录时,递归的进行 copy */
            qDebug() << fileInfo.filePath() << "-> " << targetDir.filePath(fileInfo.fileName());
            copyDirectoryFiles(fileInfo.filePath(),targetDir.filePath(fileInfo.fileName()),coverFileIfExist);
        }
        else
        {
            // 同步文件
            synTwoFiles(fileInfo.filePath(),targetDir.filePath(fileInfo.fileName()));
        }
        if(et.elapsed() > 300)
        {
            QApplication::processEvents();
            et.restart();
            qDebug() << "回到UI";
        }
    }
    return true;
}
Exemple #30
0
bool DUChainLock::lockForWrite(uint timeout)
{
  //It is not allowed to acquire a write-lock while holding read-lock

  Q_ASSERT(d->ownReaderRecursion() == 0);

  if (d->m_writer.load() == QThread::currentThread()) {
    //We already hold the write lock, just increase the recursion count and return
    d->m_writerRecursion.fetchAndAddRelaxed(1);
    return true;
  }

  QElapsedTimer t;
  if (timeout) {
    t.start();
  }

  while (1) {
    //Try acquiring the write-lcok
    if (d->m_totalReaderRecursion.load() == 0 && d->m_writerRecursion.testAndSetOrdered(0, 1)) {
      //Now we can be sure that there is no other writer, as we have increased m_writerRecursion from 0 to 1
      d->m_writer = QThread::currentThread();
      if (d->m_totalReaderRecursion.load() == 0) {
        //There is still no readers, we have successfully acquired a write-lock
        return true;
      } else {
        //There may be readers.. we have to continue spinning
        d->m_writer = nullptr;
        d->m_writerRecursion = 0;
      }
    }

    if (!timeout || t.elapsed() < timeout) {
      QThread::usleep(uSleepTime);
    } else {
      //Fail!
      return false;
    }
  }

  return false;
}