Beispiel #1
0
void HtmlParser::parse()
{
    while(!_downloaded)
    {
        QThread::msleep(10);
    }
    _info->_status = UrlInfo::PARSING;
    emit processing(_info.data());
    _info->_found = _content.contains(_text, Qt::CaseInsensitive);


    int start_offset = -1;
    QRegularExpression regExp("(?:https?|ftp)://(((((((((\\w|\\d)|\\055)|\\056)|\\046)|\\077)|\\043)|\\045)|\\057)|\\075)+");

    while (true)
    {
        QRegularExpressionMatch match = regExp.match(_content, ++start_offset);
        if (!match.hasMatch())
            break;
        start_offset = match.capturedStart();
        int end_offset = match.capturedEnd();
        _links << new HtmlParser(_content.mid(start_offset, end_offset), _text);
    }
    _content.clear();
    if (_downloader)
        delete _downloader;
    _downloader = nullptr;
    _info->_status = UrlInfo::FINISHED;
    emit processing(_info.data());
}
Beispiel #2
0
HtmlParser::HtmlParser(const QUrl &url, const QString &text, QObject *parent)
    :
      QObject(parent),
      _info(new UrlInfo, [](UrlInfo* p){delete p;}),
      _downloaded(false),
      _text(text),
      _downloader(nullptr)
{
    _info->_url = url.toString();
    _info->_found = false;
    _info->_status = UrlInfo::DOWNLOADING;
    _info->_percentage = 0;
    emit processing(_info.data());
    QThread * thread = new QThread();
    _downloader = new HtmlDownloader(url);
    _downloader->moveToThread(thread);

    connect( thread, SIGNAL(started()), _downloader, SLOT(doWork()));

    connect( _downloader, SIGNAL(finished(QString)), thread, SLOT(quit()));
    connect( _downloader, SIGNAL(finished(QString)), this, SLOT(downloaded(QString)), Qt::ConnectionType::DirectConnection);
    connect(_downloader, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgress(qint64,qint64)));

    connect( thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

    thread->start();
}
Beispiel #3
0
bool cSatipRtsp::Teardown(const char *uriP)
{
  debug1("%s (%s) [device %d]", __PRETTY_FUNCTION__, uriP, tunerM.GetId());
  bool result = false;

  if (handleM && !isempty(uriP)) {
     long rc = 0;
     cTimeMs processing(0);
     CURLcode res = CURLE_OK;

     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_STREAM_URI, uriP);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_REQUEST, (long)CURL_RTSPREQ_TEARDOWN);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEFUNCTION, cSatipRtsp::DataCallback);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEDATA, this);
     SATIP_CURL_EASY_PERFORM(handleM);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEFUNCTION, NULL);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEDATA, NULL);
     if (dataBufferM.Size() > 0) {
        ParseData();
        dataBufferM.Reset();
        }

     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_CLIENT_CSEQ, 1L);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_SESSION_ID, NULL);

     result = ValidateLatestResponse(&rc);
     debug5("%s (%s) Response %ld in %" PRIu64 " ms [device %d]", __PRETTY_FUNCTION__, uriP, rc, processing.Elapsed(), tunerM.GetId());
     }

  return result;
}
Beispiel #4
0
int main() {
    freopen(INPUT, "r", stdin);
//    freopen(OUTPUT, "w", stdout);
    scanf("%d", &n);
    while (n != 0) {
        max = sum = 0;
        min = 99;
        for (i = 0; i < n; i++) {
            scanf("%d", &temp);
            if (temp > max) {
                max = temp;
            }
            if (temp < min) {
                min = temp;
            }
            sum += temp;
            buckets[temp]++;
        }

        processing();
        printf("%d\n", current_len);

        ept_bkt();
        scanf("%d", &n);
    }
    exit(0);
}
Beispiel #5
0
void FlexWatchCam::processing(const QByteArray &array)
{
  static const char new_lines_data[] = { 0x0D, 0x0A, 0x2D, 0x2D, 0x0D, 0x0A };
  static const QByteArray new_lines = QByteArray::fromRawData(new_lines_data,
  							      sizeof(new_lines_data));

  int boundary_pos = array.indexOf(boundary_);
  if(boundary_pos == -1) {
    image_.append(array);
  }
  else {
    // если перед --myboundary идет завершение пред. картинки - добавляем ее  
    if(boundary_pos > 0) {
      image_.append(array.left(boundary_pos));
    }

    if(image_.size() > 0) {
      QPixmap pixmap;
      pixmap.loadFromData(image_);
      setImage(pixmap);
      
      image_.truncate(0);
    }

    // если в этом же пакете после "--myboundary" идет начало след. фотки
    if(array.size() > boundary_pos + 58 + 4) {
      processing(array.mid(boundary_pos + 58 + 4));
    }
  }
}
Beispiel #6
0
/* source */
int main(int argc, char *argv[])
{
    
    char dir1[PATH_MAX], dir2[PATH_MAX];

    if (argc != 4) {
        fprintf(stderr, "%s: Too few arguments: %d\n", program, argc);
        exit(1);
    }

    /* input data */
    program = &(argv[0][(strlen(argv[0]) - strlen(strrchr(argv[0], '/'))) + 1]);
    strcpy(dir1, argv[1]);   //argv[1] - PATH to dir1
    strcpy(dir2, argv[2]);  //argv[2] - PATH to dir2
    maxN = atoi(argv[3]);
    
    //check_args(curDir);
    //printf("%s - %d - %d - %s\n",curDir, s.min, s.max, foutput);
    //printf("\nCount of read files: %d\n", processing(curDir));

    processing(dir1, dir2);

    return 0;

}
Beispiel #7
0
bool Simonoid::connectSignalsAndSlots() {
  if ( m_dbusinterface == NULL )
    m_dbusinterface = new QDBusInterface ( "org.kde.simon",
                                           "/SimonSender",
                                           "local.SimonSender" );

  if ( m_dbusinterface == NULL ) return false;

  bool success = true;
  if ( success ) {
    success = connect ( m_dbusinterface, SIGNAL (listening()), this, SLOT (listeningCalled()) );
    kDebug() << "connecting listening:" << ( success?"connected":"disconnected" ) ;
  }
  if ( success ) {
    success = connect ( m_dbusinterface, SIGNAL (processing()), this, SLOT (processingCalled()) );
    kDebug() << "connecting processing:" << ( success?"connected":"disconnected" ) ;
  }
  if ( success ) {
    success = connect ( m_dbusinterface, SIGNAL (receivedResults()), this, SLOT (receivedResultsCalled()) );
    kDebug() << "connecting receivedResults:" << ( success?"connected":"disconnected" ) ;
  }
  if ( success ) {
    success = connect ( m_dbusinterface, SIGNAL (recordingLevel(double)), this, SLOT (recordingLevelCalled(double)) );
    kDebug() << "connecting recordingLevel:" << ( success?"connected":"disconnected" ) ;
  }
  if ( success ) {
    m_isconnected = true;
  } else {
    disconnectSignalsAndSlots();
  }

  return success;
}
Beispiel #8
0
Ut::Ut(QWidget *parent) : QDialog(parent)
{
qDebug() << "start Ut";
	ui.setupUi(this);
	connect(ui.convert, SIGNAL(clicked()), this, SLOT(read_write()));
	connect(ui.file, SIGNAL(textChanged(QString)), this, SLOT(newfile()));
	connect(ui.cat, SIGNAL(textChanged(QString)), this, SLOT(newcat()));
	connect(ui.observatory, SIGNAL(currentIndexChanged(int)), this, SLOT(observatory(int)));
	connect(ui.dir, SIGNAL(textChanged(QString)), this, SLOT(newdir()));
	connect(ui.convert, SIGNAL(pressed()), this, SLOT(processing()));

	connect(ui.LT2UT, SIGNAL(clicked()), this, SLOT(inpfilename()));	
	connect(ui.ST2UT, SIGNAL(clicked()), this, SLOT(inpfilename()));
    connect(ui.JD2UT, SIGNAL(clicked()), this, SLOT(inpfilename()));

	red.setColor(QPalette::Base,QColor(Qt::red));
	white.setColor(QPalette::Base,QColor(Qt::white));

//	filename = "..\\data\\" + ui.file->text() + "maindata_lt.txt";

	int index = 0;
	read_cfg(index);
	newfile();

	read_cat();
	observatory(index);

	read_dst();
	inpfilename();
qDebug() << "stop Ut";
}
Beispiel #9
0
void FlexWatchCam::httpReadyRead(const QHttpResponseHeader & resp)
{
  if(resp.statusCode() != 200)
    QMessageBox::warning(0, "Error", tr("StatusCode = %1").arg(resp.statusCode()));
  else {
    QByteArray array = http_.readAll();
    processing(array);
  }
}
Beispiel #10
0
MAIN(httpMain, int argc, char *argv[])
{
    MprTime     start;
    double      elapsed;

    if (mprCreate(argc, argv, MPR_USER_EVENTS_THREAD) == 0) {
        return MPR_ERR_MEMORY;
    }
    if ((app = mprAllocObj(App, manageApp)) == 0) {
        return MPR_ERR_MEMORY;
    }
    mprAddRoot(app);
    mprAddStandardSignals();

    initSettings();
    if (!parseArgs(argc, argv)) {
        showUsage();
        return MPR_ERR_BAD_ARGS;
    }
    mprSetMaxWorkers(app->workers);

#if BLD_FEATURE_SSL
    if (!mprLoadSsl(1)) {
        mprError("Can't load SSL");
        exit(1);
    }
#endif
    if (mprStart() < 0) {
        mprError("Can't start MPR for %s", mprGetAppTitle());
        exit(2);
    }
    start = mprGetTime();
    app->http = httpCreate();
    httpEaseLimits(app->http->clientLimits);

    processing();
    mprServiceEvents(-1, 0);

    if (app->benchmark) {
        elapsed = (double) (mprGetTime() - start);
        if (app->fetchCount == 0) {
            elapsed = 0;
            app->fetchCount = 1;
        }
        mprPrintf("\nRequest Count:       %13d\n", app->fetchCount);
        mprPrintf("Time elapsed:        %13.4f sec\n", elapsed / 1000.0);
        mprPrintf("Time per request:    %13.4f sec\n", elapsed / 1000.0 / app->fetchCount);
        mprPrintf("Requests per second: %13.4f\n", app->fetchCount * 1.0 / (elapsed / 1000.0));
        mprPrintf("Load threads:        %13d\n", app->loadThreads);
        mprPrintf("Worker threads:      %13d\n", app->workers);
    }
    if (!app->success && app->verbose) {
        mprError("Request failed");
    }
    return (app->success) ? 0 : 255;
}
Beispiel #11
0
void button_clicked(GtkWidget *widget, gpointer data) {
    g_print("%d\n", isDirectory(data));
    if (isDirectory(data)) {
        g_print("Valid directory %s\n", (char *) data);
        processing(data);

    } else {
        g_print("Invalid directory %s\n", (char *) data);
    }
}
Beispiel #12
0
void process(char *path, char *delim)
{
	int count, i;
	char *subpath[10];
	count = stok(path, delim[0], subpath);
	for (i = 0; i < count; i++)
		processing(subpath[i]);
	suntok(path, delim[0], subpath, count);
	change(path);
}
task main()
{
	int myval2 = 2; // defined as local to task main()(preferred)
	int myval3 = 3;
	
	inputs(myval1);
	processing(myval2);
	outputs(myval3);


}
Beispiel #14
0
bool cSatipRtsp::Setup(const char *uriP, int rtpPortP, int rtcpPortP)
{
  debug1("%s (%s, %d, %d) [device %d]", __PRETTY_FUNCTION__, uriP, rtpPortP, rtcpPortP, tunerM.GetId());
  bool result = false;

  if (handleM && !isempty(uriP)) {
     cString transport;
     long rc = 0;
     cTimeMs processing(0);
     CURLcode res = CURLE_OK;

     switch (modeM) {
       case cmMulticast:
            // RTP/AVP;multicast;destination=<IP multicast address>;port=<RTP port>-<RTCP port>;ttl=<ttl>
            transport = cString::sprintf("RTP/AVP;multicast;port=%d-%d", rtpPortP, rtcpPortP);
            break;
       default:
       case cmUnicast:
            // RTP/AVP;unicast;client_port=<client RTP port>-<client RTCP port>
            transport = cString::sprintf("RTP/AVP;unicast;client_port=%d-%d", rtpPortP, rtcpPortP);
            break;
       }

     // Setup media stream
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_STREAM_URI, uriP);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_TRANSPORT, *transport);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_REQUEST, (long)CURL_RTSPREQ_SETUP);
     // Set header callback for catching the session and timeout
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_HEADERFUNCTION, cSatipRtsp::HeaderCallback);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEHEADER, this);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEFUNCTION, cSatipRtsp::DataCallback);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEDATA, this);
     SATIP_CURL_EASY_PERFORM(handleM);
     // Session id is now known - disable header parsing
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_HEADERFUNCTION, NULL);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEHEADER, NULL);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEFUNCTION, NULL);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_WRITEDATA, NULL);
     if (headerBufferM.Size() > 0) {
        ParseHeader();
        headerBufferM.Reset();
        }
     if (dataBufferM.Size() > 0) {
        ParseData();
        dataBufferM.Reset();
        }

     result = ValidateLatestResponse(&rc);
     debug5("%s (%s, %d, %d) Response %ld in %" PRIu64 " ms [device %d]", __PRETTY_FUNCTION__, uriP, rtpPortP, rtcpPortP, rc, processing.Elapsed(), tunerM.GetId());
     }

  return result;
}
Beispiel #15
0
MAIN(httpMain, int argc, char **argv, char **envp)
{
    MprTime     start;
    double      elapsed;

    if (mprCreate(argc, argv, MPR_USER_EVENTS_THREAD) == 0) {
        return MPR_ERR_MEMORY;
    }
    if ((app = mprAllocObj(App, manageApp)) == 0) {
        return MPR_ERR_MEMORY;
    }
    mprAddRoot(app);
    mprAddStandardSignals();

    initSettings();
    if (parseArgs(argc, argv) < 0) {
        return MPR_ERR_BAD_ARGS;
    }
    mprSetMaxWorkers(app->workers);
    if (mprStart() < 0) {
        mprError("Cannot start MPR for %s", mprGetAppTitle());
        exit(2);
    }
    start = mprGetTime();
    app->http = httpCreate(HTTP_CLIENT_SIDE);
    httpEaseLimits(app->http->clientLimits);
#if BIT_STATIC && BIT_PACK_SSL
    extern MprModuleEntry mprSslInit;
    mprNop(mprSslInit);
#endif
    processing();
    mprServiceEvents(-1, 0);

    if (app->benchmark) {
        elapsed = (double) (mprGetTime() - start);
        if (app->fetchCount == 0) {
            elapsed = 0;
            app->fetchCount = 1;
        }
        mprPrintf("\nRequest Count:       %13d\n", app->fetchCount);
        mprPrintf("Time elapsed:        %13.4f sec\n", elapsed / 1000.0);
        mprPrintf("Time per request:    %13.4f sec\n", elapsed / 1000.0 / app->fetchCount);
        mprPrintf("Requests per second: %13.4f\n", app->fetchCount * 1.0 / (elapsed / 1000.0));
        mprPrintf("Load threads:        %13d\n", app->loadThreads);
        mprPrintf("Worker threads:      %13d\n", app->workers);
    }
    if (!app->success && app->verbose) {
        mprError("Request failed");
    }
    mprDestroy(MPR_EXIT_DEFAULT);
    return (app->success) ? 0 : 255;
}
Beispiel #16
0
MAIN(httpMain, int argc, char **argv, char **envp)
{
    MprTime     start;
    double      elapsed;
    int         success;

    if (mprCreate(argc, argv, MPR_USER_EVENTS_THREAD) == 0) {
        return MPR_ERR_MEMORY;
    }
    if ((app = mprAllocObj(App, manageApp)) == 0) {
        return MPR_ERR_MEMORY;
    }
    mprAddRoot(app);
    mprAddStandardSignals();
    initSettings();

    if ((app->http = httpCreate(HTTP_CLIENT_SIDE)) == 0) {
        return MPR_ERR_MEMORY;
    }
    if (parseArgs(argc, argv) < 0) {
        return MPR_ERR_BAD_ARGS;
    }
    mprSetMaxWorkers(app->workers);
    if (mprStart() < 0) {
        mprLog("error http", 0, "Cannot start MPR for %s", mprGetAppTitle());
        exit(2);
    }
    start = mprGetTime();

    processing();
    mprServiceEvents(-1, 0);

    if (app->benchmark) {
        elapsed = (double) (mprGetTime() - start);
        if (app->fetchCount == 0) {
            elapsed = 0;
            app->fetchCount = 1;
        }
        mprPrintf("\nRequest Count:       %13d\n", app->fetchCount);
        mprPrintf("Time elapsed:        %13.4f sec\n", elapsed / 1000.0);
        mprPrintf("Time per request:    %13.4f sec\n", elapsed / 1000.0 / app->fetchCount);
        mprPrintf("Requests per second: %13.4f\n", app->fetchCount * 1.0 / (elapsed / 1000.0));
        mprPrintf("Load threads:        %13d\n", app->loadThreads);
        mprPrintf("Worker threads:      %13d\n", app->workers);
    }
    if (!app->success && app->verbose) {
        mprLog("error http", 0, "Request failed");
    }
    success = app->success;
    mprDestroy();
    return success ? 0 : 255;
}
Beispiel #17
0
SimonSender::SimonSender() : m_state(SimonSender::Idle)
{
  new SimonSenderAdaptor(this);
  QDBusConnection dbus = QDBusConnection::sessionBus();
  dbus.registerObject("/SimonSender", this);
  dbus.registerService("org.simon-listens.SimonSender");

  connect(this, SIGNAL(processing()), this, SLOT(slotProcessing()));
  connect(this, SIGNAL(listening()), this, SLOT(slotListening()));
  connect(this, SIGNAL(receivedResults()), this, SLOT(slotReceivedResults()));
  connect(&loudnessTimer, SIGNAL(timeout()), this, SLOT(relayLoudness()));
  
  loudnessTimer.start(500);
}
int main(void) 
{
	printf("start of int main()");
	// your code goes here

	int myval2 = 2; // defined as local to task main()(preferred)
	int myval3 = 3;
	
	inputs();
	processing(myval2);
	outputs(myval3);
    
    printf("end of int main()");

	return 0;
} // end of int main()
bool NetworkDynamicsPlotterApplication::setupGui() {

	//Have to  be present before the GUI is constructed.
	StandardNeuralNetworkFunctions();
	StandardConstraintCollection();



	mMainWindow = new DynamicsPlotterMainWindow(mEnableSimulator, true);

	if(mMainWindow != 0) {
		new NetworkEditorCollection(mMainWindow->getMenu("Tools"), "Network &Editor", false);

		BoolValueSwitcherAction *runPlotterButton = new BoolValueSwitcherAction("&Run Plotters",
					DynamicsPlotConstants::VALUE_PLOTTER_EXECUTE);
		runPlotterButton->setShortcut(tr("Ctrl+r"));
		mMainWindow->getMenu("Control")->addAction(runPlotterButton);
	}

	connect(this, SIGNAL(showGui()), mMainWindow, SLOT(showWindow()));


	mTimer = new QTimer();
	mTimer->setInterval(2000);

	OnlinePlotter *op = new OnlinePlotter();
	//Core::getInstance()->addSystemObject(op);

	for(int i = 0; i < 6; ++i) {

		OnlinePlotterWindow *opw = new OnlinePlotterWindow(i);

		connect(op, SIGNAL(dataPrepared(QString, MatrixValue*, bool)), opw,
SLOT(printData(QString, MatrixValue*, bool)));
		connect(mTimer, SIGNAL(timeout()), opw, SLOT(updateData()));
		connect(opw, SIGNAL(timerStart()), mTimer, SLOT(start()));
		connect(op, SIGNAL(startProcessing()), opw, SLOT(processing()));
		connect(op, SIGNAL(finishedProcessing()), opw, SLOT(finishedProcessing()));
	}

	connect(op, SIGNAL(finishedProcessing()), mTimer, SLOT(stop()));

	//***/Till****//

	return true;
}
Beispiel #20
0
void
finishreg(void)
{
	int idx = 0;

	if(!fpga_read) {
		startfpga();
		fpga_read = 1;
	}

	while(((idx = findreg(idx)) >= 0) && processing()) {
		if(idx == (FPGA_MAX - FPGA_DIFF)) {
			printf("."); fflush(stdout);
			idx = 0;
		} else
			idx++;
	}
}
Beispiel #21
0
bool cSatipRtsp::Play(const char *uriP)
{
  debug1("%s (%s) [device %d]", __PRETTY_FUNCTION__, uriP, tunerM.GetId());
  bool result = false;

  if (handleM && !isempty(uriP)) {
     long rc = 0;
     cTimeMs processing(0);
     CURLcode res = CURLE_OK;

     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_STREAM_URI, uriP);
     SATIP_CURL_EASY_SETOPT(handleM, CURLOPT_RTSP_REQUEST, (long)CURL_RTSPREQ_PLAY);
     SATIP_CURL_EASY_PERFORM(handleM);

     result = ValidateLatestResponse(&rc);
     debug5("%s (%s) Response %ld in %" PRIu64 " ms [device %d]", __PRETTY_FUNCTION__, uriP, rc, processing.Elapsed(), tunerM.GetId());
     }

  return result;
}
/**
 * Extract lines from a set of points using ransac
 */
std::vector<Line> SegmentStitching::extractLinesFromMeasurements(pcl::PointCloud<pcl::PointXYZ>::Ptr measurements,
                                                                 float ransacThreshold){
    std::vector<Line> lines;
    // will pass this vector to ransac to get the line model - we then need to
    // use it to remove the inliers of the model so that we can process other
    // lines in the data
    std::vector<int>* inliers = new std::vector<int>();

    pcl::PointCloud<pcl::PointXYZ>::Ptr processing(new pcl::PointCloud<pcl::PointXYZ>);
    pcl::PointCloud<pcl::PointXYZ>::Ptr trimmed(new pcl::PointCloud<pcl::PointXYZ>);
    *processing = *measurements; // copy stuff from the measurement cloud to be processed

    // naive: extract two lines from each segment. TODO: extraction of lines
    // based on proportion of points remaining in the cloud once the first line
    // has been removed.
    for (int i = 0; i < 2; i++) {
        // ROS_INFO("Trimmed size: %d", (int)trimmed->size());
        // ROS_INFO("Processing size: %d", (int)processing->size());

        // Extract a line from the measurements, and put the inlier references into inliers.
        lines.push_back(extractLineFromMeasurements(processing, ransacThreshold, inliers));
        // ExtractIndices expects a different type than vector, so create that
        pcl::PointIndices::Ptr inl(new pcl::PointIndices);
        inl->indices = *inliers;

        // Trim the cloud down to those points which are not the inliers of the
        // model that was discovered by ransac.
        pcl::ExtractIndices<pcl::PointXYZ> extract;
        extract.setInputCloud(processing);
        extract.setIndices(inl);
        extract.setNegative(true); // return points which are NOT the indices
        extract.filter(*trimmed);

        // Update the points to be processed for the next loop
        *processing = *trimmed;
    
        std::cout << lines[i] << std::endl;
    }

    return lines;
}
Beispiel #23
0
network code(){
	switch(line){
		case THING1:
			doit1();

		break;
		case THING2:
			if(x == STUFF){
				do_first_stuff();

				if(y == OTHER_STUFF)
					break;
				do_later_stuff();
			}
			initialize_modes_pointer();
			break;
		default:
			processing();
	}
	use_modes_pointer();
}
Beispiel #24
0
Datei: main.c Projekt: EQ4/waonc
int
main (int argc, char * argv [])
{
   wbool_t parse_good = wtrue;
   waon_parameters_t waon_parameters;
   analysis_scratchpad_t analysis_scratchpad;
   wbool_t result = parameters_initialize(&waon_parameters);
   if (result)
      result = parameters_parse(&waon_parameters, argc, argv);

   if (result)
      result = analysis_scratchpad_initialize(&analysis_scratchpad);

   if (result)
   {
       analysis_scratchpad.absolute_cutoff = waon_parameters.abs_flg;
       if (not_nullptr(waon_parameters.file_patch))
          analysis_scratchpad.use_patchfile = wtrue;

       /* NEW as of 12-01 */

       g_midi_pitch_info.mp_adj_pitch = waon_parameters.adj_pitch;
   }
   if (waon_parameters.show_help)
   {
      print_usage();
      parse_good = wfalse;
   }
   else if (waon_parameters.show_version)
   {
      print_version();
      parse_good = wfalse;
   }
   if (result && parse_good)
   {
      parse_good = processing(&waon_parameters, &analysis_scratchpad);
      parameters_free(&waon_parameters);
   }
   return parse_good ? 0 : 1 ;
}
Beispiel #25
0
void RApplication::go()
{	
	CV_Assert(capture.open(Pubvar::videoPath));	
	videoLen = (int)capture.get(CV_CAP_PROP_FRAME_COUNT);	
	fps = (int)capture.get(CV_CAP_PROP_FPS);			
	bDtr = new BDetector(fps, Pubvar::sensitive);	
	fidOI = new bool[videoLen];
	for(int i=0; i<videoLen;++i)
		fidOI[i] = false;

	cout<<"[a]: rewind"<<endl<<"[d]: forward"<<endl<<"[p]: pause / continue"<<endl<<"[o]: object detection"<<endl;

	for (fid=0; fid < videoLen; ++fid)
	{
		sec = fid/fps;
		capture >> frame;		
		processing();
		isSkip = false;

#ifdef DEMO
		imshow(Pubvar::videoPath, frame);			
		createTrackbar( "time", Pubvar::videoPath, &sec, videoLen/fps ,fidControler, (void*)this);				
		
		if(!keyboardCtrl( waitKey(playSpeed) ))
			break;

#elif defined EXPERIMENT			
		if(fid %(videoLen/10) ==0)
		{
			system("cls");
			cout<<Pubvar::videoPath <<" :"<< ((double)fid/videoLen) * 100<<" %"<<endl;			
		}				
#endif
	}

#ifdef EXPERIMENT
	this->writeVideo();	
#endif
}
Beispiel #26
0
////////////////////////////////////////////////
/// Thread sensitive to clock and inport event
/// - inherited from ipcore
/// - recieve incoming flits
/// - assign arrival timestamps
/// - send them for processing (concatenation)
////////////////////////////////////////////////
void App_concat::recv()
{
    string data;
    while (true)
    {
        wait();	// wait until inport event
        if (flit_inport.event())
        {
            flit flit_recd = flit_inport.read();	// read incoming flit
            flit_recd.simdata.atimestamp = sim_count;	// record arrival time (in clock cycles)
            flit_recd.simdata.atime = sc_time_stamp();	// record absolute arrival time
            if (LOG >= 1)
                eventlog<<"\ntime: "<<sc_time_stamp()<<" name: "<<this->name()<<" tile: "<<tileID<<" Recieved flit at core "<<flit_recd<<flit_recd.simdata;
            cout<<"\ntime: "<<sc_time_stamp()<<" name: "<<this->name()<<" tile: "<<tileID<<" Recieved flit at core "<<flit_recd;
            get_data(flit_recd, data);
            if (LOG >= 1)
                eventlog<<"Recieved data: "<<data;
            cout<<"Recieved data: "<<data;

            processing(flit_recd);	// call method to process flit
        }
    }
}
void MainWindow::fileParse(QString fn)
{
    ui->statusBar->showMessage(fn);

    QFile file(fn);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "Erro",
                              "Ocorreu um erro ao abrir o arquivo",
                              QMessageBox::Ok);
    }

    processing(true);

    QTextStream in(&file);

    // read the fist line. It contains the HEADERS
    QStringList first_line = in.readLine().split(",");
    ui->tableWidget->setColumnCount(first_line.length());
    ui->tableWidget->setHorizontalHeaderLabels(first_line);

    this->stringsToNormalize = new QList< QStringList >();

    while (!in.atEnd()) {
        QStringList line_splited = in.readLine().split(",");

        int col = 0;
        int row = ui->tableWidget->rowCount();

        this->stringsToNormalize->append(line_splited);

        ui->tableWidget->insertRow(row);
        foreach (QString s, line_splited) {
            // add the line to table
            QTableWidgetItem *item = new QTableWidgetItem(s);
            ui->tableWidget->setItem(row, col++, item);
        }
    }
Beispiel #28
0
int main(int argc,char *argv[])
{
	struct	sigaction sa;
	time_t	second_new_time;
	char	*ep;
   	pid_t	pid;
   	int port;
    int errno;
    struct tm *new_time_information;


  	if (argc != 4){
		usage();
		errno = 0;
	}
	
    strtoul(argv[1], &ep, 10);
 	if (*argv[1] == '\0' || *ep != '\0') {
		printf("WRONG PORT NUMBER\n");
		usage();
	}
    char	buf[80];
	memset(buf, 0, 81);
    bind_t *s = malloc(sizeof(bind_t));
	bzero(s, sizeof(bind_t));

	port = strtoul(argv[1], &ep, 10);
	s->document_dir = argv[2];
	s->logFile_dir = argv[3];
	
	FILE*	file = fopen(argv[3], "a");
	if (file < 0) {
		perror("CLIENT:\n");
		exit(EXIT_FAILURE);
	}
	fclose(file);
    //Daemonise, run background
    if (daemon(1, 0) == -1)
        err(1, "daemon() failed");
	

	s->si.sin_family = AF_INET;
	s->si.sin_port = htons(port);
	s->si.sin_addr.s_addr = htonl(INADDR_ANY);

	if ((s->ss = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
		err(1,"Client: cannot connect socket\n");

	if (bind(s->ss, (struct sockaddr *)&s->si, sizeof(s->si)) == -1)
		err(1,"Binding Error\n");

	/* Catching SIGCHLD to make sure we have no zombies children */
	sa.sa_handler = kidhandler;
		sigemptyset(&sa.sa_mask);

	/*
	* allow system calls(eg. accept) to be restarted 
	* if they get interrupted by a SIGCHLD
	*/
	sa.sa_flags = SA_RESTART;
	if (sigaction(SIGCHLD, &sa, NULL) == -1)
		err(1, "sigaction failed\n");

	printf("Start to listen to port: %d\n", ntohs(s->si.sin_port));
	
	while(1){
        conn_t *c = malloc(sizeof(conn_t));
        bzero(c, sizeof(conn_t));
        
		c->slen = sizeof(c->client);
        c->s = s;

        if((recvfrom(c->s->ss, c->buffer, sizeof(c->buffer), 0,
            (struct sockaddr*)&c->client, &c->slen)) != -1){
			pid = fork();
			if (pid == 0){
			    time( &second_new_time );
	            new_time_information = localtime( &second_new_time );
	            strftime(buf,80,"%a %d %b %Y %X %Z", new_time_information);
				c->rec_time = strdup(buf);
				processing(c);
				close(s->ss);
				exit(0);				
			} else if (pid == -1) {
				err(1, "Can not Fork");
			}
		}else{
            err(errno, "Fail");
        }
        free(c);
	}
}
	void
	PuzzleSolver::ASyncSolver(PopStarBoard board)
	{
		PuzzleSolution* Solution = new PuzzleSolution(board);
		
		auto task = 
			[&](PuzzleSolution* solution, Concurrency::ThreadPool<PuzzleSolution>& pool)
		{
			Position nextPop = solution->NextPop();
			if (nextPop.m_x < BoardWidth && nextPop.m_y < BoardHeight)
			{
				solution->CurrentPoints() += solution->Board().Pop(nextPop.m_x, nextPop.m_y);
				solution->m_solutionPath.push_back(Position(solution->NextPop().m_x, solution->NextPop().m_y));
			}
			PieceMap matches;
			solution->Board().GetPoppableItems(matches);
			//if this is the end of this line of pops then add to solutions and return
			if (0 >= matches.size())
			{
				PuzzleSolution* processSolution = new PuzzleSolution(*solution);
				processSolution->CurrentPoints() += processSolution->Board().AddBonusPoints();
				m_outputQueue.Push(processSolution);
				m_process.notify_one();
			}

			//if we've already processed this board (and it's not finished)
			//and the score is lower than when we got here then skip
			unsigned int tempScore;
			if (true == m_finishedBoards.Find(solution->Board().BitSet(), tempScore)
				&&  tempScore >= solution->CurrentPoints())
			{
				delete solution; solution = nullptr;
				return;
			}		
			m_finishedBoards.Insert(solution->Board().BitSet(), solution->CurrentPoints());
			
			for (auto pos : matches)
			{
				PuzzleSolution* newSolution = new PuzzleSolution(*solution);
				newSolution->NextPop() = pos;
				newSolution->Level() += 1;
				pool.Enqueue(newSolution);
			}

			delete solution; solution = nullptr;
		};
		
		Concurrency::ThreadPool<PuzzleSolution> pool(std::thread::hardware_concurrency(), task);
		pool.Enqueue(Solution);
		std::thread processing(&PuzzleSolver::ProcessSolutions, this);

		{   // acquire lock
			std::mutex mutex;
			std::unique_lock<std::mutex> lock(mutex);
			pool.workIsDone.wait(lock);
		}
		m_finished = true;
		m_process.notify_one();
		if (processing.joinable())
			processing.join();
		if (nullptr == m_highestPoints)
			return; 
	}
Beispiel #30
0
//Thread de traitement
void *t_trait (void * buff){

  struct sockaddr_in serverAddr;
  socklen_t addr_size;
  int udpSocket;

  int sortie[nb][TEC_FRAME_LG_WB*3];
  int tab[TEC_FRAME_LG_WB*3]; //Tableau pour mettre en forme les échantillons avant de les envoyer

  rec *r;
  r=static_cast<rec *>(buff); // Cast du pointeur void* en rec*

  int n1=0,n2=0,i,k;

  long clk_tck = CLOCKS_PER_SEC;

    //Creation de la socket UDP
    udpSocket = socket(PF_INET, SOCK_DGRAM, 0);

    //Initialisation de l'adresse du client
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr =33597632; // Ici l'adresse du client. En c++ on n'utilise pas la fonction inet_addr("IP") on écrit directement la valeur de l'adresse IP
    serverAddr.sin_port = htons(7892);
    memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);  

    //Initialisation de la taille de l'adresse du client
    addr_size = sizeof serverAddr; 
   
	for (n1 = 0; n1 < nb_trames; n1++)
	{
	  k= n1%nb;
	  /*Verouillage du mutex et attente de la réception du paquet entier*/
             pthread_mutex_lock(&mutex[k]);   
             while ((*r).start[k] == 0) {
             pthread_cond_wait(&cond[k], &mutex[k]);
	     }
             pthread_mutex_unlock(&mutex[k]);

	     //Débruitage trame par trame
               for (n2 = 0; n2 <TEC_FRAME_LG_WB*3; n2++) // Read 20 ms of signal @ 48k 
	       {
			int sample =(*r).buffer[k][n2];
			
			//Convert sample from pcmformat to 24 bits format:
			sample = sample << (24 - PCM_BITS);

			//Set sample to processing interface: 
			//ctrl_s.ns_in_s.input_signal_pi[n2] = intp(sample);
			working_sample[n2] = (intp)sample;
		}

		// Downsample to 16k 
		dsp_fir_bb_processing(&delay_bb_ai[0], &working_sample[0], &fir_samples[0], &working_sample2[0], TEC_FRAME_LG_WB * 3, FIR_SIZE);

		for (n2 = 0; n2 < TEC_FRAME_LG_WB; n2++) // Output signal @96k
		{
			//Set sample to processing interface:
			ctrl_s.ns_in_s.input_signal_pi[n2] = working_sample2[n2 * 3];
		}		

		//NS processing per 20 ms of signal
		processing();

		//Upsample to 48k 
		for (n2 = 0; n2 < TEC_FRAME_LG_WB * 3; n2++) // Read 20 ms of signal @ 48k 
		{
			//Set sample to processing interface:
			working_sample2[n2] = 0;
		}
		for (n2 = 0; n2 < TEC_FRAME_LG_WB; n2++) // Read 20 ms of signal @ 48k 
		{
			//Set sample to processing interface:
			working_sample2[n2 * 3] = ctrl_s.ns_out_s.output_signal_pi[n2];
			
		}
		dsp_fir_bb_processing(&delay_bb_ai2[0], &working_sample2[0], &fir_samples[0], &working_sample[0], TEC_FRAME_LG_WB * 3, FIR_SIZE);
		//write_int_array(sortie2, (int *)&working_sample[0], TEC_FRAME_LG_WB * 3, 7); // right samples on 16bits 


        //Mise en forme des échantillons pour l'envoi
		for(i=0;i<960;i++){
		  tab[i]=working_sample[i] >> 7;
		}

		//Envoi du paquet débruité
		sendto(udpSocket,tab,960*sizeof(int),0,(struct sockaddr *)&serverAddr,addr_size);	     
		printf("Paquet envoyé %d\n",n1);

        //Mesure et affichage du temps d'exécution
		if(n1==(nb-1)){
		  t2 = clock();

	        }
        }

	// printf("Nombre de paquets envoyés %d \n", n1);
    //  printf("Temps consomme (s) : %lf \n",(double)(t2-t1)/(double)clk_tck);
}