コード例 #1
0
ファイル: UnitRules.C プロジェクト: BLLIP/bllip-parser
void
UnitRules::
gatherData(InputTree* tree)
{
  const Term* trm = Term::get(tree->term());
  assert(trm);
  int parInt = trm->toInt();
  int rparI = parInt-( Term::lastTagInt() + 1);
  InputTreesIter iti = tree->subTrees().begin();
  int len = tree->subTrees().size();
  for( ; iti != tree->subTrees().end() ; iti++)
    {
      InputTree* stree = (*iti);
      if(len == 1)
	{
	  const Term* strm = Term::get(stree->term());
	  if(strm->terminal_p()) continue;
	  assert(strm);
	  int chiInt = strm->toInt();
	  if(chiInt == parInt) continue;
	  int rchiI = chiInt -( Term::lastTagInt() + 1);
	  treeData_[rparI][rchiI]++;
	  //cerr << "TD " << parInt<<" " << chiInt << " " << treeData_[rparI][rchiI] << endl;
	}
      gatherData(stree);
    }
}
コード例 #2
0
void demo_test(){
    tempcounter=2;
    char c=0;
    //if(SolarStatus()==1){
        if (BatteryCharged()){
//            if (ReadInitFlag()==0){                             //check if its first initialisation of device
//                GSM_ON();                                       //turn on GSM module
//                SIM900_SEND(2);                                 //send a configuration request message to server
//                SetInitFlag();                                  //set initcheck flag
//            }
            for (char d=0; d<TRANSMIT_FREQ; d++){
                days++;                                         //increment days
                for (int i=0; i<tempcounter; i++){
                    getTempHum();                               //get temperature and humidity sensor
                    while ((TEMP_INT==0)&&(c<=3)){              //check DHT11 sensor 3 times for reading if no data received
                        getTempHum();
                        c++;
                    }
                    DayTEMP[i]=TEMP_INT;
                    DayHUM[i]=RH_INT;
                    delay_1s(3);                               //wait 30 seconds between each temperature readings
                }
                avgTempHum();                                   //calculate average temperature and humidity
                minmaxTempHum();                                //calculate minimum and maximum temperature and humidity
                getWaterLevel();                                //get water level from ultrasonic sensor
                getConductivity();
                getSolarReading();
                getBatteryReading();
                ShiftData();                                    //shift gathered data by offset
                if ((WaterLevel-OFFSET) >= WATER_THRESHOLD){    //check if water level is too low
                    SMS_data[0]=WARNING_PREFIX;                 //initiate message with warning char
                    SMS_data[1]=WaterLevel;                     //put water level in text message
                    SMS_data[2]=DATA_SUFFIX;                    //end message with suffix

                    GSM_ON();                                   //turn on sim900
                    delay_1s(5);                               //wait for GSM to connect to network
                    SIM900_SEND(1);                             //Send data message to server
                    GSM_OFF();                                  //turn off sim900
                }
                SaveData();                                     //Sava sensor readings to memory
            }
        }
        if (!BatteryCharged()){
            MonitorBattery();
        }
    SMS_data[0]=DATA_PREFIX;                            //start message with prefix
    gatherData();                                       //read data from memory
    getCheckByte();                                     //calculate check byte
    GSM_ON();                                           //turn on sim900
    delay_1s(10);                                       //wait for GSM to connect to network
    puts1USART("AT\r\n");
    delay_1s(5);
    SIM900_SEND(1);                                     //Send data message to server
   //} //solarpanel check
}
コード例 #3
0
ファイル: webcrawlerdialog.cpp プロジェクト: Iownnoname/qt
WebCrawlerDialog::WebCrawlerDialog(QWidget *parent) : QDialog (parent)
{
    ui.setupUi(this);
    connect ( ui.buttonBox,SIGNAL(accepted()), this, SLOT(gatherData()) );

    (ui.buttonBox) -> button (QDialogButtonBox::Ok) -> setDefault(true);

    (ui.seedUrlEdit)->setFocus();

    connect (ui.extLinksCheckBox, &QCheckBox::stateChanged,
             this, &WebCrawlerDialog::checkErrors);

    connect (ui.intLinksCheckBox, &QCheckBox::stateChanged,
             this, &WebCrawlerDialog::checkErrors);

    if ( !ui.extLinksCheckBox->isChecked()  &&!ui.intLinksCheckBox->isChecked() )
    {
        (ui.buttonBox) -> button (QDialogButtonBox::Ok)->setDisabled(true);
    }

}
コード例 #4
0
ファイル: nodeeditdialog.cpp プロジェクト: Iownnoname/qt
void NodeEditDialog::checkErrors()
{
    qDebug()<< " NodeEditDialog::checkErrors()" ;
    QString userLabel = ui.labelEdit->text();
    userLabel = userLabel.simplified();
    ui.labelEdit->setText(userLabel);

    if ( ui.labelEdit->text().isEmpty())
    {
        qDebug() << "empty label!";
        QGraphicsColorizeEffect *effect = new QGraphicsColorizeEffect;
        effect->setColor(QColor("red"));
        ui.labelEdit->setGraphicsEffect(effect);
        //(ui.buttonBox) -> button (QDialogButtonBox::Ok) -> setEnabled(false);
    }
    else
    {
        ui.labelEdit->setGraphicsEffect(0);
        (ui.buttonBox)->button(QDialogButtonBox::Ok)->setEnabled(true);
    }

    gatherData();
}
コード例 #5
0
ファイル: sessionanalysiswidget.cpp プロジェクト: HxCory/f1lt
void SessionAnalysisWidget::update(bool repaintCharts)
{
    gatherData();

    int rows = 0;

    QTableWidget *table = ui.lapTimeTableWidget;
    if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT)
        table = ui.lapTimeTableWidgetFP;

    if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT)
    {
        switch (ui.qualiTabWidget->currentIndex())
        {
            case 0: table = ui.lapTimeTableWidgetQuali; break;
            case 1: table = ui.lapTimeTableWidgetQ1; break;
            case 2: table = ui.lapTimeTableWidgetQ2; break;
            case 3: table = ui.lapTimeTableWidgetQ3; break;
        }
    }

    int firstPlace = 0;
	for (int i = 0; i < lapDataArray.size(); ++i)
	{
        if (lapInWindow(i))
        {
            if (rows == 0)
                firstPlace = i;
            if (rows + 1 >= table->rowCount())
            {
                table->insertRow(rows+1);
                table->setRowHeight(rows+1, 22);
            }

            if (lapDataArray[i].getCarID() < 0)
                continue;

            ColorsManager &sd = ColorsManager::getInstance();
            setItem(table, rows+1, 0, QString::number(rows+1)+".", Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::CYAN));

            QString s = EventData::getInstance().getDriversData()[lapDataArray[i].getCarID()-1].getDriverName();
            QTableWidgetItem *item = setItem(table, rows+1, 1, s, Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignLeft | Qt::AlignVCenter, sd.getColor(LTPackets::WHITE));
            item->setIcon(getDriverIcon(EventData::getInstance().getDriversData()[lapDataArray[i].getCarID()-1].getNumber()));


            setItem(table, rows+1, 2, lapDataArray[i].getTime().toString(), Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignCenter, sd.getColor(LTPackets::WHITE));

            s = (rows == 0 || !lapDataArray[i].getTime().isValid()) ? "" : "+" + DriverData::calculateGap(lapDataArray[i].getTime(), lapDataArray[firstPlace].getTime());
            setItem(table, rows+1, 3, s, Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::YELLOW));

            s = QString::number(lapDataArray[i].getLapNumber());
            if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT)
                s = SeasonData::getInstance().getSessionDefaults().correctFPTime(lapDataArray[i].getPracticeLapExtraData().getSessionTime()).toString("h:mm:ss");//lapDataArray[i].sessionTime.toString("h:mm:ss") + " (" + QString::number(LTPackets::currentEventFPLength()-LTPackets::timeToMins(lapDataArray[i].sessionTime))+")";

            else if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT)
                s = SeasonData::getInstance().getSessionDefaults().correctQualiTime(lapDataArray[i].getQualiLapExtraData().getSessionTime(), lapDataArray[i].getQualiLapExtraData().getQualiPeriod()).toString("mm:ss");

            setItem(table, rows+1, 4, s, Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::WHITE));

            if (ui.qualiTabWidget->currentIndex() == 0)
                setItem(table, rows+1, 5, QString::number(lapDataArray[i].getQualiLapExtraData().getQualiPeriod()), Qt::ItemIsEnabled | Qt::ItemIsSelectable, Qt::AlignRight | Qt::AlignVCenter, sd.getColor(LTPackets::WHITE));

            ++rows;
        }
	}
    if (rows < table->rowCount()-1)
    {
        for (int i = table->rowCount()-1; i > rows; --i)
            table->removeRow(i);
    }

    if (repaintCharts)
    {
        if (EventData::getInstance().getEventType() == LTPackets::RACE_EVENT)
        {
            ui.sessionLapTimesChart->setData(lapDataArray);
            ui.sessionLapTimesChart->update();

            ui.sessionPositionsChart->setData(lapDataArray);
            ui.sessionPositionsChart->update();

            ui.sessionGapsChart->setData(lapDataArray);
            ui.sessionGapsChart->update();
        }
        if (EventData::getInstance().getEventType() == LTPackets::PRACTICE_EVENT)
        {
            ui.sessionLapTimesChartFP->setData(lapDataArray);
            ui.sessionLapTimesChartFP->update();
        }
        if (EventData::getInstance().getEventType() == LTPackets::QUALI_EVENT)
        {
            switch (ui.qualiTabWidget->currentIndex())
            {
                case 0:
                    ui.sessionLapTimesChartQuali->setData(lapDataArray);
                    ui.sessionLapTimesChartQuali->update();
                break;

                case 1:
                    ui.sessionLapTimesChartQ1->setData(lapDataArray);
                    ui.sessionLapTimesChartQ1->update();
                    break;

                case 2:
                    ui.sessionLapTimesChartQ2->setData(lapDataArray);
                    ui.sessionLapTimesChartQ2->update();
                    break;

                case 3:
                    ui.sessionLapTimesChartQ3->setData(lapDataArray);
                    ui.sessionLapTimesChartQ3->update();
                    break;
            }
        }
    }
}
コード例 #6
0
int main(int argc, char **argv)
{
	// handling Crl-C
    struct 	sigaction act;

	// config file handling
    char	configFilePath[MAXPATHLEN];
    config_t cfg;
    struct	config config;
    int		c;						// for getopt

	// network communication
    int		socket_fd_cms;
    struct	sockaddr_in	info_cms;
    struct	hostent	*he_cms;
    struct	in_addr ipv4addr;

	// data gathering
	struct	data data;
//	char	command[256];
//	FILE	*fileDescriptor;		// for reading from /proc/net/wireless
//	char 	fileContent[256];


    if (argc==1)
    {
		printHelp();
		return 1;
    }

    opterr = 0;
    while ((c=getopt(argc, argv, "c:")) != -1) {
		switch (c) {
		    case 'c': strcpy(configFilePath, optarg); break;
		    case '?': if (optopt=='d' || optopt=='h')
				fprintf(stderr, "Option -%c requires an argument.\n", optopt);
			      else if (isprint (optopt))
				fprintf(stderr, "Unknown option '-%c'.\n", optopt);
		    	  else
				fprintf(stderr, "Unknown option character '\\x%x'.\n", optopt);
			      return 1;
	    	default: abort();
		}
    }

    act.sa_handler = intHandler;
    sigaction(SIGINT, &act, NULL);	// catch Ctrl-C


    // read config file
    config_init(&cfg);
    /* Read the file. If there is an error, report it and exit. */
    if(! config_read_file(&cfg, configFilePath))
    {
		fprintf(stderr, "%s:%d - %s\n", config_error_file(&cfg),
	    config_error_line(&cfg), config_error_text(&cfg));
		config_destroy(&cfg);
		return(EXIT_FAILURE);
    }
    // node, host, apikey, wlaninterface
    if (!(config_lookup_string(&cfg, "node", &(config.pNodeName))))
    {
		fprintf(stderr, "No 'node' setting in configuration file.\n");
		config_destroy(&cfg);
		return(EXIT_FAILURE);
    }
    if (!(config_lookup_string(&cfg, "host", &(config.pHostName))))
    {
		fprintf(stderr, "No 'host' setting in configuration file.\n");
		config_destroy(&cfg);
		return(EXIT_FAILURE);
    }
    if (!(config_lookup_string(&cfg, "apikey", &(config.pApiKey))))
    {
		fprintf(stderr, "No 'apikey' setting in configuration file.\n");
		config_destroy(&cfg);
		return(EXIT_FAILURE);
    }
    if (!(config_lookup_string(&cfg, "i2cbus", &(config.pi2cBus))))
    {
		fprintf(stderr, "No 'i2cbus' setting in configuration file.\n");
		config_destroy(&cfg);
		return(EXIT_FAILURE);
    }

printf ("conf file: %s\n", configFilePath);
printf ("host: %s\n", config.pHostName);
printf ("node: %s\n", config.pNodeName);
printf ("API key: %s\n", config.pApiKey);
printf ("i2c bus: %s\n", config.pi2cBus);

    if (!(he_cms = gethostbyname(config.pHostName)))
    {
        fprintf(stderr, "Could not resolve host name, err %d.\n", h_errno);
		config_destroy(&cfg);
        exit(1);
    }

// check existence of i2c bus
	wiringPiSetup();
	wiringPiI2CSetupInterface (config.pi2cBus, 0);
		// this stops execution on error. BAD!

  keepRunning = 0;
  do {
	if (!(gatherData(&config, &data)))
	{
		fprintf(stderr, "Could not gather data.\n");
		config_destroy(&cfg);
		return(EXIT_FAILURE);
	}
/*
  } while (keepRunning);
config_destroy(&cfg);
return (EXIT_FAILURE);
do {
*/
    if ((socket_fd_cms = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
    {
        fprintf(stderr, "Could not allocate socket, err %d.\n", errno);
		config_destroy(&cfg);
        exit(1);
    }
    info_cms.sin_family = AF_INET;
    info_cms.sin_port = htons(80);
    info_cms.sin_addr = *((struct in_addr *)he_cms->h_addr);
    if (connect(socket_fd_cms, (struct sockaddr *)&info_cms, sizeof(struct sockaddr)) < 0)
    {
        fprintf(stderr, "Could not connect to server, err%d.\n", errno);
        close(socket_fd_cms);
		config_destroy(&cfg);
        exit(1);
    }

    if (!(sendToEmonCMS(&config, &data, socket_fd_cms))) {
        printf("Could not send data.\n");
    }

    close(socket_fd_cms);

//    sleep (10);
  } while (keepRunning);

    printf ("Closing down.\n");
    config_destroy(&cfg);
    return EX_OK;
}
コード例 #7
0
SEXP matrixApply(SEXP result, SEXP data, SEXP margin, SEXP function,
                 int worldRank, int worldSize) {

  SEXP ans, data_size;
  
  MPI_Datatype row_type, column_type;
  MPI_Status status;
  
  int my_start, my_end, N, function_nlines,
    nvectors, offset;
  int local_check = 0, global_check = 0;
  int dimensions[2];

  if (worldRank == MASTER_PROCESS) { 
    data_size = GET_DIM(data);
    
    dimensions[0] = INTEGER_POINTER(data_size)[0];
    dimensions[1] = INTEGER_POINTER(data_size)[1];

    /* function SEXP object is a vector of strings, each element contains
       a single line of the function definition */

    function_nlines = length(function);   
  }

  MPI_Bcast(dimensions, 2, MPI_INT, 0, MPI_COMM_WORLD);
  MPI_Bcast(&function_nlines, 1, MPI_INT, 0, MPI_COMM_WORLD);

  /* margin provides the subscripts which the function will be
     applied over.  "1" indicates rows, "2" indicates columns,
     c(1,2)" indicates rows and columns */

  if(worldRank != MASTER_PROCESS)
    PROTECT(margin = allocVector(INTSXP, 1));

  MPI_Bcast(INTEGER(margin), 1, MPI_INT, 0, MPI_COMM_WORLD);

  /* Matrix dimensions in R are interpreted differen than in C.
     We will refer to R rows and columns ordering, so rows are not alligned
     in memory */

  if (INTEGER(margin)[0] == 1) {
    N = dimensions[0];

    /* define vector type type to handle R rows exchange
       (count, blocklength, stride)*/
    MPI_Type_vector (dimensions[1], 1, dimensions[0], MPI_DOUBLE, &row_type);
    MPI_Type_commit (&row_type);

  } else if (INTEGER(margin)[0] == 2) {
    N = dimensions[1];

    /* define contiguous type to handle R columns exchange */
    MPI_Type_contiguous(dimensions[0], MPI_DOUBLE, &column_type);
    MPI_Type_commit(&column_type);
    
  } else if (INTEGER(margin)[0] == 3) {
    // TODO
    DEBUG("Margin number 3 not yet implemented\n");
    return R_NilValue;
  } else {
    DEBUG("Don't know how to deal with margin number %d\n",
          INTEGER(margin)[0]);
    return R_NilValue;
  }
  
  if(worldRank != MASTER_PROCESS) {
  
    /* Allocate memory for SEXP objects on worker nodes.
       alloc... functions do their own error-checking and
       return if the allocation process will fail. */
    loopDistribute(worldRank, worldSize, N, &my_start, &my_end);
    
    if (INTEGER(margin)[0] == 1)
      PROTECT(data = allocMatrix(REALSXP, my_end-my_start, dimensions[1]));
    if (INTEGER(margin)[0] == 2)
      PROTECT(data = allocMatrix(REALSXP, dimensions[0], my_end-my_start));
              
    PROTECT(function = allocVector(STRSXP, function_nlines));
  }

  if ( (data == NULL) ||  (function == NULL) ) {
      local_check = 1;
  } else {
      local_check = 0;
  }

  /* Check whether memory was successfully allocated on all worker nodes */
  MPI_Allreduce(&local_check, &global_check, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);

  /*  No need to free memory if allocation fails on one of the workers
      R_alloc will release it after .Call returns to R */
  if ( global_check != 0 ) {
    /* Remove all references from the stack, I'm not sure if this is necessary */
    if(worldRank != MASTER_PROCESS)
      UNPROTECT(3);

    return ScalarInteger(-1);
  }

  /* Distribute data between processes */

  for (int worker_id=1; worker_id<worldSize; worker_id++) {

    if (worldRank == MASTER_PROCESS) {

      /* Calculate expected message length for each worker */
      loopDistribute(worker_id, worldSize, N, &my_start, &my_end);
      nvectors = my_end - my_start;

      /* If we applying over rows, as defined in R, we need to use the MPI vector type
         sending each row as a separate message */
      if (INTEGER(margin)[0] == 1) {
        for(int k=0; k<nvectors; k++) {
          offset = my_start+k;
          MPI_Send(&REAL(data)[offset], 1, row_type, worker_id, 0, MPI_COMM_WORLD);
        }
      }

      /* R defined columns are alligned in memory, single message of build from contiguous
         column_type elemensts is send */
      else if (INTEGER(margin)[0] == 2) {
        offset = my_start*dimensions[0];
        MPI_Send(&REAL(data)[offset], nvectors, column_type, worker_id, 0, MPI_COMM_WORLD);
      }
    }
    else if (worldRank == worker_id) {

      nvectors = my_end - my_start;

      if (INTEGER(margin)[0] == 1) {
        
        for(int k=0; k<nvectors; k++) {
          offset = k*dimensions[1];
          MPI_Recv(&REAL(data)[offset], dimensions[1], MPI_DOUBLE, MASTER_PROCESS, 0, MPI_COMM_WORLD, &status);
        }
      }
      else if (INTEGER(margin)[0] == 2) {
        MPI_Recv(REAL(data), nvectors, column_type, MASTER_PROCESS, 0, MPI_COMM_WORLD, &status);
      }
    }
  }

  /* Redo loop distribution for the Master process */
  if (worldRank == MASTER_PROCESS) {
      loopDistribute(worldRank, worldSize, N, &my_start, &my_end);
  }
    
  /* Bcast function name or definition, cover case when definition is split into
     several lines and stored as a SEXP string vector */
   bcastRFunction(function, function_nlines, worldRank);
  
  /* Response container, Vector of SEXPs, margin determines vector length */
  PROTECT(ans = allocVector(VECSXP, N));

  do_matrixApply(ans, data, margin, function, my_start, my_end, dimensions, worldRank);

  gatherData(result, ans, N, my_start, my_end, worldRank);
  
  if(worldRank != MASTER_PROCESS) {
    UNPROTECT(4);
  } else {
    UNPROTECT(1);
  }

  return result;

}
コード例 #8
0
void routine(){
        START:
        if(SolarStatus()==1){                                       //if solar-panel is on
            solarcounter = 0;

            while (BatteryCharged()){                               //if battery is charged
                if (ReadInitFlag()==0){                             //check if its first initialisation of device
                    GSM_ON();                                       //turn on GSM module
                    SIM900_SEND(2);                                 //send a configuration request message to server
                    SetInitFlag();                                  //set initcheck flag
                }
                char c=0;
                while ((TEMP_INT==0)&&(c<=3)){                      //check DHT11 sensor 3 times for reading if no data received
                    getTempHum();
                    c++;
                }
                DayTEMP[tempcounter]=TEMP_INT;
                DayHUM[tempcounter]=RH_INT;
                tempcounter++;
                delay_1ms(1);
                sleep();

                if (tempcounter==2){
                    days++;                                         //increment days
                    avgTempHum();                                   //calculate average temperature and humidity
                    minmaxTempHum();                                //calculate minimum and maximum temperature and humidity
                    getConductivity();                              //get conductivity value from sensor
                    getWaterLevel();                                //get water level from ultrasonic sensor

                    ShiftData();                                    //shift gathered data by offset
                    if ((WaterLevel-OFFSET) >= WATER_THRESHOLD){    //check if water level is too low
                        SMS_data[0]=WARNING_PREFIX;                 //initiate message with warning char
                        SMS_data[1]=WaterLevel;                     //put water level in text message
                        SMS_data[2]=DATA_SUFFIX;                    //end message with suffix

                        GSM_ON();                                   //turn on sim900
                        delay_1s(10);                               //wait for GSM to connect to network
                        SIM900_SEND(1);                             //Send data message to server
                    }
                }
            }
            if (!BatteryCharged()){
                MonitorBattery();
            }
            if (SolarStatus()==0)                                  //if solar-panel is off
                goto OFF;
            goto START;

        }
        else {                                                      //when solar-panel is off
            OFF:
            SaveData();                                             //Sava sensor readings to memory
            tempcounter=0;

            //check if data transmission frequency is met
            if (days >= TRANSMIT_FREQ){
                SMS_data[0]=DATA_PREFIX;                            //start message with prefix
                gatherData();                                       //read data from memory
                getCheckByte();                                     //calculate check byte
                GSM_ON();                                           //turn on sim900
                delay_1s(10);                                       //wait for GSM to connect to network
                SIM900_SEND(1);                                     //Send data message to server
                days=0;
            } //reset days counter only after successful tranmsission

            //sleep for 6h
            for (char z=0; z<3; z++){
                sleep();
            }

            while (SolarStatus()==2){ //if solar-panel is off
                for (char z=0; z<5; z++){
                    delay_1s(60);
                }
                solarcounter++;
                if (solarcounter > SOLAR_THRESHOLD){
                        //turn on Fault LED
                        goto START;
                }
            }
        }

}