void Console::execute( const std::string& line )
{
	std::clog << ">";
	pushLine( line );

	std::string::size_type pos = line.find( ' ' );
	std::string cmd = std::string( line.begin(), pos != std::string::npos ? line.begin() + pos : line.end() );

	auto find = std::find_if( m_cmds.begin(), m_cmds.end(), std::bind( &con::Command::operator==, std::placeholders::_1, cmd ) );

	try
	{
		if ( find == m_cmds.end() )
			throw UnknownCommandException();
		(**find)( *this, parseArguments( pos != std::string::npos ? std::string( line.begin() + pos + 1, line.end() ) : "" ) );
	}
	catch ( std::exception& err )
	{
		*this << con::setcerr << err.what() << con::endl;
	}
}
Esempio n. 2
0
int init(int argc, char **args) {

    puts("Start Server...");
    char *port;
    puts("Parse Arguments from console...");
    if (parseArguments(argc, args, &port) == EXIT_FAILURE)
        return EXIT_FAILURE;

    puts("Initiating connection...");
    if (initConnection(port) == EXIT_FAILURE)
        return EXIT_FAILURE;
        
    if (initPoll() == EXIT_FAILURE) {
        return EXIT_FAILURE;
    }
    
    clientList = clientVector_construct(8);
    printf("Gnuddels-Server started on the port %s!\n", port);

    return EXIT_SUCCESS;
}
Esempio n. 3
0
int main(int argc, char *argv[]) {
    const char* fmuFileName;
    int i;

    // parse command line arguments and load the FMU
    // default arguments value
    double tEnd = 1.0;
    double h=0.1;
    int loggingOn = 0;
    char csv_separator = ',';
    fmi2String *categories = NULL;
    int nCategories = 0;

    parseArguments(argc, argv, &fmuFileName, &tEnd, &h, &loggingOn, &csv_separator, &nCategories, &categories);
    loadFMU(fmuFileName);

  // run the simulation
    printf("FMU Simulator: run '%s' from t=0..%g with step size h=%g, loggingOn=%d, csv separator='%c' ",
            fmuFileName, tEnd, h, loggingOn, csv_separator);
    printf("log categories={ ");
    for (i = 0; i < nCategories; i++) printf("%s ", categories[i]);
    printf("}\n");

    simulate(&fmu, tEnd, h, loggingOn, csv_separator, nCategories, categories);
    printf("CSV file '%s' written\n", RESULT_FILE);

    // release FMU
#ifdef _MSC_VER
    FreeLibrary(fmu.dllHandle);
#else
    dlclose(fmu.dllHandle);
#endif
    freeModelDescription(fmu.modelDescription);
    //if (categories) free(categories);

    // delete temp files obtained by unzipping the FMU
    deleteUnzippedFiles();

    return EXIT_SUCCESS;
}
Esempio n. 4
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    Q_INIT_RESOURCE(bauhaus);

    doStyling(app);

#ifdef Q_WS_X11
    QIcon applicationIcon;
    applicationIcon.addFile(":/16xBauhaus_Log");
    applicationIcon.addFile(":/64xBauhaus_Logo.png");
    applicationIcon.addFile(":/128xBauhaus_Logo.png");
    applicationIcon.addFile(":/256xBauhaus_Logo.png");
    Q_ASSERT(!applicationIcon.isNull());
    app.setWindowIcon(applicationIcon);
#endif

    QCoreApplication::setOrganizationName("Nokia");
    QCoreApplication::setOrganizationDomain("nokia.com");
    QCoreApplication::setApplicationName("Bauhaus");

    try {
        QmlDesigner::IntegrationCore core;
        core.pluginManager()->setPluginPaths(pluginPaths());

        MainWindow mainWindow;
        mainWindow.show();

        parseArguments(app.arguments(), mainWindow);

//        if (mainWindow.documentCount() == 0)
//            mainWindow.showWelcomeScreen();
//
        return app.exec();

    } catch (const QmlDesigner::Exception &exception) {
        qWarning() << exception;
        return -1;
    }
}
Esempio n. 5
0
int main(int argc,  char  *argv[]) {
FILE *f;
extern void initGlobalStructure(void);
extern void setMetaKeyOptions(int swap);
	parseArguments( argv, argc, args);

	if (versionMe) versionMessage(vmPath);
	if (helpMe) helpMessage(vmPath, "!Help");

	atexit(exit_function);   // setup a clean exit function

	InitRiscOS();
	initGlobalStructure();

	dummyWimpPoll();

	/* read the image file and allocate memory for Squeak heap */
	f = fopen(imageName, "rb");
	PRINTF(("\\t Starting Squeak with image file: %s\n", imageName));
	if (f == NULL) {
		/* give a RPC error message if image file is not found */
		extern char VMVersion[];
		privateErr.errnum = (bits)0;
		sprintf(privateErr.errmess, "Could not open the Squeak image file '%s' (Squeak version: %s)", imageName, VMVersion);
		printf("%s\n", privateErr.errmess);
		platReportError((os_error *)&privateErr);
		helpMessage(vmPath, "!ImName");
		ioExit();
	}

	setMetaKeyOptions(swapMeta);

	readImageFromFileHeapSize(f, objectHeadroom);
	fclose(f);

	/* run Squeak */
	PRINTF(("\\t start running image\n"));

	interpret();
}
Esempio n. 6
0
static void
initialize(int argc, char *argv[], int offset) {
	int e, fd;

	parseArguments(argc, argv, offset);

	if (logFile != NULL) {
		fd = open(logFile, O_WRONLY | O_APPEND | O_CREAT, 0644);
		if (fd == -1) {
			e = errno;
			fprintf(stderr, ERROR_PREFIX
				": cannot open log file %s for writing: %s (errno %d)\n",
				logFile, strerror(e), e);
			exit(1);
		}

		if (dup2(fd, 1) == -1) {
			e = errno;
			fprintf(stderr, ERROR_PREFIX ": cannot dup2(%d, 1): %s (errno %d)\n",
				fd, strerror(e), e);
		}
		if (dup2(fd, 2) == -1) {
			e = errno;
			fprintf(stderr, ERROR_PREFIX ": cannot dup2(%d, 2): %s (errno %d)\n",
				fd, strerror(e), e);
		}

		close(fd);
	}

	if (pipe(terminationPipe) == -1) {
		e = errno;
		fprintf(stderr, ERROR_PREFIX ": cannot create a pipe: %s (errno %d)\n",
			strerror(e), e);
		exit(1);
	}

	setNonBlocking(terminationPipe[1]);
}
Esempio n. 7
0
static boolean parseFeature (tokenInfo *const token)
{
	boolean found = FALSE;
	while (readFeatureName (token))
	{
		found = TRUE;
		makeEiffelFeatureTag (token);
		readToken (token);
		if (isType (token, TOKEN_COMMA))
			readToken (token);
	}
	if (found)
	{
		if (isKeyword (token, KEYWORD_alias)) {
			readToken (token);
			if (isType (token, TOKEN_STRING))
				makeEiffelFeatureTag (token);
			readToken (token);
		}
		if (isType (token, TOKEN_OPEN_PAREN))  /* arguments? */
			parseArguments (token);
		if (isType (token, TOKEN_COLON))       /* a query? */
			parseEntityType (token);
		if (isKeyword (token, KEYWORD_assign))
		{
			readToken (token);
			readToken (token);
		}
		if (isKeyword (token, KEYWORD_obsolete))
		{
			readToken (token);
			if (isType (token, TOKEN_STRING))
				readToken (token);
		}
		findFeatureEnd (token);
	}
	return found;
}
Esempio n. 8
0
int main (int argc, char **argv)
{

	bool pass = true;

	static size_t n = 20;
	//static integer q = 65519; problem
	//static integer q = 1009;
	//static integer q = 1000003;
	static integer q = 46337;
	static int iterations = 1;
        static double sparsity = 0.05;

	static Argument args[] = {
		{ 'n', "-n N", "Set dimension of test matrices to NxN.", TYPE_INT,     &n },
		{ 'q', "-q Q", "Operate over the \"field\" GF(Q) [1].", TYPE_INTEGER, &q },
		{ 'i', "-i I", "Perform each test for I iterations.", TYPE_INT,     &iterations },
		{ 's', "-s S", "Sparse matrices with density S.", TYPE_DOUBLE,     &sparsity },
		END_OF_ARGUMENTS
	};

	parseArguments (argc, argv, args);

	srand ((unsigned)time (NULL));
	// srand48 ((unsigned)time (NULL));

	commentator().start("Givaro::Modular<uint32_t,uint64_t> sparse rank test suite", "rank");
	commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (3);
	commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDetailLevel (Commentator::LEVEL_NORMAL);

	Givaro::Modular<uint32_t,uint64_t> F (q);
	pass = pass && testSparseRank(F,n,n+1,(size_t)iterations,sparsity);
	pass = pass && testSparseRank(F,LINBOX_USE_BLACKBOX_THRESHOLD+n,LINBOX_USE_BLACKBOX_THRESHOLD+n-1,(size_t)iterations,sparsity);


	commentator().stop("Givaro::Modular<uint32_t,uint64_t> sparse rank test suite");
	return pass ? 0 : -1;
}
Esempio n. 9
0
int main(int argc, char* argv[]) {
  Matrix matrix;
  /*Read in height and width*/
  parseArguments(argc, argv, &matrix);
  /*Allocate matrix on the heap*/
  initMatrix(&matrix);
  /*Fill with random unsigned chars*/
  fillRandomData(&matrix);
  /*Start timer*/
  double start,mid1, mid2, end;
  start = (double) clock();
  /*Differentiate*/
  int** dx = differentiateX(&matrix);
  mid1 = (double) clock();
  int** dy = differentiateY(&matrix);
  mid2 = (double) clock();
  /*Compute min and max*/
  printf("The max and min for dx are: %d and %d\n", max(dx, matrix.width, matrix.height), min(dx, matrix.width, matrix.height));
  printf("The max and min for dy are: %d and %d\n", max(dy, matrix.width, matrix.height), min(dy, matrix.width, matrix.height));
  /*End timer*/
  end = (double) clock();
  printf("Total time taken: %.4f msec\n", (end-start) / CLOCKS_PER_MSEC);
  printf("dx takes %f, dy takes %f msec\n", (mid1 - start) / CLOCKS_PER_MSEC, (mid2 - mid1) / CLOCKS_PER_MSEC);
  /*Print*/
  /*printMatrix(&matrix);*/
  /*printArray(dx, matrix.width, matrix.height);*/
  /*printArray(dy, matrix.width, matrix.height);*/
  /*Free everything*/
  for (int x = 0; x < matrix.width; x++) {
    free(matrix.data[x]);
    free(dx[x]);
    free(dy[x]);
  }
  free(matrix.data);
  free(dx);
  free(dy);
  return 0;
}
Esempio n. 10
0
int main(int argc, char **argv)
{
	switch (parseArguments(argc, argv))
	{
		case CommandTypes::None:
			return RET_OK;

		case CommandTypes::Invalid:
			return RET_FAIL_ARGS;

		case CommandTypes::Run:
			return Run();

		case CommandTypes::Compile:
		case CommandTypes::CompileNative:
			return Compile();

		case CommandTypes::CompileAndRun:
			return CompileAndRun();
	}

	return RET_OK;
}
Esempio n. 11
0
/*!
    Uses application's arguments (\a appArguments) to initialise
    QWsdl Flags and itself, and \a parent to construct the object.
  */
WsdlConverter::WsdlConverter(const QStringList &appArguments, QObject *parent) :
    QObject(parent)
{
    flags = new Flags();
    argList = new QMap<int, QVariant>();
    // Dummy wsdl to prevent segfaulting when parsing arguments fails.
    wsdl = new QWsdl(this);
    errorState = false;
//    errorMessage = "";

    QString applicationName = qApp->applicationFilePath().mid(
                qApp->applicationDirPath().length() + 1);

    if ((appArguments.length() == 0)
            || (appArguments.contains(QLatin1String("--help")))
            || (appArguments.contains(QLatin1String("-h")))
            || (appArguments.length() == 1
                && (appArguments.at(0) == qApp->applicationFilePath()
                    || appArguments.at(0) == (QLatin1String("./") + applicationName)
                    || appArguments.at(0) == applicationName)
                )) {
        displayHelp();
        return;
    }

    if (!parseArguments(appArguments)) {
        enterErrorState(QLatin1String("Encountered an error when parsing arguments."));
        return;
    }

    baseClassName = argList->value(ClassName).toString();
    outputDir = argList->value(Dir).toString();
    wsdl->setWsdlFile(argList->value(Path).toString());
    if (wsdl->isErrorState())
        enterErrorState(QLatin1String("WSDL error!"));
}
Esempio n. 12
0
int main(int argc, char **argv)
{
    int err;

    parseArguments(argc, argv);

    if (nodaemon == 0) {
        err = daemonise();
        if (err != 0) exit(1);

        err = writePidFile(pidFile);
        if (err != 0) exit(1);
    }

    err = signalisation();
    if (err != 0) exit(1);

    serverSocket = openServerSocket(port);
    if (serverSocket == -1) exit(1);

    request_t req;
    response_t resp;
    output_t output;

    memset(&output, 0, sizeof(output_t));

    while (serverSocket != -1) {

        memset(&req, 0, sizeof(request_t));
        memset(&resp, 0, sizeof(response_t));

        int client = serverSocketAccept(serverSocket);
        if (client == -1)
            continue;


        int r = parseRequest(client, &req, &resp);
        if (r != 0) {
            clientPrintf(client, "HTTP/1.1 %03d\r\n", resp.status);
            closeClient(client);
            continue;
        }

        if (1) {
            printf("path: %s\n", req.path);
            for (int i =0; i < req.num_args; i++)
                printf("arg[%d]: %s = %s\n", i, req.names[i], req.values[i]);
        }

        const char* cmdline = findCommand(req.path);

        if (cmdline == NULL) {
            log_warn("Daemon: Invalid path: '%s'\n", req.path);
            clientPrint(client, "HTTP/1.1 404\r\n");
            closeClient(client);
            continue;
        }

        if (execute(&output, cmdline) != 0) {
            clientPrint(client, "HTTP/1.1 500\r\n"); // Internal server error
            closeClient(client);
            continue;
        }

        if ((output.count > 8) && (strncmp(output.buf, "HTTP/1.1", 8) == 0)) {
            clientWrite(client, output.buf, output.count);
        } else {
            clientPrintf(client, "HTTP/1.1 200\r\nContent-Length: %d\r\n\r\n",
                         output.count);
            clientWrite(client, output.buf, output.count);
        }

        closeClient(client);

        output_clear(&output);
        if (req.path) free(req.path);
    }

    removePidFile(pidFile);

    return 0;
}
Esempio n. 13
0
int main(int argc, char** argv) {
#ifdef _3DS
	UNUSED(_mPerfShutdown);
    gfxInitDefault();
    osSetSpeedupEnable(true);
	consoleInit(GFX_BOTTOM, NULL);
	if (!allocateRomBuffer()) {
		return 1;
	}
#elif defined(__SWITCH__)
	UNUSED(_mPerfShutdown);
	gfxInitDefault();
	consoleInit(NULL);
#else
	signal(SIGINT, _mPerfShutdown);
#endif
	int didFail = 0;

	struct mLogger logger = { .log = _log };
	mLogSetDefaultLogger(&logger);

	struct PerfOpts perfOpts = { false, false, false, 0, 0, 0, false };
	struct mSubParser subparser = {
		.usage = PERF_USAGE,
		.parse = _parsePerfOpts,
		.extraOptions = PERF_OPTIONS,
		.opts = &perfOpts
	};

	struct mArguments args = {};
	bool parsed = parseArguments(&args, argc, argv, &subparser);
	if (!args.fname) {
		parsed = false;
	}
	if (!parsed || args.showHelp) {
		usage(argv[0], PERF_USAGE);
		didFail = !parsed;
		goto cleanup;
	}

	if (args.showVersion) {
		version(argv[0]);
		goto cleanup;
	}

	if (perfOpts.savestate) {
		_savestate = VFileOpen(perfOpts.savestate, O_RDONLY);
		free(perfOpts.savestate);
	}

	_outputBuffer = malloc(256 * 256 * 4);
	if (perfOpts.csv) {
		puts("game_code,frames,duration,renderer");
	}
	if (perfOpts.server) {
		didFail = !_mPerfRunServer(args.fname, &args, &perfOpts);
	} else {
		didFail = !_mPerfRunCore(args.fname, &args, &perfOpts);
	}
	free(_outputBuffer);

	if (_savestate) {
		_savestate->close(_savestate);
	}
	cleanup:
	freeArguments(&args);

#ifdef _3DS
	gfxExit();
	acExit();
#elif defined(__SWITCH__)
	gfxExit();
#endif

	return didFail;
}
Esempio n. 14
0
/* Функция компиляци
 * Осуществляется как проверки, так и вызовв других
 * функций для проверок или преобразваний.
 * Проверки на правельность написания мнемокода ассамблера
 * и заменна мнемокода на коды команд, так же замена символов
 * адресации на коды адресации, и также меток на их дресса
 * - Входные данные: исходные мнемокод ассамблера с виджета
 * - Выходные данные: записать данных в ячейки ОЗУ сформированных
 * во время выполнения функции
 */
void Compiler::exec(QString &strSource)
{
  if(strSource.isEmpty()) return;
  QTime startTime = QTime::currentTime();

  strSource = parseLabel(strSource);
  QStringList slCommandPair = strSource.split(" ");

  mBar->setStyleSheet("QProgressBar {border: 1px solid rgb(83, 83, 83);background-color: rgb(38, 40, 41);border-radius: 5px;} QProgressBar::chunk {background-color: rgb(64, 66, 68);width: 20px; }");
  mBar->setMaximum(slCommandPair.size() - 1);
  mBar->setValue(0);

  QStringList debugList;
  QString isRegistr, strCode, strCmd, strArg = "000", typeAdrr = "0",
          debugArg = " ", debugCmd = " ", resParseCmd = "", error = "";

  int indexCmd = 0;
  for(int i = 0; i < slCommandPair.size(); i ++, mBar->setValue(i)) {
    strCmd = slCommandPair.at(i);
    debugCmd = slCommandPair.at(i);
    strCmd = strCmd.toLower();
    resParseCmd = parseSpecialCommand(strCmd,
                                      i + 1 < slCommandPair.size() ?
                                      slCommandPair.at(i + 1) : " ",
                                      error);
    qDebug() <<"ParseCmd: " << resParseCmd;
    if(resParseCmd != "-1" && error.isEmpty()) {
      mMemory->set(indexCmd, resParseCmd);
      debugList.append(strCmd);
      indexCmd ++;
    } else if(!error.isEmpty()) {
      fireError(error, indexCmd); return;
    } else {
      if(i < slCommandPair.size()) {
        if(i + 1 < slCommandPair.size()) {
          isRegistr = slCommandPair.at(i + 1);
          strCode = isRegistr.contains('r') || isRegistr.contains('R') ?
                    mGenCode->getCode(strCmd + "R") : mGenCode->getCode(strCmd);
        } else {
          fireError("нет аргумента для команды: " +  strCmd, indexCmd); return;
        }
      } else {
        fireError("нет аргумента для команды: " +  strCmd, indexCmd); return;
      }

      if(strCode != "-1") {
        if((i + 1) < slCommandPair.size() ) {
          if(mGenCode->getCode(slCommandPair.at(i + 1)) == "-1") {
            i ++;
            strArg = slCommandPair.at(i); debugArg = strArg;
            parseArguments(strArg, typeAdrr);
          } else {
            fireError("не верный аргумент команды: " +  strCmd, indexCmd); return;
          }
        } else {
          fireError("нет аргумента для команды: " +  strCmd, indexCmd); return;
        }

        while(strArg.size() < 3) strArg.push_front("0");
        strArg = strArg.replace('r', '0');

        debugList.append(debugCmd + " " + debugArg);
        mMemory->set(indexCmd, strCode + typeAdrr + strArg);
        indexCmd ++;
      } else {
        if(out) {
          fireError(" не верная команда", indexCmd);return;
        }
      }
    }
  }
  updateLog(startTime);
  mDpanel->updateCode(debugList);
}
Esempio n. 15
0
int main(int argc, char** argv) {
  std::cout << std::endl;
  
  char* ref = NULL;

  // Important NOT invert (init requires argument to be parsed)
  parseArguments(argc,argv);
  initSimulator();

  
  size_t N = Options::opts.N;
  size_t m = Options::opts.m;
  size_t M = Options::opts.M;
  size_t Nbar = N - m + 1;
  double pe = Options::opts.pe; 
  std::cout << std::endl;
  
  std::cout << "\t\t+++++  Starting simulation +++++ \n\n";  
  std::cout << "* Reference generation... ";
  ref = new char[N];
  generateIIDGenome(N,ref);
  std::string s(ref);
  std::cout << "[OK]" << std::endl;

  std::cout << "* Read generation... ";
  std::priority_queue<Read> reads;
  generateOfflineReads(s, reads);
  std::cout << "[OK]" << std::endl;

  std::cout << "* Processing reads... ";

  Read r1 = reads.top();
  reads.pop();
  while(!reads.empty()) {
    Read r2 = reads.top();
    reads.pop();
    size_t s = m - (r2.j - r1.j);
    evaluateChainRelation(r1, r2, s);
    int dh = -1;
    if (s <= m) {
      dh = prefixSuffixHammingDistance(r2.r, r1.r, s);
    } else {
      addNonOverlapRecord(r2.j - r1.j - m);
    }
    r1 = r2;
  }

  std::cout << "[OK]" << std::endl;

  
  std::cout << "* Cleaning... ";
  delete[] ref;
  std::cout << "\n\n";
  //  printChainMatrix();
  //printNonOverlapDistribution();
  printFalsePositiveMatrix();
  clearSimulator();
  std::cout << "[OK]" << std::endl;

  
  std::cout << std::endl;
  return 0;
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
	int pid = -1; //PID 
	float temp = 0; //inital temperature from command line
	float downTemp = 0;
	float parentTemp = 0;
	float upTemp = 0;
	//parses command line arguments and updates pid and initial temperature/exits on fail
	if(!getArgumentValues(parseArguments(argc, argv), pid, temp)) exit(0);
	
	mqd_t mqueue; /*message queue*/
	mqd_t parent;
	mqd_t child_1;
	mqd_t child_2;
	struct mq_attr ma;
	ma.mq_flags = 0;
	ma.mq_maxmsg = 10;
	ma.mq_msgsize = 33;
	ma.mq_curmsgs = 0;

	float child1Value;
	float child2Value;
	//sendFloat(mqueue, temp);
			//qout << receiveFloat(mqueue);
			//mq_close(mqueue);
			//mq_unlink(P0);
	switch(pid){
		case 0:
		{
			mqueue = openMailbox(P0, ma);
			child_1 = openMailbox(P1, ma);
			child_2 = openMailbox(P2, ma);
			sendFloat(child_1, temp, 0.0); //false flags as sent down
			sendFloat(child_2, temp, 0.0);
			break;
		}
		case 1:
			parent = openMailbox(P0, ma);
			mqueue = openMailbox(P1, ma);
			child_1 = openMailbox(P3, ma);
			child_2 = openMailbox(P4, ma);
			break;
		case 2:
			parent = openMailbox(P0, ma);
			mqueue = openMailbox(P2, ma);
			child_1 = openMailbox(P5, ma);
			child_2 = openMailbox(P6, ma);
			break;
		case 3:
			parent = openMailbox(P1, ma);
			mqueue = openMailbox(P3, ma);
			break;
		case 4:
			parent = openMailbox(P1, ma);
			mqueue = openMailbox(P4, ma);
			break;
		case 5:
			parent = openMailbox(P2, ma);
			mqueue = openMailbox(P5, ma);
			break;
		case 6:
			parent = openMailbox(P2, ma);
			mqueue = openMailbox(P6, ma);
			break;
	}


	bool isStable = false;
	while(!isStable)
	{
		if(pid == 0)
		{
			if(numMessages(mqueue) > 1)
			{
				float cPid = 10;
				float c2Pid = 10;
				float child1Value = receiveFloat(mqueue, cPid);
				float child2Value = receiveFloat(mqueue, c2Pid);
				upTemp = (temp + child1Value + child2Value)/3.0;
				qout << "Process " << pid << " current temperature " << upTemp << endl;
				if(qAbs(upTemp - temp) <= .01)
				{
					temp = upTemp;
					isStable = true;
					sendFloat(child_1, temp, 20);
					sendFloat(child_2, temp, 20);
				}
				else
				{
					temp = upTemp;
					sendFloat(child_1, temp, pid);
					sendFloat(child_2, temp, pid);
				}
			}

		}
		if(pid == 1 || pid == 2)
		{	
			if(hasMessages(mqueue))
			{
				float rPid = 10;
				float value = receiveFloat(mqueue, rPid);
				if(rPid == 20)
				{
					isStable = true;
					sendFloat(child_1, temp, 20);
					sendFloat(child_1, temp, 20);
				}

				else if(rPid == 0)
				{
					float downTemp = (temp + value)/2.0;
					temp = downTemp;
					sendFloat(child_1, downTemp, pid);
					sendFloat(child_2, downTemp, pid);
				}

				else if(rPid == 3 || rPid == 4 || rPid == 5 || rPid == 6)
				{
					float child1_value = value;
					float sPid = 10;
					float child2_value = receiveFloat(mqueue, sPid);
					if(sPid == 3 || sPid == 4 || sPid == 5 || sPid == 6)
					{
						upTemp = (temp + child1_value + child2_value)/3.0;
						temp = upTemp;
						qout << "Process " << pid << " current temperature " << upTemp << endl;
						sendFloat(parent, upTemp, pid);
					}
				}

			}
		}

		if(pid == 3 || pid == 4 || pid == 5 || pid ==6)	
		{
			if(hasMessages(mqueue))
			{
				float rPid;
				parentTemp = receiveFloat(mqueue, rPid);
				if(rPid == 20)
				{
					isStable = true;
				}
				else
				{
					downTemp = (temp + parentTemp)/2.0;
					temp = downTemp;
					sendFloat(parent, downTemp, pid); //true flags it as sent up 
					qout << "Process " << pid << " current temperature " << downTemp << endl;
				}
			}
		}
	}

	qout << "Process " << pid << " final temperature " << temp << endl;
	
	mq_close(parent);
	mq_close(child_1);
	mq_close(child_2);
	mq_close(mqueue);

	mq_unlink(P0);
	mq_unlink(P1);
	mq_unlink(P2);
	mq_unlink(P3);
	mq_unlink(P4);
	mq_unlink(P5);
	mq_unlink(P6);

	return 0;

} /*end main()*/
Esempio n. 17
0
k_Quantifier::k_Quantifier(QStringList& ak_Arguments, QSet<r_Parameter::Enumeration> ak_Parameters, QString as_ProgramName, QString as_AdditionalArguments)
    : k_QuantifierBase(ak_Arguments, ak_Parameters, as_ProgramName, as_AdditionalArguments)
{
    parseArguments(ak_Arguments);
}
Esempio n. 18
0
int main(int argc, char **argv)
{
	bool keepGoing = true;

	srand(time(NULL)); //seed random generator

	parseArguments(argc, argv);

	allocWorld();
	fillWorld();
	
	Timer renderTimer = makeTimer(1.0 / config.framerate);

	if (config.render)
		initRender();

	if (config.measureSamples < 0) {
		/* Loop forever, or until the user quits the renderer */
		while (stepSimulation(&renderTimer));
	} else {
		printf("Waiting for system to relax.\n");
		for (double t = 0; keepGoing && t < config.measureWait; t += config.timeStep) {
			keepGoing = stepSimulation(&renderTimer);
			if (fmod(t, config.measureWait / 100) < config.timeStep) {
				printf("\rRelax time %13f of %f",
						(t + config.measureWait/100) / TIME_FACTOR, 
						config.measureWait / TIME_FACTOR);
				fflush(stdout);
			}
		}

		/* Perform the measurements */
		printf("\nStarting measurement.\n");
		FILE *outstream = fopen(DATA_FILE_NAME, "w");
		//plotHeader(outstream);
		double intervalTime = 0;
		for (long sample = 0; keepGoing && sample < config.measureSamples; sample++) {
			while (keepGoing && intervalTime <= config.measureInterval) {
				keepGoing = stepSimulation(&renderTimer);
				intervalTime += config.timeStep;
			}
			if (!keepGoing)
				break;

			/* Check for numerical drift (or bugs) before 
			 * commiting measurement. */
			if (!physicsCheck())
				die("You broke physics!\n");

			dumpEnergies(outstream);
			printf("\rMeasured sample %ld/%ld", sample + 1, config.measureSamples);
			fflush(stdout);
			intervalTime -= config.measureInterval;
		}
		printf("\n");
		fclose(outstream);
	}

	freeWorld();
	return 0;
}
Esempio n. 19
0
ArgumentParser::ArgumentParser(int argc, char * argv[])
	: ArgumentCollection() {
	parseArguments(argc, argv);
}
Esempio n. 20
0
PageRunner::PageRunner(const QStringList& args)
    : QWebPage(0),
      out(stdout),
      err(stderr),
      view(new QWidget()) {

    QMap<QString, QString> settings = parseArguments(args);
    QStringList arguments = args.mid(settings.size() * 2);
    exportpdf = settings.value("export-pdf");
    exportpng = settings.value("export-png");
    url = QUrl(arguments[0]);
    nativeio = new NativeIO(this, QFileInfo(arguments[0]).dir(),
                            QDir::current());
    if (url.scheme() == "file" || url.isRelative()) {
        QFileInfo info(arguments[0]);
        url = QUrl::fromLocalFile(info.absoluteFilePath());
        if (!info.isReadable() || !info.isFile()) {
            QTextStream err(stderr);
            err << "Cannot read file '" + url.toString() + "'.\n";
            qApp->exit(1);
        }
    }
    nam = new NAM(this, QUrl(url).host(), QUrl(url).port());

    setNetworkAccessManager(nam);
    connect(this, SIGNAL(loadFinished(bool)), this, SLOT(finished(bool)));
    connect(mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            this, SLOT(slotInitWindowObjects()));
    sawJSError = false;

    setView(view);
    scriptMode = arguments[0].endsWith(".js");
    if (scriptMode) {
        QByteArray html = "'" + arguments[0].toUtf8().replace('\'', "\\'")
                + "'";
        for (int i = 1; i < arguments.length(); ++i) {
            html += ",'" + arguments[i].toUtf8().replace('\'', "\\'") + "'";
        }
        html = "<html>"
                "<head><title></title>"
                "<script>var arguments=[" + html + "];</script>"
                "<script src=\"" + QUrl::fromLocalFile(arguments[0]).toEncoded() + "\"></script>";
        // add runtime modification
        html += "<script>//<![CDATA[\n" + getRuntimeBindings() +
             "if (typeof(runtime) !== 'undefined' && typeof(nativeio) !== 'undefined') {\n"
             "    runtime.libraryPaths = function () {"
             "        /* convert to javascript array */"
             "        var p = nativeio.libraryPaths(),"
             "            a = [], i;"
             "        for (i in p) { a[i] = p[i]; }"
             "        return a;"
             "    };}//]]></script>";
        html += "</head><body></body></html>\n";
        QTemporaryFile tmp("XXXXXX.html");
        tmp.setAutoRemove(true);
        tmp.open();
        tmp.write(html);
        tmp.close();
        QFileInfo info(tmp.fileName());
        mainFrame()->load(QUrl::fromLocalFile(info.absoluteFilePath()));
    } else {
        // Make the url absolute. If it is not done here, QWebFrame will do
        // it, and it will lose the query and fragment part.
        QUrl absurl;
        if (url.isRelative()) {
            absurl = QUrl::fromLocalFile(QFileInfo(url.toLocalFile()).absoluteFilePath());
            absurl.setQuery(url.query());
            absurl.setFragment(url.fragment());
        } else {
            absurl = url;
        }
        mainFrame()->load(absurl);
    }
}
Esempio n. 21
0
    bool ExprParser::parseKeyword (int keyword, const TokenLoc& loc, Scanner& scanner)
    {
        if (const Extensions *extensions = getContext().getExtensions())
        {
            std::string argumentType; // ignored
            bool hasExplicit = false; // ignored
            if (extensions->isInstruction (keyword, argumentType, hasExplicit))
            {
                // pretend this is not a keyword
                return parseName (loc.mLiteral, loc, scanner);
            }
        }

        if (keyword==Scanner::K_end || keyword==Scanner::K_begin ||
            keyword==Scanner::K_short || keyword==Scanner::K_long ||
            keyword==Scanner::K_float || keyword==Scanner::K_if ||
            keyword==Scanner::K_endif || keyword==Scanner::K_else ||
            keyword==Scanner::K_elseif || keyword==Scanner::K_while ||
            keyword==Scanner::K_endwhile || keyword==Scanner::K_return ||
            keyword==Scanner::K_messagebox || keyword==Scanner::K_set ||
            keyword==Scanner::K_to || keyword==Scanner::K_startscript ||
            keyword==Scanner::K_stopscript || keyword==Scanner::K_enable ||
            keyword==Scanner::K_disable)
        {
            return parseName (loc.mLiteral, loc, scanner);
        }

        mFirst = false;

        if (!mExplicit.empty())
        {
            if (mRefOp && mNextOperand)
            {
                if (keyword==Scanner::K_getdisabled)
                {
                    start();

                    mTokenLoc = loc;

                    Generator::getDisabled (mCode, mLiterals, mExplicit);
                    mOperands.push_back ('l');
                    mExplicit.clear();
                    mRefOp = false;

                    mNextOperand = false;
                    return true;
                }
                else if (keyword==Scanner::K_getdistance)
                {
                    start();

                    mTokenLoc = loc;
                    parseArguments ("c", scanner);

                    Generator::getDistance (mCode, mLiterals, mExplicit);
                    mOperands.push_back ('f');
                    mExplicit.clear();
                    mRefOp = false;

                    mNextOperand = false;
                    return true;
                }

                // check for custom extensions
                if (const Extensions *extensions = getContext().getExtensions())
                {
                    char returnType;
                    std::string argumentType;

                    bool hasExplicit = true;
                    if (extensions->isFunction (keyword, returnType, argumentType, hasExplicit))
                    {
                        if (!hasExplicit)
                        {
                            getErrorHandler().warning ("stray explicit reference (ignoring it)", loc);
                            mExplicit.clear();
                        }

                        start();

                        mTokenLoc = loc;
                        int optionals = parseArguments (argumentType, scanner);

                        extensions->generateFunctionCode (keyword, mCode, mLiterals, mExplicit,
                            optionals);
                        mOperands.push_back (returnType);
                        mExplicit.clear();
                        mRefOp = false;

                        mNextOperand = false;
                        return true;
                    }
                }
            }

            return Parser::parseKeyword (keyword, loc, scanner);
        }

        if (mNextOperand)
        {
            if (keyword==Scanner::K_getsquareroot)
            {
                start();

                mTokenLoc = loc;
                parseArguments ("f", scanner);

                Generator::squareRoot (mCode);
                mOperands.push_back ('f');

                mNextOperand = false;
                return true;
            }
            else if (keyword==Scanner::K_menumode)
            {
                start();

                mTokenLoc = loc;

                Generator::menuMode (mCode);
                mOperands.push_back ('l');

                mNextOperand = false;
                return true;
            }
            else if (keyword==Scanner::K_random)
            {
                start();

                mTokenLoc = loc;
                parseArguments ("l", scanner);

                Generator::random (mCode);
                mOperands.push_back ('l');

                mNextOperand = false;
                return true;
            }
            else if (keyword==Scanner::K_scriptrunning)
            {
                start();

                mTokenLoc = loc;
                parseArguments ("c", scanner);

                Generator::scriptRunning (mCode);
                mOperands.push_back ('l');

                mNextOperand = false;
                return true;
            }
            else if (keyword==Scanner::K_getdistance)
            {
                start();

                mTokenLoc = loc;
                parseArguments ("c", scanner);

                Generator::getDistance (mCode, mLiterals, "");
                mOperands.push_back ('f');

                mNextOperand = false;
                return true;
            }
            else if (keyword==Scanner::K_getsecondspassed)
            {
                start();

                mTokenLoc = loc;

                Generator::getSecondsPassed (mCode);
                mOperands.push_back ('f');

                mNextOperand = false;
                return true;
            }
            else if (keyword==Scanner::K_getdisabled)
            {
                start();

                mTokenLoc = loc;

                Generator::getDisabled (mCode, mLiterals, "");
                mOperands.push_back ('l');

                mNextOperand = false;
                return true;
            }
            else
            {
                // check for custom extensions
                if (const Extensions *extensions = getContext().getExtensions())
                {
                    start();

                    char returnType;
                    std::string argumentType;

                    bool hasExplicit = false;

                    if (extensions->isFunction (keyword, returnType, argumentType, hasExplicit))
                    {
                        mTokenLoc = loc;
                        int optionals = parseArguments (argumentType, scanner);

                        extensions->generateFunctionCode (keyword, mCode, mLiterals, "", optionals);
                        mOperands.push_back (returnType);

                        mNextOperand = false;
                        return true;
                    }
                }
            }
        }
        else
        {
            // no comma was used between arguments
            scanner.putbackKeyword (keyword, loc);
            return false;
        }

        return Parser::parseKeyword (keyword, loc, scanner);
    }
Esempio n. 22
0
/** Constructor. Parses the command-line arguments, resets Rshare's
 * configuration (if requested), and sets up the GUI style and language
 * translation. */
Rshare::Rshare(QStringList args, int &argc, char **argv, const QString &dir)
: QApplication(argc, argv)
{
  mStartupTime = QDateTime::currentDateTime();

#if QT_VERSION >= QT_VERSION_CHECK (5, 0, 0)
  qInstallMessageHandler(qt_msg_handler);
#else
  qInstallMsgHandler(qt_msg_handler);
#endif

#ifndef __APPLE__

  /* set default window icon */
  setWindowIcon(QIcon(":/icons/logo_128.png"));

#endif

  mBlink = true;
  QTimer *timer = new QTimer(this);
  timer->setInterval(500);
  connect(timer, SIGNAL(timeout()), this, SLOT(blinkTimer()));
  timer->start();

  timer = new QTimer(this);
  timer->setInterval(60000);
  connect(timer, SIGNAL(timeout()), this, SIGNAL(minuteTick()));
  timer->start();

  /* Read in all our command-line arguments. */
  parseArguments(args);

  /* Check if we're supposed to reset our config before proceeding. */
  if (_args.contains(ARG_RESET)) {
    Settings->reset();
  }
  
  /* Handle the -loglevel and -logfile options. */
  if (_args.contains(ARG_LOGFILE))
    _log.open(_args.value(ARG_LOGFILE));
  if (_args.contains(ARG_LOGLEVEL)) {
    _log.setLogLevel(Log::stringToLogLevel(
                      _args.value(ARG_LOGLEVEL)));
    if (!_args.contains(ARG_LOGFILE))
      _log.open(stdout);
  }
  if (!_args.contains(ARG_LOGLEVEL) && 
      !_args.contains(ARG_LOGFILE))
    _log.setLogLevel(Log::Off);

  /* config directory */
  useConfigDir = false;
  if (dir != "")
  {
  	setConfigDirectory(dir);
  }

  /** Initialize support for language translations. */
  //LanguageSupport::initialize();

  resetLanguageAndStyle();

  /* Switch off auto shutdown */
  setQuitOnLastWindowClosed ( false );

	/* Initialize GxsIdDetails */
	GxsIdDetails::initialize();
}
Esempio n. 23
0
int main (int argc, char **argv) {
	struct config c = parseArguments(argc, argv);
	if (c.error)
		return 0;

	std::cout << "Starting uEye camera demo..." << std::endl;
	//std::cout << "Test message:" << std::endl;

	std::cout << "Getting number of cameras" << std::endl;
	time_point start = Clock::now();
	INT nCam = CameraImpl::getNumberOfCameras();
	printTime(start, Clock::now());
	std::cout << nCam << " connected camera(s) founded." << std::endl;
	std::cout << "Getting the list of available cameras" << std::endl;
	start = Clock::now();
	UEYE_CAMERA_LIST* cams = CameraImpl::getCameraList(nCam);
	printTime(start, Clock::now());
	HIDS hCam = 0;
	for (INT i = 0; i < cams->dwCount; i++) {
		std::cout << "Frame: Camera[" << i << "] ID is " << cams->uci[i].dwCameraID << std::endl;
	}
	if (cams->dwCount > 0) {
		hCam = cams->uci[0].dwCameraID;
	}
	delete[] cams;
	std::cout << std::endl;

	CameraImpl cam(hCam); //call the camera implementation
	cam.start(false);
	if (cam.getCameraState() != CameraImpl::START) {
		return 1;
	}

	std::cout << "Frame: Configuring camera" << std::endl;
	start = Clock::now();
	cam.config(); //do the configuration of the camera 

	if (c.pixel != -1) {
		cam.setPixelClock(c.pixel); // set the pixel clock
	}
	if (c.exposure != -1) {
		cam.setExposureTime(c.exposure); // set the exposure time
	}
	if (c.aoi[0] != -1) {
		CameraImpl::AreaOfInterest aoi;
		for (int i = 0; i < 4; i++) {
			aoi[i] = c.aoi[i];
		}
		cam.setLogicalAOI(aoi); // set the area of interest
	}
	cam.resume();  // sets Camera state to READY and Software trigger to on
	usleep(4000000);
       
	printTime(start, Clock::now());
		

	start = Clock::now();
	cam.allocImage(); // Allocate image buffer

	printTime(start, Clock::now());
	std::cout << std::endl;

 	//double starttemp = 0; //warmup loop
	double finaltemp = 0;
	double currenttemp = 0;
	int nt = 15;//number of times the temperature must be the same
	double reftemp_arr[nt];//Contains the last temperature values
	double reftemp = 0;//The stable temperature
	//starttemp = cam.getTempCels();

	cam.resetImage();

	std::cout << "The initial temperature is " << cam.getTempCels() << " Celsius. Heating."<< std::endl;
	cam.printPixelClockList();
	//cam.setExposureTime(1);
	cam.setPixelClock(216);
	usleep(4000000);//ns
	std::cout << "Setting pixel clock to 216" <<  std::endl;
        //Make a loop heating at least nt times. If the temperature is the same nt times it will be adjusted at that value
        for (int aux =0; aux<nt; aux++){//Just the first nt times. Save these values
        	cam.takeImage();
		reftemp_arr [aux] = cam.getTempCels();
		std::cout << "The temperature is " << reftemp_arr [aux] << " Celsius. Heating." << std::endl;
        }
	currenttemp = reftemp_arr[nt-1];
	while (currenttemp >  reftemp_arr[0]){//warmup loop. If the current temperature is higher than the reference (nt values ago), go heating. If they are equal, stop.
			cam.takeImage();
			currenttemp = cam.getTempCels();
			std::cout << "The temperature is " << currenttemp << " Celsius. Heating." << std::endl;
  			memmove(reftemp_arr,reftemp_arr+1,sizeof(double)*(nt-1));//Shift to the left
  			reftemp_arr[nt-1]=currenttemp;//Last measured value
			//compare with the previous values, update them as the loops go forward
			//if these values are similar (or in a little range?), the stability was reached
			//in that case stop the warm-up loop
		}
	reftemp = currenttemp;
	std::cout << "The stable temperature is " << reftemp << " Celsius." << std::endl;
	// Back to the "normal" pixel clock
	cam.setPixelClock(c.pixel);
	std::cout << "Frame: The pixel clock is " << cam.getPixelClock() << " Hz" << std::endl;
	cam.setExposureTime(c.exposure);
	std::cout << "Frame: The exposure time is " << cam.getExposureTime() << " ms" << std::endl;
	
    for (int j = 0; j < c.blocks; j++) { //open loop over all frame blocks
	
	std::cout << "Exposing block " << j << " of " << c.blocks << std::endl;
	//std::cout << "Saving " << c.frames << " images" << std::endl;
	std::cout << "The temperature is " << cam.getTempCels() << " Celsius" << std::endl;
	start = Clock::now();

        
	std::cout << "The pixel clock is " << cam.getPixelClock() << " Hz" << std::endl;
	if (cam.getTempCels() <  reftemp){
		std::cout << "The current temperature is " << cam.getTempCels() << " Celsius, this is smaller than " << reftemp  << " Celsius" << std::endl;
		//cam.printPixelClockList();
		//cam.setExposureTime(1);
		cam.setPixelClock(432);
		std::cout << "The pixel clock is " << cam.getPixelClock() << " Hz" << std::endl;
		usleep(4000000);//ns
		std::cout << "Setting pixel clock to 432" <<  std::endl;
		while (cam.getTempCels() <  reftemp){//warmup loop
			cam.allocImage(); // Allocate image buffer and sets an image memory active
			cam.resetImage();
			cam.takeImage();
			cam.freeImage();
			std::cout << "The temperature is " << cam.getTempCels() << " Celsius" << std::endl;
		}
	cam.setPixelClock(c.pixel);
	std::cout << "The pixel clock is " << cam.getPixelClock() << " Hz" << std::endl;
	std::cout << "The exposure time is " << cam.getExposureTime() << " ms" << std::endl;	
	//cam.setExposureTime(c.exposure);

	}

	//for (int m = 1; m < 2 ; m++) {// loop for the three colors
	//			std::cout << "Going for the colors " << m << std::endl;

	cam.allocImage(); // Allocate image buffer and sets an image memory active
	cam.resetImage(); //clean the memory to take a new image 

	cam.setPixelClock(c.pixel);
	std::cout << "Frame:The pixel clock is " << cam.getPixelClock() << " Hz" << std::endl;
	std::cout << "Frame:The exposure time is " << cam.getExposureTime() << " ms" << std::endl;		
	//cam.setExposureTime(c.exposure);
	usleep(4000000);//ns

		//if (m == 1) {
			//CameraImpl::HardwareGains g = {100, 100, 0, 0}; // change gains to blue
			//CameraImpl::HardwareGains g = {100, 0, 0, 0}; // change gains to all three colors
			//CameraImpl::HardwareGains g = {100, 22, 0, 22}; // change gains to all three colors

			//cam.setHardwareGains(g);
			std::ostringstream oss;
			//oss << c.filename << j << "blue.jpg";	
			//oss << c.filename << j << "three_col.jpg";	
			//oss << c.filename << j << "three_col.png";	

			//std::cout << "Filename is " << oss.str() << std::endl;
			cam.setFileName(oss.str());
		//}
	//	if (m == 2) {
	//		CameraImpl::HardwareGains g = {100, 0, 100, 0}; // change gains to green
	//		cam.setHardwareGains(g);
	//		std::ostringstream oss;
	//		oss << c.filename << j << "green.jpg";	
	//		std::cout << "Filename is " << oss.str() << std::endl;
	//		cam.setFileName(oss.str());
	//	}
	//	if (m == 3) {
	//		CameraImpl::HardwareGains g = {100, 0, 0, 100}; // change gains to red
	//		cam.setHardwareGains(g);
	//		std::ostringstream oss;
	//		oss << c.filename << j << "red.jpg";	
	//		std::cout << "Filename is " << oss.str() << std::endl;
	//		cam.setFileName(oss.str());
	//	}
	//		std::cout << "Going for the frames " << std::endl;

		for (int i = 0; i < c.frames; i++) { //take c.frames images for averaging
			//oss << i;
			cam.takeImage();
			//cam.saveImage();
			cam.addImage();
		}
		cam.averageImage(c.frames);

		//create a string for the filname including the image-block number
		//std::ostringstream oss;
		oss << c.filename << j << ".fits";	
		std::cout << "Filename is " << oss.str() << std::endl;
		cam.setFileName(oss.str());
	
	
	
		//save the image
		//cam.saveImages(); //needs a parameter
		//cam.saveImage(1); //Save the image in .jpg or .png
		cam.saveFitsImage(); 

	
	
	

		//convert the image, if wished
		if (c.bmp) {
			cam.convertImage(std::string(".bmp"));
		}
		if (c.jpg) {
			cam.convertImage(std::string(".jpg"));
		}
		if (c.sex) {
			cam.runSExtractor();
		}

		printTime(start, Clock::now());
		std::cout << std::endl;

		cam.freeImage(); // releases the image memory. Does it also globally unlock the memory?
		
		//} //close the loop for the different colors	

		std::cout << "Please press enter " << std::endl;
		std::cin.ignore();
	
	} //close the loop for the frame blocks
	
	std::cout << "Releasing image buffer" << std::endl;
	start = Clock::now();
	//cam.freeImage(); // clean the image memory
	printTime(start, Clock::now());

	

	start = Clock::now();
	cam.pause();
	printTime(start, Clock::now());

	start = Clock::now();
	cam.reset();
	printTime(start, Clock::now());

	start = Clock::now();
	cam.stop();
	printTime(start, Clock::now());

	return 0;
}
Esempio n. 24
0
int main(int argc, char* argv[])
{
	int 		status;
	int 		ch;

	const char 	*progname;
	char*		val 	= new char[255];
	
	gpioSetup* 	setup 	= new gpioSetup;

	// reset gpio setup and set defaults
	initGpioSetup(setup);

	setup->verbose 		= FASTGPIO_DEFAULT_VERBOSITY;
	setup->debug 		= FASTGPIO_DEFAULT_DEBUG;

	// save the program name
	progname = argv[0];	


	//// parse the option arguments
	while ((ch = getopt(argc, argv, "vqud")) != -1) {
		switch (ch) {
		case 'v':
			// verbose output
			setup->verbose = FASTGPIO_VERBOSITY_ALL;
			break;
		case 'q':
			// quiet output
			setup->verbose = FASTGPIO_VERBOSITY_QUIET;
			break;
		case 'u':
			// ubus output
			setup->verbose = FASTGPIO_VERBOSITY_JSON;
			break;
		case 'd':
			// debug mode
			setup->debug 	= 1;
			break;
		default:
			usage(progname);
			return 0;
		}
	}

	// advance past the option arguments
	argc 	-= optind;
	argv	+= optind;

	// parse the arguments
	if (parseArguments(progname, argc, argv, setup) == EXIT_FAILURE) {
		return EXIT_FAILURE;
	}


	// check for any pwm processes already running on this pin
	status = checkOldProcess(setup);


	// run the command
	if (setup->cmd != GPIO_CMD_PWM) {
		// single gpio command
		status = gpioRun(setup);
	}
	else {
		//// continuous gpio commands, need another process

		// create the new process
		pid_t pid = fork();

		if (pid == 0) {
			// child process, run the pwm
			status = pwmRun(setup);
		}
		else {
			// parent process
			if (FASTGPIO_VERBOSE > 0) printf("Launched child pwm process, pid: %d \n", pid);
			noteChildPid(setup->pinNumber, pid);

			if ( setup->verbose == FASTGPIO_VERBOSITY_JSON ) {
				sprintf(val, "%dHz with %d%% duty", setup->pwmFreq, setup->pwmDuty);
				printf(FASTGPIO_JSON_STRING, setup->cmdString, setup->pinNumber, val);
			}
		}
	}


	// clean-up
	delete 	val;
	delete 	setup;

	return 0;
}
Esempio n. 25
0
 int ExprParser::parseArguments (const std::string& arguments, Scanner& scanner)
 {
     return parseArguments (arguments, scanner, mCode);
 }
Esempio n. 26
0
 virtual void run(std::string notParsedArgs) {
   std::vector<std::string> parsedArgs = parseArguments(notParsedArgs);
   if (checkNumberOfArguments(parsedArgs.size(), 1, out)) {
     manager.run(atoi(parsedArgs[0].c_str()));
   }
 }
Esempio n. 27
0
int main(int argc, char *argv[])
{
    float *h_psum;					// vector to hold partial sum
    int in_nsteps = INSTEPS;		// default number of steps (updated later to device prefereable)
    int niters = ITERS;				// number of iterations
    int nsteps;
    float step_size;
    ::size_t nwork_groups;
    ::size_t max_size, work_group_size = 8;
    float pi_res;

    cl::Buffer d_partial_sums;

    try
    {
        cl_uint deviceIndex = 0;
        parseArguments(argc, argv, &deviceIndex);

        // Get list of devices
        std::vector<cl::Device> devices;
        unsigned numDevices = getDeviceList(devices);

        // Check device index in range
        if (deviceIndex >= numDevices)
        {
          std::cout << "Invalid device index (try '--list')\n";
          return EXIT_FAILURE;
        }

        cl::Device device = devices[deviceIndex];

        std::string name;
        getDeviceName(device, name);
        std::cout << "\nUsing OpenCL device: " << name << "\n";

        std::vector<cl::Device> chosen_device;
        chosen_device.push_back(device);
        cl::Context context(chosen_device);
        cl::CommandQueue queue(context, device);

        // Create the program object
        cl::Program program(context, util::loadProgram("../pi_ocl.cl"), true);

        // Create the kernel object for quering information
        cl::Kernel ko_pi(program, "pi");

        // Get the work group size
        work_group_size = ko_pi.getWorkGroupInfo<CL_KERNEL_WORK_GROUP_SIZE>(device);
        //printf("wgroup_size = %lu\n", work_group_size);

        cl::make_kernel<int, float, cl::LocalSpaceArg, cl::Buffer> pi(program, "pi");

        // Now that we know the size of the work_groups, we can set the number of work
        // groups, the actual number of steps, and the step size
        nwork_groups = in_nsteps/(work_group_size*niters);

        if ( nwork_groups < 1) {
            nwork_groups = device.getInfo<CL_DEVICE_MAX_COMPUTE_UNITS>();
            work_group_size=in_nsteps / (nwork_groups*niters);
        }

        nsteps = work_group_size * niters * nwork_groups;
        step_size = 1.0f/static_cast<float>(nsteps);
        std::vector<float> h_psum(nwork_groups);

        printf(
            " %d work groups of size %d.  %d Integration steps\n",
            (int)nwork_groups,
            (int)work_group_size,
            nsteps);

        d_partial_sums = cl::Buffer(context, CL_MEM_WRITE_ONLY, sizeof(float) * nwork_groups);

        util::Timer timer;

        // Execute the kernel over the entire range of our 1d input data set
        // using the maximum number of work group items for this device
        pi(
            cl::EnqueueArgs(
                    queue,
                    cl::NDRange(nsteps / niters),
                    cl::NDRange(work_group_size)),
                    niters,
                    step_size,
                    cl::Local(sizeof(float) * work_group_size),
                    d_partial_sums);

        cl::copy(queue, d_partial_sums, h_psum.begin(), h_psum.end());

        // complete the sum and compute final integral value
        pi_res = 0.0f;
        for (unsigned int i = 0; i< nwork_groups; i++) {
                pi_res += h_psum[i];
        }
        pi_res = pi_res * step_size;

        //rtime = wtime() - rtime;
        double rtime = static_cast<double>(timer.getTimeMilliseconds()) / 1000.;
        printf("\nThe calculation ran in %lf seconds\n", rtime);
        printf(" pi = %f for %d steps\n", pi_res, nsteps);

        }
        catch (cl::Error err) {
            std::cout << "Exception\n";
            std::cerr
            << "ERROR: "
            << err.what()
            << "("
            << err_code(err.err())
            << ")"
            << std::endl;
        }
}
Esempio n. 28
0
void rrd_graph_script(
    int argc,
    char *argv[],
    image_desc_t *const im,
    int optno)
{
    int       i;

    /* and now handle the things*/
    parsedargs_t pa;
    initParsedArguments(&pa);

    /* loop arguments */
    for (i = optno; i < argc; i++) {
	/* release parsed args - avoiding late cleanups*/
	freeParsedArguments(&pa);
	/* processed parsed args */
	if (parseArguments(argv[i],&pa)) {
	  return; }

        /* dumpArguments(&pa); */
	/* now let us handle the field based on the first command or cmd=...*/
	char*cmd=NULL;
	/* and try to get via cmd */
	char* t=getKeyValueArgument("cmd",255,&pa);
	if (t) {
	  cmd=t;
	} else if ((t=getKeyValueArgument("pos0",255,&pa))) {
	  cmd=t;
	} else {
	  rrd_set_error("no command set in argument %s",pa.arg_orig);
	  freeParsedArguments(&pa);
	  return;
	}

	/* convert to enum but handling LINE special*/
	enum gf_en gf = (enum gf_en) -1;
	gf=gf_conv(cmd);
	if ((int)gf == -1) {
	  if (strncmp("LINE",cmd,4)==0) {
	    gf=GF_LINE;
	    addToArguments(&pa,NULL,"linewidth",cmd+4,0);
	  } else {
	    rrd_set_error("'%s' is not a valid function name in %s", cmd,pa.arg_orig );
	    return;
	  }
	}
	/* now we can handle the commands */
	int r=0;
	switch (gf) {
	case GF_XAXIS:     r=parse_axis(gf,&pa,im); break;
	case GF_YAXIS:     r=parse_axis(gf,&pa,im); break;
	case GF_DEF:       r=parse_def(gf,&pa,im); break;
	case GF_CDEF:      r=parse_cvdef(gf,&pa,im); break;
	case GF_VDEF:      r=parse_cvdef(gf,&pa,im); break;
	case GF_LINE:      r=parse_line(gf,&pa,im); break;
	case GF_AREA:      r=parse_area(gf,&pa,im); break;
	case GF_PRINT:     r=parse_gprint(gf,&pa,im); break;
	case GF_GPRINT:    r=parse_gprint(gf,&pa,im); break;
	case GF_COMMENT:   r=parse_comment(gf,&pa,im); break;
	case GF_HRULE:     r=parse_hvrule(gf,&pa,im); break;
	case GF_VRULE:     r=parse_hvrule(gf,&pa,im); break;
	case GF_STACK:     r=parse_stack(gf,&pa,im); break;
	case GF_TICK:      r=parse_tick(gf,&pa,im); break;
	case GF_TEXTALIGN: r=parse_textalign(gf,&pa,im); break;
	case GF_SHIFT:     r=parse_shift(gf,&pa,im); break;
	case GF_XPORT:     r=parse_xport(gf,&pa,im); break;
	  /* unsupported types right now */
  }
	/* handle the return error case */
	if (r) { freeParsedArguments(&pa); return;}
	/* check for unprocessed keyvalue args */
	char *s;
	if ((s=checkUnusedValues(&pa))) {
	  /* set error message */
	  rrd_set_error("Unused Arguments \"%s\" in command : %s",s,pa.arg_orig);
	  free(s);
	  /* exit early */
	  freeParsedArguments(&pa);
	  return;
	}
    }
    /* finally free arguments */
    freeParsedArguments(&pa);
}
Esempio n. 29
0
UDTTest::UDTTest(int& argc, char** argv) :
    QCoreApplication(argc, argv)
{
    qInstallMessageHandler(LogHandler::verboseMessageHandler);
    
    parseArguments();
    
    // randomize the seed for packet size randomization
    srand(time(NULL));

    _socket.bind(QHostAddress::AnyIPv4, _argumentParser.value(PORT_OPTION).toUInt());
    qDebug() << "Test socket is listening on" << _socket.localPort();
    
    if (_argumentParser.isSet(TARGET_OPTION)) {
        // parse the IP and port combination for this target
        QString hostnamePortString = _argumentParser.value(TARGET_OPTION);
        
        QHostAddress address { hostnamePortString.left(hostnamePortString.indexOf(':')) };
        quint16 port { (quint16) hostnamePortString.mid(hostnamePortString.indexOf(':') + 1).toUInt() };
        
        if (address.isNull() || port == 0) {
            qCritical() << "Could not parse an IP address and port combination from" << hostnamePortString << "-" <<
                "The parsed IP was" << address.toString() << "and the parsed port was" << port;
            
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        } else {
            _target = HifiSockAddr(address, port);
            qDebug() << "Packets will be sent to" << _target;
        }
    }
    
    if (_argumentParser.isSet(PACKET_SIZE)) {
        // parse the desired packet size
        _minPacketSize = _maxPacketSize = _argumentParser.value(PACKET_SIZE).toInt();
        
        if (_argumentParser.isSet(MIN_PACKET_SIZE) || _argumentParser.isSet(MAX_PACKET_SIZE)) {
            qCritical() << "Cannot set a min packet size or max packet size AND a specific packet size.";
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        }
    } else {
        
        bool customMinSize = false;
        
        if (_argumentParser.isSet(MIN_PACKET_SIZE)) {
            _minPacketSize = _argumentParser.value(MIN_PACKET_SIZE).toInt();
            customMinSize = true;
        }
        
        if (_argumentParser.isSet(MAX_PACKET_SIZE)) {
            _maxPacketSize = _argumentParser.value(MAX_PACKET_SIZE).toInt();
            
            // if we don't have a min packet size we should make it 1, because we have a max
            if (customMinSize) {
                _minPacketSize = 1;
            }
        }
        
        if (_maxPacketSize < _minPacketSize) {
            qCritical() << "Cannot set a max packet size that is smaller than the min packet size.";
            QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection);
        }
    }
    
    if (_argumentParser.isSet(MAX_SEND_BYTES)) {
        _maxSendBytes = _argumentParser.value(MAX_SEND_BYTES).toInt();
    }
    
    if (_argumentParser.isSet(MAX_SEND_PACKETS)) {
        _maxSendPackets = _argumentParser.value(MAX_SEND_PACKETS).toInt();
    }
    
    if (_argumentParser.isSet(UNRELIABLE_PACKETS)) {
        _sendReliable = false;
    }

    if (_argumentParser.isSet(ORDERED_PACKETS)) {
        _sendOrdered = true;
    }
    
    if (_argumentParser.isSet(MESSAGE_SIZE)) {
        if (_argumentParser.isSet(ORDERED_PACKETS)) {
            static const double BYTES_PER_MEGABYTE = 1000000;
            _messageSize = (int) _argumentParser.value(MESSAGE_SIZE).toInt() * BYTES_PER_MEGABYTE;
            
            qDebug() << "Message size for ordered packet sending is" << QString("%1MB").arg(_messageSize / BYTES_PER_MEGABYTE);
        } else {
            qWarning() << "message-size has no effect if not sending ordered - it will be ignored";
        }
    }
    
    
    // in case we're an ordered sender or receiver setup our random number generator now
    static const int FIRST_MESSAGE_SEED = 742272;
    
    int messageSeed = FIRST_MESSAGE_SEED;
    
    if (_argumentParser.isSet(MESSAGE_SEED)) {
        messageSeed = _argumentParser.value(MESSAGE_SEED).toInt();
    }
    
    // seed the generator with a value that the receiver will also use when verifying the ordered message
    _generator.seed(messageSeed);
    
    if (!_target.isNull()) {
        sendInitialPackets();
    } else {
        // this is a receiver - in case there are ordered packets (messages) being sent to us make sure that we handle them
        // so that they can be verified
        _socket.setMessageHandler(
            [this](std::unique_ptr<udt::Packet> packet) {
                auto messageNumber = packet->getMessageNumber();
                auto it = _pendingMessages.find(messageNumber);

                if (it == _pendingMessages.end()) {
                    auto message = std::unique_ptr<Message>(new Message { messageNumber, packet->readAll() });
                    message->data.reserve(_messageSize);
                    if (packet->getPacketPosition() == udt::Packet::ONLY) {
                        handleMessage(std::move(message));
                    } else {
                        _pendingMessages[messageNumber] = std::move(message);
                    }
                } else {
                    auto& message = it->second;
                    message->data.append(packet->readAll());

                    if (packet->getPacketPosition() == udt::Packet::LAST) {
                        handleMessage(std::move(message));
                        _pendingMessages.erase(it);
                    }
                }

        });
    }
    _socket.setMessageFailureHandler(
        [this](HifiSockAddr from, udt::Packet::MessageNumber messageNumber) {
            _pendingMessages.erase(messageNumber);
        }
    );
    
    // the sender reports stats every 100 milliseconds, unless passed a custom value
    
    if (_argumentParser.isSet(STATS_INTERVAL)) {
        _statsInterval = _argumentParser.value(STATS_INTERVAL).toInt();
    }
    
    QTimer* statsTimer = new QTimer(this);
    connect(statsTimer, &QTimer::timeout, this, &UDTTest::sampleStats);
    statsTimer->start(_statsInterval);
}
Esempio n. 30
0
int main (int argc, char **argv) {
	struct config c = parseArguments(argc, argv);
	if (c.error)
		return 0;

	std::cout << "Starting uEye camera demo..." << std::endl;
	//std::cout << "Test message:" << std::endl;

	std::cout << "Getting number of cameras" << std::endl;
	time_point start = Clock::now();
	INT nCam = CameraImpl::getNumberOfCameras();
	printTime(start, Clock::now());
	std::cout << "We found " << nCam << " connected camera(s)." << std::endl;
	std::cout << "Getting the list of available cameras" << std::endl;
	start = Clock::now();
	UEYE_CAMERA_LIST* cams = CameraImpl::getCameraList(nCam);
	printTime(start, Clock::now());
	HIDS hCam = 0;
	for (INT i = 0; i < cams->dwCount; i++) {
		std::cout << "Camera[" << i << "] ID is " << cams->uci[i].dwCameraID << std::endl;
	}
	if (cams->dwCount > 0) {
		hCam = cams->uci[0].dwCameraID;
	}
	delete[] cams;
	std::cout << std::endl;

	CameraImpl cam(hCam); //call the camera implementation
	cam.start(false);
	if (cam.getCameraState() != CameraImpl::START) {
		return 1;
	}

	std::cout << "Configuring camera" << std::endl;
	start = Clock::now();
	cam.config(); //do the configuration of the camera 

	if (c.pixel != -1) {
		cam.setPixelClock(c.pixel); // set the pixel clock
	}
	if (c.exposure != -1) {
		cam.setExposureTime(c.exposure); // set the exposure time
	}
	if (c.aoi[0] != -1) {
		CameraImpl::AreaOfInterest aoi;
		for (int i = 0; i < 4; i++) {
			aoi[i] = c.aoi[i];
		}
		cam.setLogicalAOI(aoi); // set the area of interest
	}
	cam.resume();  // sets Camera state to READY and Software trigger to on
	usleep(4000000);
       
	printTime(start, Clock::now());
		

	std::cout << "Allocating image buffer" << std::endl;
	start = Clock::now();
	cam.allocImage(); // Allocate image buffer

	printTime(start, Clock::now());
	std::cout << std::endl;

 	double starttemp=0; //warmup loop
	double finaltemp=0;
	
	starttemp = cam.getTempCels();
	std::cout << "startemp is " << starttemp  << std::endl;
	//finaltemp = starttemp + c.degrees;

	finaltemp = c.degrees;// set the absolute temperature
	std::cout << "finaltemp is " << finaltemp  << c.degrees << std::endl;

	cam.resetImage();
	if (cam.getTempCels() <  finaltemp){
		std::cout << "The actual temperature is " << cam.getTempCels() << " Celsius" << " this is smaller than " << finaltemp << std::endl;
		cam.printPixelClockList();
		//cam.setExposureTime(1);
		cam.setPixelClock(216);
		usleep(4000000);//ns
		std::cout << "Setting pixel clock to 216" <<  std::endl;
		while (cam.getTempCels() <  finaltemp){//warmup loop
			cam.takeImage();
			std::cout << "The temperature is " << cam.getTempCels() << " Celsius" << std::endl;
		}
	cam.setPixelClock(c.pixel);
	std::cout << "The pixel clock is " << cam.getPixelClock() << " Hz?" << std::endl;
	cam.setExposureTime(c.exposure);
	std::cout << "The exposure time is " << cam.getExposureTime() << " ms" << std::endl;
	}
    for (int j = 0; j < c.blocks; j++) { //open loop over all frame blocks
	
	std::cout << "Exposing block " << j << " of " << c.blocks << std::endl;
	std::cout << "Saving " << c.frames << " images" << std::endl;
	std::cout << "The temperature is " << cam.getTempCels() << " Celsius" << std::endl;
	start = Clock::now();

        
	std::cout << "The pixel clock is " << cam.getPixelClock() << " Hz?" << std::endl;
	if (cam.getTempCels() <  finaltemp){
		std::cout << "The actual temperature is " << cam.getTempCels() << " Celsius" << " this is smaller than " << finaltemp << std::endl;
		//cam.printPixelClockList();
		//cam.setExposureTime(1);
		cam.setPixelClock(432);
		std::cout << "The pixel clock is " << cam.getPixelClock() << " Hz?" << std::endl;
		usleep(4000000);//ns
		std::cout << "Setting pixel clock to 432" <<  std::endl;
		while (cam.getTempCels() <  finaltemp){//warmup loop
			cam.allocImage(); // Allocate image buffer and sets an image memory active
			cam.resetImage();
			cam.takeImage();
			cam.freeImage();
			std::cout << "The temperature is " << cam.getTempCels() << " Celsius" << std::endl;
		}
	cam.setPixelClock(c.pixel);
	std::cout << "The pixel clock is " << cam.getPixelClock() << " Hz?" << std::endl;
	std::cout << "The exposure time is " << cam.getExposureTime() << " ms" << std::endl;	
	//cam.setExposureTime(c.exposure);

	}

	cam.allocImage(); // Allocate image buffer and sets an image memory active
	cam.resetImage(); //clean the memory to take a new image 

	cam.setPixelClock(c.pixel);
	std::cout << "The pixel clock is " << cam.getPixelClock() << " Hz?" << std::endl;
	std::cout << "The exposure time is " << cam.getExposureTime() << " ms" << std::endl;		
	//cam.setExposureTime(c.exposure);
	usleep(4000000);//ns

	for (int i = 0; i < c.frames; i++) {
		cam.takeImage();
		//cam.saveImage();
		cam.addImage();
	}
	cam.averageImage(c.frames);
	

	//create a string for the filname including the image-block number
	std::ostringstream oss;
	oss << c.filename << j << ".fit";	
	std::cout << "Filename is " << oss.str() << std::endl;
	cam.setFileName(oss.str());
	//save the image
	cam.saveFitsImage(); 
	//convert the image, if wished
	if (c.bmp) {
		cam.convertImage(std::string(".bmp"));
	}
	if (c.jpg) {
		cam.convertImage(std::string(".jpg"));
	}
	if (c.sex) {
		cam.runSExtractor();
	}

	printTime(start, Clock::now());
	std::cout << std::endl;

	cam.freeImage(); // releases the image memory. Does it also globally unlock the memory?
	std::cout << "Please press enter " << std::endl;
	std::cin.ignore();
	//restart the camera after 100 images...  
	//if (j == 100) 	{
	//	//cam.resetImage()
	//	std::cout << "Image 100. Cleaning memory" << std::endl;
	//	cam.freeImage(); // clean the image memory
	//	//cam.allocImage(); // Allocate image buffer
	//	cam.pause();
	//	//cam.reset();
	//	//std::cout << "Image 100. Camera reset memory" << std::endl;
	//	//cam.resume(); 
	//	cam.reset();
	//	cam.stop();
	//	cam.start(false);
	//	if (cam.getCameraState() != CameraImpl::START) {
	//		return 1;
	//	}
	//	cam.config(); 
	//	cam.resume(); 
	//	usleep(4000000);
	//	cam.allocImage(); // Allocate image buffer
	//	cam.resetImage();
	//}

    } //close the loop for the frame blocks
	std::cout << "Releasing image buffer" << std::endl;
	start = Clock::now();
	cam.freeImage(); // clean the image memory
	printTime(start, Clock::now());

	

	start = Clock::now();
	cam.pause();
	printTime(start, Clock::now());

	start = Clock::now();
	cam.reset();
	printTime(start, Clock::now());

	start = Clock::now();
	cam.stop();
	printTime(start, Clock::now());

	return 0;
}