int main(int argc, char* argv[]) { // Setup. AppLib::Logging::setApplicationName(std::string("apputil")); struct arg_file *script = arg_file1(NULL, NULL, "script", "the path of the script to execute"); struct arg_end *end = arg_end(20); void *argtable[] = { script, end }; script->filename[0] = NULL; // Check to see if the argument definitions were allocated // correctly. if (arg_nullcheck(argtable)) { AppLib::Logging::showErrorW("Insufficient memory."); return 1; } // Now parse the arguments. int nerrors = arg_parse(argc, argv, argtable); // Check to see if there were errors. if (nerrors > 0 && script->filename[0] == NULL) { printf("Usage: apputil"); arg_print_syntax(stdout, argtable, "\n"); arg_print_errors(stdout, end, "apputil"); printf("AppUtil - The application scripting utility.\n\n"); arg_print_glossary(stdout, argtable, " %-25s %s\n"); return 1; } // Execute. return runPython(script->filename[0], argc, argv); }
void test_argstr_basic_010(CuTest* tc) { struct arg_str* a = arg_str0(NULL, "hello,world", "STRVAL", "either --hello or --world or none"); struct arg_str* b = arg_str0("bB", NULL, "STRVAL", "either -b or -B or none"); struct arg_str* c = arg_str1("cC", NULL, "STRVAL", "either -c or -C"); struct arg_str* d = arg_strn("dD", "delta", "STRVAL", 2, 4, "-d|-D|--delta 2..4 occurences"); struct arg_end* end = arg_end(20); void* argtable[] = {a, b, c, d, end}; int nerrors; char* argv[] = {"program", "-Cstring1", "-Dstring2", NULL}; int argc = sizeof(argv) / sizeof(char*) - 1; CuAssertTrue(tc, arg_nullcheck(argtable) == 0); nerrors = arg_parse(argc, argv, argtable); CuAssertTrue(tc, nerrors == 1); CuAssertTrue(tc, a->count == 0); CuAssertTrue(tc, b->count == 0); CuAssertTrue(tc, c->count == 1); CuAssertStrEquals(tc, c->sval[0], "string1"); CuAssertTrue(tc, d->count == 1); CuAssertStrEquals(tc, d->sval[0], "string2"); arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); }
int main(int argc, char **argv) { struct arg_xxx *scalar = arg_xxx1(NULL, NULL, "<scalar>", 0.0, 1.0, "<double> value in range [0.0, 1.0]"); struct arg_xxx *x = arg_xxx0("x", NULL, "<double>", -1.0, 1.0, "x coeff in range [-1.0, 1.0]"); struct arg_xxx *y = arg_xxxn("y", NULL, "<double>", 0,argc+2, 0.5, 0.9, "y coeff in range [0.5, 0.9]"); struct arg_lit *help = arg_lit0(NULL,"help", "print this help and exit"); struct arg_end *end = arg_end(20); void* argtable[] = {scalar,x,y,help,end}; const char* progname = "argcustom"; int nerrors; int exitcode=0; int i; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n",progname); exitcode=1; goto exit; } /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout,argtable,"\n"); printf("This program demonstrates the use of the argtable2 library\n"); printf("for parsing command line arguments.\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); exitcode=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,progname); printf("Try '%s --help' for more information.\n",progname); exitcode=1; goto exit; } /* only get here is command line arguments were parsed sucessfully */ printf("scalar = %f\n", scalar->data[0]); if (x->count > 0) printf("x = %f\n", x->data[0]); for (i=0; i<y->count; i++) printf("y[%d] = %f\n", i, y->data[i]); exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return exitcode; }
static int dslink_parse_opts(int argc, char **argv, DSLinkConfig *config) { int ret = 0; struct arg_lit *help; struct arg_str *broker, *log; struct arg_end *end; void *argTable[] = { help = arg_lit0("h", "help", "Displays this help menu"), broker = arg_str1("b", "broker", "url", "Sets the broker URL to connect to"), log = arg_str0("l", "log", "log type", "Sets the logging level"), end = arg_end(5) }; if (arg_nullcheck(argTable) != 0) { return DSLINK_ALLOC_ERR; } int errs = arg_parse(argc, argv, argTable); if (help->count > 0) { printf("Usage: <opts>\n"); arg_print_glossary(stdout, argTable, " %-25s %s\n"); ret = 1; goto exit; } if (errs > 0) { dslink_print_help(); arg_print_errors(stdout, end, ":"); ret = 1; goto exit; } config->broker_url = broker->sval[0]; if (log->count > 0) { char lvl[8]; const char *src = log->sval[0]; size_t len = strlen(src); if (len > sizeof(lvl)) { len = sizeof(lvl); } memcpy(lvl, src, len); if (dslink_log_set_lvl(lvl, len) != 0) { printf("Invalid log level: %s\n", lvl); dslink_print_help(); ret = 1; goto exit; } } exit: arg_freetable(argTable, sizeof(argTable) / sizeof(argTable[0])); return ret; }
int main(int argc, char **argv) { struct arg_int *val = arg_intn(NULL,NULL,NULL,2,100,"must be an even number of non-zero integer values that sum to 100"); struct arg_end *end = arg_end(20); void* argtable[] = {val,end}; const char* progname = "callbacks"; int nerrors; int exitcode=0; int i; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n",progname); exitcode=1; goto exit; } /* replace the default arg_int parsing and error validation routines with our own custom routines */ val->hdr.scanfn = (arg_scanfn*)myscanfn; val->hdr.checkfn = (arg_checkfn*)mycheckfn; val->hdr.errorfn = (arg_errorfn*)myerrorfn; /* special case: no command line options induces brief help */ if (argc==1) { printf("Usage: %s ", progname); arg_print_syntax(stdout,argtable,"\n"); arg_print_glossary(stdout,argtable,"where: %s %s\n"); exitcode=0; goto exit; } /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc,argv,argtable); /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,progname); exitcode=1; goto exit; } /* parsing was succesful, print the values obtained */ for (i=0; i<val->count; i++) printf("val->ival[%d] = %d\n",i, val->ival[i]); exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return exitcode; }
void parse_command_line(int argc, char* argv[]) { // if the parsing of the arguments was unsuccessful int nerrors; // Define argument table structs python_folder = arg_file0 ( NULL, "py-folder", "<path to file>", "Path to folder (relative or absolute) that contains python script (default: lpfw-pygui)" ); log_debug = arg_int0 ( NULL, "log-debug", "<1/0 for yes/no>", "Enable debug messages logging" ); struct arg_lit *help = arg_lit0 ( NULL, "help", "Display this help screen" ); struct arg_lit *version = arg_lit0 ( NULL, "version", "Display the current version" ); struct arg_end *end = arg_end ( 10 ); void *argtable[] = {python_folder, log_debug, help, version, end}; // Set default values char *python_folder_pointer = malloc(strlen("lpfw-pygui")+1); strcpy (python_folder_pointer, "lpfw-pygui"); python_folder->filename[0] = python_folder_pointer; * ( log_debug->ival ) = 0; if ( arg_nullcheck ( argtable ) != 0 ) { printf ( "Error: insufficient memory\n" ); exit(0); } nerrors = arg_parse ( argc, argv, argtable ); if ( nerrors == 0 ) { if ( help->count == 1 ) { printf ( "Leopard Flower frontend :\n Syntax and help:\n" ); arg_print_glossary ( stdout, argtable, "%-43s %s\n" ); exit (0); } else if ( version->count == 1 ) { printf ( "%s\n", VERSION ); exit (0); } } else if ( nerrors > 0 ) { arg_print_errors ( stdout, end, "Leopard Flower frontend" ); printf ( "Leopard Flower frontend:\n Syntax and help:\n" ); arg_print_glossary ( stdout, argtable, "%-43s %s\n" ); exit (1); } // Free memory - don't do this cause args needed later on // arg_freetable(argtable, sizeof (argtable) / sizeof (argtable[0])); }
int main(int argc, char * argv[]) { void* argtable[] = { input = arg_filen( "i", "input", "<string>", 0, 100, "input file") , o_validate = arg_strn( "v", "validate", "<string>", 0, 10, "validate operations") , o_h = arg_file0( NULL, "output-h", "<string>", "output h file dir") , o_lib_c = arg_file0( NULL, "output-lib-c", "<string>", "output c lib file") , o_lib_c_arg = arg_str0( NULL, "output-lib-c-arg", "<string>", "output c lib file") , o_lib_bin = arg_file0( NULL, "output-lib-bin", "<string>", "output c lib file") , help = arg_lit0( NULL, "help", "print this help and exit") , end = arg_end(20) }; struct error_monitor em_buf; error_monitor_t em; int rv; int nerrors; cpe_error_monitor_init(&em_buf, cpe_error_log_to_consol, 0); em = &em_buf; rv = -1; if (arg_nullcheck(argtable) != 0) { CPE_ERROR(em, "init arg table fail!"); goto exit; } nerrors = arg_parse(argc,argv,argtable); if (help->count > 0) { printf("Usage: %s", argv[0]); arg_print_syntax(stdout,argtable,"\n"); rv = 0; goto exit; } if (nerrors > 0) { arg_print_errors(stdout, end, argv[0]); printf("Try '%s --help' for more information.\n", argv[0]); goto exit; } rv = tools_main(em); exit: arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return rv; }
void test_argfile_basic_003(CuTest* tc) { struct arg_file* a = arg_file1(NULL, NULL, "<file>", "filename to test"); struct arg_end* end = arg_end(20); void* argtable[] = {a, end}; int nerrors; char* argv[] = {"program", "./foo.bar", NULL}; int argc = sizeof(argv) / sizeof(char*) - 1; CuAssertTrue(tc, arg_nullcheck(argtable) == 0); nerrors = arg_parse(argc, argv, argtable); CuAssertTrue(tc, nerrors == 0); CuAssertTrue(tc, a->count == 1); CuAssertStrEquals(tc, a->filename[0], "./foo.bar"); CuAssertStrEquals(tc, a->basename[0], "foo.bar"); CuAssertStrEquals(tc, a->extension[0], ".bar"); arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); }
int main(int argc, char **argv) { int exitcode = 0; int nerrors = 0; /* Prepare command line arguments */ struct arg_str *latero_ip = arg_str1(NULL,"latero_ip","IP", "Latero server IP address"); struct arg_lit *print_resp= arg_lit0("p", "print", "print response packet"); struct arg_int *numpkt = arg_int0("n", "numpkt","<n>", "How many packets (default is 1)"); struct arg_int *dacval = arg_intn(NULL,"dac","<int>",0,4,"dac values (up to 4 values)"); struct arg_lit *rd = arg_lit0("r", "read", "read"); struct arg_lit *wr = arg_lit0("w", "write", "write"); struct arg_int *addr = arg_int0("a", "addr",NULL, "address"); struct arg_int *value = arg_int0("v", "value",NULL, "value"); struct arg_lit *mainctrl = arg_lit0(NULL,"mainctrl", "Raw commands are for the main controller"); struct arg_int *tpat = arg_int0("t","testpat","<n>", "Run Test Pattern:1=Split, 2=AllPin, 3=RowCol"); struct arg_lit *latio = arg_lit0(NULL,"lateroio", "Raw commands are for the Latero IO card"); struct arg_lit *help = arg_lit0(NULL,"help", "print this help and exit"); struct arg_end *end = arg_end(10); void* argtable[] = {latero_ip,print_resp,numpkt,dacval, rd, wr, addr, value, mainctrl, tpat, latio, help,end}; //latero_ip->sval[0] = "192.168.1.108"; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("Insufficient memory (argtable)\n"); exitcode = 1; goto exit; } numpkt->ival[0] = 1; tpat->ival[0] = 0; nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", argv[0]); arg_print_syntax(stdout,argtable,"\n"); printf("Latero client demonstration program version 1, revision 1\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); exitcode=0; goto exit; } if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,argv[0]); printf("Try '%s --help' for more information.\n",argv[0]); exitcode = 0; goto exit; } if( wr->count > 0 ) { if( addr->count != 1 || value->count != 1 ) { printf("Write requires an address and a value\n"); exitcode = 1; goto exit; } if( mainctrl->count + latio->count == 0 ) { printf("Write requires a destination (--mainctrl or --lateroio)\n"); exitcode = 1; goto exit; } } if( rd->count > 0 ) { if( addr->count != 1 ) { printf("Read requires an address\n"); exitcode = 1; goto exit; } if( mainctrl->count + latio->count == 0 ) { printf("Read requires a destination (--mainctrl or --lateroio)\n"); exitcode = 1; goto exit; } } return( my_main( latero_ip->sval[0], print_resp->count, numpkt->ival[0], dacval->ival, dacval->count, rd->count, wr->count, addr->ival[0], value->ival[0], mainctrl->count, latio->count, tpat->ival[0]) ); exit: printf("Program Ended\n"); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return(exitcode); }
int main(int argc, char* argv[]) { #ifdef BALL double discountFactor = 0.9; #else #ifdef CART_POLE double discountFactor = 0.95; #else #ifdef DOUBLE_CART_POLE double discountFactor = 0.95; #else #ifdef MOUNTAIN_CAR double discountFactor = 0.99; #else #ifdef ACROBOT double discountFactor = 0.95; #else #ifdef BOAT double discountFactor = 0.95; #else #ifdef CART_POLE_BINARY double discountFactor = 0.95; #else #ifdef SWIMMER double discountFactor = 0.95; #endif #endif #endif #endif #endif #endif #endif #endif FILE* initFileFd = NULL; state** initialStates = NULL; FILE* results = NULL; char str[1024]; unsigned int i = 0; unsigned int h = 0; unsigned int* ns = NULL; unsigned int nbN = 0; unsigned int n = 0; unsigned int nbSteps = 0; unsigned int timestamp = time(NULL); int readFscanf = -1; optimistic_instance* optimistic = NULL; struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state"); struct arg_str* r = arg_str1("n", NULL, "<s>", "List of maximum numbers of evaluations"); struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps"); struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem"); struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs"); struct arg_end* end = arg_end(6); int nerrors = 0; void* argtable[6]; argtable[0] = initFile; argtable[1] = r; argtable[2] = s; argtable[3] = k; argtable[4] = where; argtable[5] = end; if(arg_nullcheck(argtable) != 0) { printf("error: insufficient memory\n"); arg_freetable(argtable, 6); return EXIT_FAILURE; } nerrors = arg_parse(argc, argv, argtable); if(nerrors > 0) { printf("%s:", argv[0]); arg_print_syntax(stdout, argtable, "\n"); arg_print_errors(stdout, end, argv[0]); arg_freetable(argtable, 6); return EXIT_FAILURE; } initGenerativeModelParameters(); K = k->ival[0]; initGenerativeModel(); initFileFd = fopen(initFile->filename[0], "r"); readFscanf = fscanf(initFileFd, "%u\n", &n); initialStates = (state**)malloc(sizeof(state*) * n); for(; i < n; i++) { readFscanf = fscanf(initFileFd, "%s\n", str); initialStates[i] = makeState(str); } fclose(initFileFd); nbSteps = s->ival[0]; ns = parseUnsignedIntList((char*)r->sval[0], &nbN); optimistic = optimistic_initInstance(NULL, discountFactor); sprintf(str, "%s/%u_results_%u_%u.csv", where->filename[0], timestamp, K, nbSteps); results = fopen(str, "w"); for(h = 0; h < nbN; h++) { double sumRewards = 0.0; for(i = 0; i < n; i++) { unsigned int j = 0; state* crt = copyState(initialStates[i]); optimistic_resetInstance(optimistic, crt); for(; j < nbSteps; j++) { char isTerminal = 0; double reward = 0.0; state* nextState = NULL; optimistic_keepSubtree(optimistic); action* optimalAction = optimistic_planning(optimistic, ns[h]); isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0; freeState(crt); crt = nextState; sumRewards += reward; if(isTerminal) break; } optimistic_resetInstance(optimistic, crt); freeState(crt); printf(">>>>>>>>>>>>>> %uth initial state processed\n", i + 1); fflush(NULL); } fprintf(results, "%u,%.15f\n", ns[h], sumRewards / (double)n); printf(">>>>>>>>>>>>>> n = %u done\n\n", ns[h]); fflush(NULL); } fclose(results); arg_freetable(argtable, 6); for(i = 0; i < n; i++) freeState(initialStates[i]); free(initialStates); optimistic_uninitInstance(&optimistic); freeGenerativeModel(); freeGenerativeModelParameters(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { struct arg_dbl *a = arg_dbl1(NULL,NULL,"a","a is <double>"); struct arg_dbl *b = arg_dbl0(NULL,NULL,"b","b is <double>"); struct arg_dbl *c = arg_dbl0(NULL,NULL,"c","c is <double>"); struct arg_dbl *d = arg_dbln("dD","delta","<double>",0,3,"d can occur 0..3 times"); struct arg_dbl *e = arg_dbl0(NULL,"eps,eqn","<double>","eps is optional"); struct arg_lit *help = arg_lit0(NULL,"help","print this help and exit"); struct arg_end *end = arg_end(20); void* argtable[] = {a,b,c,d,e,help,end}; int nerrors; int exitcode=0; int i; double sum=0; /* printf("a=%p\n",a); printf("b=%p\n",b); printf("c=%p\n",c); printf("d=%p\n",d); printf("e=%p\n",e); printf("help=%p\n",help); printf("end=%p\n",end); printf("argtable=%p\n",argtable); */ /* print the command line */ for (i=0; i<argc; i++) printf("%s ",argv[i]); printf("\n"); /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n",argv[0]); exitcode=1; goto exit; } /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s ", argv[0]); arg_print_syntax(stdout,argtable,"\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); exitcode=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,argv[0]); exitcode=1; goto exit; } /* parsing complete, verify all args sum to zero */ for (i=0; i<a->count; i++) { printf("a[%d]=%f\n",i,a->dval[i]); sum += a->dval[i]; } for (i=0; i<b->count; i++) { printf("b[%d]=%f\n",i,b->dval[i]); sum += b->dval[i]; } for (i=0; i<c->count; i++) { printf("c[%d]=%f\n",i,c->dval[i]); sum += c->dval[i]; } for (i=0; i<d->count; i++) { printf("d[%d]=%f\n",i,d->dval[i]); sum += d->dval[i]; } for (i=0; i<e->count; i++) { printf("e[%d]=%f\n",i,e->dval[i]); sum += e->dval[i]; } printf("sum=%f\n",sum); if (sum<-1.0e-6 || sum>1.0e-6) { printf("%s: error - sum=%f is non-zero\n",argv[0],sum); exitcode=1; goto exit; } exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); printf("%s: exitcode=%d\n\n",argv[0],exitcode); /* close stdin and stdout to stop memcheck whining about their memory not being freed */ fclose(stdin); fclose(stdout); return exitcode; }
int main(int argc, char* argv[]) { double discountFactor; unsigned int maxNbEvaluations; char isTerminal = 0; char keepingTree = 0; int nbTimestep = -1; unsigned int branchingFactor = 0; #ifdef USE_SDL char isDisplayed = 1; char isFullscreen = 1; char verbose = 0; char resolution[255] = "640x480"; #else char verbose = 1; #endif uniform_instance* instance = NULL; state* crtState = NULL; state* nextState = NULL; double reward = 0.0; action* optimalAction = NULL; struct arg_dbl* g = arg_dbl1("g", "discountFactor", "<d>", "The discount factor for the problem"); struct arg_int* n = arg_int1("n", "nbEvaluations", "<n>", "The number of evaluations"); struct arg_int* s = arg_int0("s", "nbtimestep", "<n>", "The number of timestep"); struct arg_int* b = arg_int0("b", "branchingFactor", "<n>", "The branching factor of the problem"); struct arg_lit* k = arg_lit0("k", NULL, "Keep the subtree"); struct arg_str* i = arg_str0(NULL, "state", "<s>", "The initial state to use"); #ifdef USE_SDL struct arg_lit* d = arg_lit0("d", NULL, "Display the viewer"); struct arg_lit* f = arg_lit0("f", NULL, "Fullscreen"); struct arg_lit* v = arg_lit0("v", NULL, "Verbose"); struct arg_str* r = arg_str0(NULL, "resolution", "<s>", "The resolution of the display window"); void* argtable[11]; int nbArgs = 10; #else void* argtable[7]; int nbArgs = 6; #endif struct arg_end* end = arg_end(nbArgs+1); int nerrors = 0; s->ival[0] = -1; b->ival[0] = 0; argtable[0] = g; argtable[1] = n; argtable[2] = s; argtable[3] = k; argtable[4] = b; argtable[5] = i; #ifdef USE_SDL argtable[6] = d; argtable[7] = f; argtable[8] = v; argtable[9] = r; #endif argtable[nbArgs] = end; if(arg_nullcheck(argtable) != 0) { printf("error: insufficient memory\n"); arg_freetable(argtable, nbArgs+1); return EXIT_FAILURE; } nerrors = arg_parse(argc, argv, argtable); if(nerrors > 0) { printf("%s:", argv[0]); arg_print_syntax(stdout, argtable, "\n"); arg_print_errors(stdout, end, argv[0]); arg_freetable(argtable, nbArgs+1); return EXIT_FAILURE; } discountFactor = g->dval[0]; maxNbEvaluations = n->ival[0]; branchingFactor = b->ival[0]; initGenerativeModelParameters(); if(branchingFactor) K = branchingFactor; initGenerativeModel(); if(i->count) crtState = makeState(i->sval[0]); else crtState = initState(); #if USE_SDL isDisplayed = d->count; isFullscreen = f->count; verbose = v->count; if(r->count) strcpy(resolution, r->sval[0]); #endif nbTimestep = s->ival[0]; keepingTree = k->count; arg_freetable(argtable, nbArgs+1); instance = uniform_initInstance(crtState, discountFactor); #ifdef USE_SDL if(isDisplayed) { if(initViewer(resolution, uniform_drawingProcedure, isFullscreen) == -1) return EXIT_FAILURE; viewer(crtState, NULL, 0.0, instance); } #endif do { if(keepingTree) uniform_keepSubtree(instance); else uniform_resetInstance(instance, crtState); optimalAction = uniform_planning(instance, maxNbEvaluations); isTerminal = nextStateReward(crtState, optimalAction, &nextState, &reward); freeState(crtState); crtState = nextState; if(verbose) { printState(crtState); printAction(optimalAction); printf("reward: %f depth: %u\n", reward, uniform_getMaxDepth(instance)); } #ifdef USE_SDL } while(!isTerminal && (nbTimestep < 0 || --nbTimestep) && !viewer(crtState, optimalAction, reward, instance)); #else } while(!isTerminal && (nbTimestep < 0 || --nbTimestep));
int main(int argc, char *argv[]) { SDL_AudioSpec want, have; SDL_AudioDeviceID dev; Streamer streamer; int retcode = 0; // Init SDL Audio if(SDL_Init(SDL_INIT_AUDIO) != 0) { fprintf(stderr, "Error: %s\n", SDL_GetError()); return 1; } // commandline argument parser options struct arg_lit *help = arg_lit0("h", "help", "print this help and exit"); struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit"); struct arg_file *file = arg_file1("f", "file", "<file>", "SOUNDS.DAT file"); struct arg_file *output = arg_file0("o", "output", "<file>", "Output sounds file"); struct arg_int *sid = arg_int0("s", "sound", "<int>", "Sound ID"); struct arg_int *sampleprint = arg_int0(NULL, "print", "<int>", "Print first n bytes from selected sound"); struct arg_lit *play = arg_lit0("p", "play", "Play selected sound"); struct arg_file *export = arg_file0("e", "export", "<file>", "Export selected sound to AU file"); struct arg_file *import = arg_file0("i", "import", "<file>", "Import selected sound from AU file"); struct arg_end *end = arg_end(20); void* argtable[] = {help,vers,file,output,sid,sampleprint,play,export,import,end}; const char* progname = "soundtool"; // Make sure everything got allocated if(arg_nullcheck(argtable) != 0) { printf("%s: insufficient memory\n", progname); goto exit_0; } // Parse arguments int nerrors = arg_parse(argc, argv, argtable); // Handle help if(help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout, argtable, "\n"); printf("\nArguments:\n"); arg_print_glossary(stdout, argtable, "%-25s %s\n"); goto exit_0; } // Handle version if(vers->count > 0) { printf("%s v0.1\n", progname); printf("Command line One Must Fall 2097 SOUNDS.DAT file editor.\n"); printf("Source code is available at https://github.com/omf2097 under MIT license.\n"); printf("(C) 2013 Tuomas Virtanen\n"); goto exit_0; } // Handle errors if(nerrors > 0) { arg_print_errors(stdout, end, progname); printf("Try '%s --help' for more information.\n", progname); goto exit_0; } // Open sounds.dat sd_sound_file sf; sd_sounds_create(&sf); retcode = sd_sounds_load(&sf, file->filename[0]); if(retcode) { printf("Error %d: %s\n", retcode, sd_get_error(retcode)); goto exit_1; } if(sid->count > 0) { // Sound ID to handle int sound_id = sid->ival[0]; const sd_sound *sound = sd_sounds_get(&sf, sound_id-1); if(sound == NULL) { printf("Invalid sound ID"); goto exit_1; } if(sampleprint->count > 0) { int count = (sampleprint->ival[0] > sound->len) ? sound->len : sampleprint->ival[0]; printf("Sample size = %d\n", sound->len); printf("Unknown = %d\n", sound->unknown); printf("Attempting to print %d first bytes.\n", count); for(int i = 0; i < count; i++) { unsigned int s = sound->data[i] & 0xFF; printf("%2x ", s); } } else if(play->count > 0) { printf("Attempting to play sample #%d.\n", sound_id); // Make sure there is data at requested ID position if(sound->len <= 0) { printf("Sample does not contain data.\n"); goto exit_1; } // Streamer streamer.size = sound->len; streamer.pos = 0; streamer.data = sound->data; // Initialize required audio SDL_zero(want); want.freq = 8000; want.format = AUDIO_U8; want.channels = 1; want.samples = 4096; want.callback = stream; want.userdata = &streamer; // Open device, play file dev = SDL_OpenAudioDevice(NULL, 0, &want, &have, 0); if(dev == 0) { printf("Failed to open audio dev: %s\n", SDL_GetError()); goto exit_0; } else { if(have.format != want.format) { printf("Could not get correct playback format.\n"); } else { printf("Starting playback ...\n"); SDL_PauseAudioDevice(dev, 0); while(streamer.pos < streamer.size) { SDL_Delay(100); } printf("All done.\n"); } SDL_CloseAudioDevice(dev); } } else if(import->count > 0) { if(sd_sound_from_au(&sf, sound_id, import->filename[0]) != SD_SUCCESS) { printf("Importing sample %d from file %s failed.\n", sound_id, import->filename[0]); } else { printf("Importing sample %d from file %s succeeded.\n", sound_id, import->filename[0]); } } else if(export->count > 0) { if(sd_sound_to_au(&sf, sound_id, export->filename[0]) != SD_SUCCESS) { printf("Exporting sample %d to file %s failed.\n", sound_id, export->filename[0]); } else { printf("Exporting sample %d to file %s succeeded.\n", sound_id, export->filename[0]); } } else {
int main(int argc, char *argv[]) { struct arg_str *cblOpt = arg_str1("c", "cable", "nero:<VID>:<PID> | xil3 | dusb", "cable driver to use"); struct arg_lit *scanOpt = arg_lit0("s", "scan", " scan the JTAG chain"); struct arg_file *bitOpt = arg_file0("b", "bitfile", "<fileName>", " bit file to load"); struct arg_uint *devOpt = arg_uint0("d", "device", "<device>", " target device (default \"1\")"); struct arg_lit *helpOpt = arg_lit0("h", "help", " print this help and exit\n"); struct arg_end *endOpt = arg_end(20); void* argTable[] = {cblOpt, scanOpt, bitOpt, devOpt, helpOpt, endOpt}; const char *progName = "xilprg"; uint32 exitCode = 0; int numErrors; const char *cable, *bitFile; uint32 devNum; char line[1024]; char configFileName[4097]; // TODO: Fix, somehow. if ( arg_nullcheck(argTable) != 0 ) { fprintf(stderr, "%s: insufficient memory\n", progName); fail(1); } numErrors = arg_parse(argc, argv, argTable); if ( helpOpt->count > 0 ) { printf("Xilinx Programmer 0.6 Copyright (C) 2006-2011 Zoltan Csizmadia & Chris McClelland\n\nUsage: %s", progName); arg_print_syntax(stdout, argTable, "\n"); printf("\nProgram a Xilinx FPGA.\n\n"); arg_print_glossary(stdout, argTable," %-10s %s\n"); fail(0); } if ( numErrors > 0 ) { arg_print_errors(stdout, endOpt, progName); fprintf(stderr, "Try '%s --help' for more information.\n", progName); fail(2); } if ( (scanOpt->count == 0 && bitOpt->count == 0) || (scanOpt->count != 0 && bitOpt->count != 0) ) { fprintf(stderr, "%s: you must specify either -s|--scan or -b|--bitfile, but not both\n", progName); fprintf(stderr, "Try '%s --help' for more information.\n", progName); fail(3); } cable = cblOpt->sval[0]; bitFile = bitOpt->count ? bitOpt->filename[0] : NULL; devNum = devOpt->count ? devOpt->ival[0] : 1; if ( initialize() ) { fprintf(stderr, "%s failed to initialize!\n", progName); fail(4); } if ( getConfigFullPath("xilprg.conf", configFileName, sizeof(configFileName)) ) { fprintf(stderr, "%s failed to determine the location of its config file!\n", progName); fail(5); } if ( load_config_file(configFileName) ) { fprintf(stderr, "%s failed to load its config file from %s!\n", progName, configFileName); fail(6); } try { sprintf(line, "cable %s", cable); process_command_line(line); if ( scanOpt->count ) { process_command_line("detect"); } else { sprintf(line, "program %lu \"%s\"", devNum, bitFile); process_command_line(line); } } catch ( const std::exception &ex ) { fprintf(stderr, "%s failed: %s!\n", progName, ex.what()); fail(7); } cleanup: uninitialize(); arg_freetable(argTable, sizeof(argTable)/sizeof(argTable[0])); return exitCode; }
int main(int argc, char* argv[]) { // commandline argument parser options struct arg_lit *help = arg_lit0("h", "help", "print this help and exit"); struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit"); struct arg_file *file = arg_file1("f", "file", "<file>", "Input altpals file"); struct arg_int *pal = arg_int1("p", "palette", "<number>", "Select a palette"); struct arg_file *export = arg_file0("e", "export", "<file>", "Export selected palette to GPL file"); struct arg_file *import = arg_file0("i", "import", "<file>", "Import selected palette from GPL file"); struct arg_file *output = arg_file0("o", "output", "<file>", "Output altpals file"); struct arg_end *end = arg_end(20); void* argtable[] = {help,vers,file,pal,output,import,export,end}; const char* progname = "altpaltool"; // Make sure everything got allocated if(arg_nullcheck(argtable) != 0) { printf("%s: insufficient memory\n", progname); goto exit_0; } // Parse arguments int nerrors = arg_parse(argc, argv, argtable); // Handle help if(help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout, argtable, "\n"); printf("\nArguments:\n"); arg_print_glossary(stdout, argtable, "%-25s %s\n"); goto exit_0; } // Handle version if(vers->count > 0) { printf("%s v0.1\n", progname); printf("Command line One Must Fall 2097 Altpals file editor.\n"); printf("Source code is available at https://github.com/omf2097 under MIT license.\n"); printf("(C) 2014 Tuomas Virtanen\n"); goto exit_0; } // Handle errors if(nerrors > 0) { arg_print_errors(stdout, end, progname); printf("Try '%s --help' for more information.\n", progname); goto exit_0; } // Need import or export ... if(pal->count > 0 && import->count == 0 && export->count == 0) { printf("Define either --import or --export with --palette!\n"); goto exit_0; } // Make sure output is set if(import->count > 0 && output->count <= 0) { printf("Define --output with --import.\n"); goto exit_0; } // Load file sd_altpal_file alt; sd_altpal_create(&alt); int ret = sd_altpals_load(&alt, file->filename[0]); if(ret != SD_SUCCESS) { printf("Unable to load altpals file %s: %s.\n", file->filename[0], sd_get_error(ret)); goto exit_1; } // Check ID int pal_id = pal->ival[0]; if(pal_id < 0 || pal_id > SD_ALTPALS_PALETTES) { printf("Palette index %d does not exist!\n", pal_id); goto exit_1; } // Check what to do if(export->count > 0) { ret = sd_palette_to_gimp_palette(&alt.palettes[pal_id], export->filename[0]); if(ret == SD_SUCCESS) { printf("Palette %d exported to file %s succesfully.\n", pal_id, export->filename[0]); } else {
int main(int argc, char **argv) { const char* progname = "rm"; struct arg_lit *dir = arg_lit0("d", "directory", "unlink file(s), even if it is a non-empty directory"); struct arg_rem *dir2 = arg_rem( NULL, "(super-user only)"); struct arg_lit *force = arg_lit0("f", "force", "ignore nonexistant files, never prompt"); struct arg_lit *inter = arg_lit0("i", "interactive", "prompt before any removal"); struct arg_lit *recur = arg_lit0("rR","recursive", "remove the contents of directories recursively"); struct arg_lit *verb = arg_lit0("v", "verbose", "explain what is being done"); struct arg_lit *help = arg_lit0(NULL,"help", "print this help and exit"); struct arg_lit *vers = arg_lit0(NULL,"version", "print version information and exit"); struct arg_file *files = arg_filen(NULL,NULL,NULL,1,argc+2,NULL); struct arg_end *end = arg_end(20); void* argtable[] = {dir,dir2,force,inter,recur,verb,help,vers,files,end}; int exitcode=0; int nerrors; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n",progname); exitcode=1; goto exit; } /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout,argtable,"\n"); printf("Remove (unlink) the specified file(s).\n\n"); arg_print_glossary(stdout,argtable," %-20s %s\n"); printf("\nReport bugs to <no-one> as this is just an example program.\n"); exitcode=0; goto exit; } /* special case: '--version' takes precedence error reporting */ if (vers->count > 0) { printf("'%s' example program for the \"argtable\" command line argument parser.\n",progname); printf("September 2003, Stewart Heitmann\n"); exitcode=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,progname); printf("Try '%s --help' for more information.\n",progname); exitcode=1; goto exit; } /* command line options are all ok, now perform the "rm" functionality */ mymain(dir->count, force->count, inter->count, recur->count, verb->count, files->filename, files->count); exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return exitcode; }
int main(int argc, char* argv[]) { // commandline argument parser options struct arg_lit *help = arg_lit0("h", "help", "print this help and exit"); struct arg_lit *vers = arg_lit0("v", "version", "print version information and exit"); struct arg_str *astr = arg_str1("s", "str", "<str>", "Animation string"); struct arg_end *end = arg_end(20); void* argtable[] = {help,vers,astr,end}; const char* progname = "omf_parse"; int from_stdin = 0; // Make sure everything got allocated if(arg_nullcheck(argtable) != 0) { printf("%s: insufficient memory\n", progname); goto exit_0; } // Parse arguments int nerrors = arg_parse(argc, argv, argtable); if(nerrors > 0) { arg_print_errors(stdout, end, progname); printf("Try '%s --help' for more information.\n", progname); goto exit_0; } // Handle version if(vers->count > 0) { printf("%s v0.1\n", progname); printf("Command line One Must Fall 2097 Animation string parser\n"); printf("Source code is available at https://github.com/omf2097 under MIT license.\n"); printf("(C) 2014 Tuomas Virtanen\n"); goto exit_0; } // Handle help if(help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout, argtable, "\n"); printf("\nArguments:\n"); arg_print_glossary(stdout, argtable, "%-25s %s\n"); goto exit_0; } const char *str = *astr->sval; if (strcmp("-", *astr->sval) == 0) { from_stdin = 1; char *tmp_str = malloc(512); fgets(tmp_str, 512, stdin); // throttle the newline tmp_str[strlen(tmp_str)-1] = '\0'; str = tmp_str; } // Print some data printf("Parsing \"%s\".\n\n", str); int err_pos; sd_script script; sd_script_create(&script); int ret = sd_script_decode(&script, str, &err_pos); if(ret != SD_SUCCESS) { if(ret == SD_INVALID_TAG) { printf("Bad input string! Error at position %d.\n", err_pos); } if(ret == SD_ANIM_INVALID_STRING) { printf("Bad input string!\n"); } goto exit_1; } for(int frame_id = 0; frame_id < script.frame_count; frame_id++) { sd_script_frame *frame = &script.frames[frame_id]; printf("%d. Frame %d: '%c%d'\n", frame_id, frame->sprite, (char)(frame->sprite+65), frame->tick_len); for(int tag_id = 0; tag_id < frame->tag_count; tag_id++) { sd_script_tag *tag = &frame->tags[tag_id]; if(tag->desc == NULL) { tag->desc = ""; } if(tag->has_param) { printf(" %-4s %-4d %s\n", tag->key, tag->value, tag->desc); } else { printf(" %-4s %s\n", tag->key, tag->desc); } } } exit_1: sd_script_free(&script); exit_0: if (from_stdin) { free((char*)str); } arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0])); return 0; }
int main(int argc, char* argv[]) { struct arg_lit *help; struct arg_file *input, *output; struct arg_str *rotation; struct arg_end *end; /* command line parsing through argtable package */ void* argtable[] = { help = arg_lit0("h", "help", "display this help and exit"), input = arg_file0("i", "input", "input", "name of the input file (default stdin"), output = arg_file0("o", "output", "file", "name of the output file (default stdout)"), rotation = arg_str1(NULL, NULL, "\"x y z w\"", "rotate w degrees around axis x y z"), end = arg_end(20) }; const char* progname = "xyztk-rotate"; int rc = 0; int nerrors; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n", progname); rc=1; goto exit; } /* set default values */ /* parse the command line flags, overriding default values */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout,argtable,"\n"); printf("\n"); arg_print_glossary(stdout,argtable," %-40s %s\n"); printf("\n"); rc=0; goto exit; } /* special case: no command line options induces brief help */ if (argc==1) { printf("Try '%s --help' for more information.\n",progname); rc=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,progname); printf("Try '%s --help' for more information.\n",progname); rc=1; goto exit; } /* set global structures */ /* initialize I/O pointers */ FILE* in; if (input->count) { in = fopen(input->filename[0], "r"); } else { in = stdin; } FILE* out; if (output->count) { out = fopen(output->filename[0], "w"); } else { out = stdout; } /* initialize molecule structure */ xyztk_molecule_t molecule; xyztk_molecule_load (&molecule, in); /* read rotation from string */ xyztk_quat_t r; sscanf (rotation->sval[0], "%lf%lf%lf%lf", &r.x, &r.y, &r.z, &r.w); xyztk_molecule_rotate (&molecule, &r); /* print output */ int i; fprintf(out, "%d\n", molecule.n_atoms); fprintf(out, "%s", molecule.name); for (i = 0; i < molecule.n_atoms; ++i) { fprintf(out, "%-8s %20.14lf %20.14lf %20.14lf \n", molecule.label[i].s, molecule.coord[i].x, molecule.coord[i].y, molecule.coord[i].z); } exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return rc; }
int main(int argc, char **argv) { struct arg_int *serverport = arg_int0("pP","port","","serverport, default: 1337"); struct arg_str *serialport = arg_str0("sS", "serial", "", "serial port, default /dev/ttyS0"); struct arg_int *baud = arg_int0("bB", "baud","","baudrate, default: 9600"); struct arg_str *client = arg_str0("cC","client","","only accept messages from this client"); struct arg_lit *help = arg_lit0("hH","help","print this help and exit"); struct arg_lit *version = arg_lit0(NULL,"version","print version information and exit"); struct arg_lit *debug = arg_lit0(NULL,"debug","print debug messages"); struct arg_lit *silent = arg_lit0(NULL,"silent","print no messages"); struct arg_end *end = arg_end(20); void* argtable[] = {serverport,serialport,baud,client,help,version,debug,silent,end}; int nerrors; int exitcode=0; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n",PROGNAME); exitcode=1; goto exit; } /* set any command line default values prior to parsing */ /* nothing */ /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("usage: %s", PROGNAME); arg_print_syntax(stdout,argtable,"\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); exitcode=0; goto exit; } /* special case: '--version' takes precedence error reporting */ if (version->count > 0) { printf("'%s' version ",PROGNAME); printf("%s",VERSION); printf("\nGIT-REVISION: "); printf("%s",GITREV); printf("\n%s receives udp-packets and controls\n",PROGNAME); printf("the EIWOMISA controller over RS-232\n"); printf("%s",COPYRIGHT); printf("\n"); exitcode=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,PROGNAME); printf("Try '%s --help' for more information.\n",PROGNAME); exitcode=1; goto exit; } /* special case: with no command line options induce brief help and use defaults */ if (argc==1) { printf("No command-line options present, using defaults.\n",PROGNAME); printf("Try '%s --help' for more information.\n",PROGNAME); } /* normal case: take the command line options at face value */ /* check if server port is set */ int i_serverport = -1; if(serverport->count>0) i_serverport = (int)serverport->ival[0]; /* check if serial port is set */ char* i_serialport = NULL; if(serialport->count>0) i_serialport = (char*)serialport->sval[0]; /* check if baudrate is set */ int i_baudrate = -1; if(baud->count>0) i_baudrate = (int)baud->ival[0]; /* check if client ip is set */ char* i_client = NULL; if(client->count>0) { i_client = (char *)client->sval[0]; } /* --debug enables debug messages */ if (debug->count > 0) { printf("debug messages enabled\n"); msglevel = 3; } /* --silent disables all (!) messages */ if (silent->count > 0) { msglevel = 0; } exitcode = mymain(i_serverport, i_serialport, i_baudrate, i_client); exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return exitcode; }
int main(int argc, char **argv) { const char* progname = "uname"; struct arg_lit *all = arg_lit0("a", "all", "print all information, in the following order:"); struct arg_lit *kname = arg_lit0("s", "kernel-name", "print the kernel name"); struct arg_lit *nname = arg_lit0("n", "nodename", "print the node name"); struct arg_lit *krel = arg_lit0("r", "kernel-release", "print the kernel release"); struct arg_lit *kver = arg_lit0("v", "kernel-version", "print the kernel version"); struct arg_lit *mach = arg_lit0("m", "machine", "print the machine hardware name"); struct arg_lit *proc = arg_lit0("p", "processor", "print the processor type"); struct arg_lit *hard = arg_lit0("i", "hardware-platform","print the hardware platform"); struct arg_lit *opsys = arg_lit0("o", "operating-system", "print the operating system"); struct arg_lit *help = arg_lit0(NULL,"help", "print this help and exit"); struct arg_lit *vers = arg_lit0(NULL,"version", "print version information and exit"); struct arg_end *end = arg_end(20); void* argtable[] = {all,kname,nname,krel,kver,mach,proc,hard,opsys,help,vers,end}; int nerrors; int exitcode=0; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n",progname); exitcode=1; goto exit; } /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout,argtable,"\n"); printf("Print certain system information. With no options, same as -s.\n\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); printf("\nReport bugs to <foo@bar>.\n"); exitcode=0; goto exit; } /* special case: '--version' takes precedence error reporting */ if (vers->count > 0) { printf("'%s' example program for the \"argtable\" command line argument parser.\n",progname); printf("September 2003, Stewart Heitmann\n"); exitcode=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,progname); printf("Try '%s --help' for more information.\n",progname); exitcode=1; goto exit; } /* special case: uname with no command line options is equivalent to "uname -s" */ if (argc==1) { exitcode = mymain(0,1,0,0,0,0,0,0); goto exit; } /* special case: "uname -a" is equivalent to "uname -snrvmpi" */ if (all->count>0) { exitcode = mymain(1,1,1,1,1,1,1,1); goto exit; } /* normal case: take the command line options at face value */ exitcode = mymain(kname->count, nname->count, krel->count, kver->count, mach->count, proc->count, hard->count, opsys->count); exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return exitcode; }
int main(int argc, char **argv) { /* SYNTAX 1: insert [-nvR] <file> [file]... -o <file> */ struct arg_rex *cmd1 = arg_rex1(NULL, NULL, "insert", NULL, REG_ICASE, NULL); struct arg_lit *noact1 = arg_lit0("n", NULL, "take no action"); struct arg_lit *verbose1 = arg_lit0("v", "verbose", "verbose messages"); struct arg_lit *recurse1 = arg_lit0("R", NULL, "recurse through subdirectories"); struct arg_file *infiles1 = arg_filen(NULL, NULL, NULL, 1,argc+2, "input file(s)"); struct arg_file *outfile1 = arg_file0("o", NULL, "<output>", "output file (default is \"-\")"); struct arg_end *end1 = arg_end(20); void* argtable1[] = {cmd1,noact1,verbose1,recurse1,infiles1,outfile1,end1}; int nerrors1; /* SYNTAX 2: remove [-nv] <file> */ struct arg_rex *cmd2 = arg_rex1(NULL, NULL, "remove", NULL, REG_ICASE, NULL); struct arg_lit *noact2 = arg_lit0("n", NULL, NULL); struct arg_lit *verbose2 = arg_lit0("v", "verbose", NULL); struct arg_file *infiles2 = arg_file1(NULL, NULL, NULL, NULL); struct arg_end *end2 = arg_end(20); void* argtable2[] = {cmd2,noact2,verbose2,infiles2,end2}; int nerrors2; /* SYNTAX 3: search [-v] <pattern> [-o <file>] [--help] [--version] */ struct arg_rex *cmd3 = arg_rex1(NULL, NULL, "search", NULL, REG_ICASE, NULL); struct arg_lit *verbose3 = arg_lit0("v", "verbose", NULL); struct arg_str *pattern3 = arg_str1(NULL, NULL, "<pattern>", "search string"); struct arg_file *outfile3 = arg_file0("o", NULL, "<output>", NULL); struct arg_end *end3 = arg_end(20); void* argtable3[] = {cmd3,verbose3,pattern3,outfile3,end3}; int nerrors3; /* SYNTAX 4: [-help] [-version] */ struct arg_lit *help4 = arg_lit0(NULL,"help", "print this help and exit"); struct arg_lit *version4 = arg_lit0(NULL,"version", "print version information and exit"); struct arg_end *end4 = arg_end(20); void* argtable4[] = {help4,version4,end4}; int nerrors4; const char* progname = "multisyntax"; int exitcode=0; /* verify all argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable1)!=0 || arg_nullcheck(argtable2)!=0 || arg_nullcheck(argtable3)!=0 || arg_nullcheck(argtable4)!=0 ) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n",progname); exitcode=1; goto exit; } /* set any command line default values prior to parsing */ outfile1->filename[0]="-"; outfile3->filename[0]="-"; /* Above we defined a separate argtable for each possible command line syntax */ /* and here we parse each one in turn to see if any of them are successful */ nerrors1 = arg_parse(argc,argv,argtable1); nerrors2 = arg_parse(argc,argv,argtable2); nerrors3 = arg_parse(argc,argv,argtable3); nerrors4 = arg_parse(argc,argv,argtable4); /* Execute the appropriate main<n> routine for the matching command line syntax */ /* In this example program our alternate command line syntaxes are mutually */ /* exclusive, so we know in advance that only one of them can be successful. */ if (nerrors1==0) exitcode = mymain1(noact1->count, verbose1->count, recurse1->count, outfile1->filename[0], infiles1->filename, infiles1->count); else if (nerrors2==0) exitcode = mymain2(noact2->count, verbose2->count, infiles2->filename[0]); else if (nerrors3==0) exitcode = mymain3(verbose3->count, pattern3->sval[0], outfile3->filename[0]); else if (nerrors4==0) exitcode = mymain4(help4->count, version4->count, progname, argtable1, argtable2, argtable3, argtable4); else { /* We get here if the command line matched none of the possible syntaxes */ if (cmd1->count > 0) { /* here the cmd1 argument was correct, so presume syntax 1 was intended target */ arg_print_errors(stdout,end1,progname); printf("usage: %s ", progname); arg_print_syntax(stdout,argtable1,"\n"); } else if (cmd2->count > 0) { /* here the cmd2 argument was correct, so presume syntax 2 was intended target */ arg_print_errors(stdout,end2,progname); printf("usage: %s ", progname); arg_print_syntax(stdout,argtable2,"\n"); } else if (cmd3->count > 0) { /* here the cmd3 argument was correct, so presume syntax 3 was intended target */ arg_print_errors(stdout,end3,progname); printf("usage: %s ", progname); arg_print_syntax(stdout,argtable3,"\n"); } else { /* no correct cmd literals were given, so we cant presume which syntax was intended */ printf("%s: missing <insert|remove|search> command.\n",progname); printf("usage 1: %s ", progname); arg_print_syntax(stdout,argtable1,"\n"); printf("usage 2: %s ", progname); arg_print_syntax(stdout,argtable2,"\n"); printf("usage 3: %s ", progname); arg_print_syntax(stdout,argtable3,"\n"); printf("usage 4: %s", progname); arg_print_syntax(stdout,argtable4,"\n"); } } exit: /* deallocate each non-null entry in each argtable */ arg_freetable(argtable1,sizeof(argtable1)/sizeof(argtable1[0])); arg_freetable(argtable2,sizeof(argtable2)/sizeof(argtable2[0])); arg_freetable(argtable3,sizeof(argtable3)/sizeof(argtable3[0])); arg_freetable(argtable4,sizeof(argtable4)/sizeof(argtable4[0])); return exitcode; }
int main(int argc, char* argv[]) { double discountFactor = 0.9; unsigned int i = 0; unsigned int n = 0; FILE* initFileFd = NULL; FILE* outputFileFd = NULL; unsigned int nbIterations = 0; int readFscanf = -1; optimistic_instance* optimistic = NULL; struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state"); struct arg_int* k = arg_int1("k", NULL, "<n>", "The branching factor of the problem"); struct arg_int* it = arg_int1("n", NULL, "<n>", "The number of iterations"); struct arg_file* outputFile = arg_file1("o", NULL, "<file>", "The output file"); struct arg_end* end = arg_end(5); void* argtable[5]; int nerrors = 0; argtable[0] = initFile; argtable[1] = it; argtable[2] = outputFile; argtable[3] = k; argtable[4] = end; if(arg_nullcheck(argtable) != 0) { printf("error: insufficient memory\n"); arg_freetable(argtable, 5); return EXIT_FAILURE; } nerrors = arg_parse(argc, argv, argtable); if(nerrors > 0) { printf("%s:", argv[0]); arg_print_syntax(stdout, argtable, "\n"); arg_print_errors(stdout, end, argv[0]); arg_freetable(argtable, 5); return EXIT_FAILURE; } nbIterations = it->ival[0]; initGenerativeModelParameters(); K = k->ival[0]; initGenerativeModel(); outputFileFd = fopen(outputFile->filename[0], "w"); initFileFd = fopen(initFile->filename[0], "r"); readFscanf = fscanf(initFileFd, "%u\n", &n); arg_freetable(argtable, 5); optimistic = optimistic_initInstance(NULL, discountFactor); for(; i < n; i++) { char str[1024]; unsigned int j = 0; readFscanf = fscanf(initFileFd, "%s\n", str); state* initial = makeState(str); double crtOptimalValue = 0.0; unsigned int crtOptimalAction = 0; for(; j < K; j++) { state* nextState = NULL; double reward = 0.0; char isTerminal = 0; isTerminal = nextStateReward(initial, actions[j], &nextState, &reward); optimistic_resetInstance(optimistic, nextState); freeState(nextState); optimistic_planning(optimistic, nbIterations); if(optimistic->crtOptimalValue > crtOptimalValue) { crtOptimalValue = optimistic->crtOptimalValue; crtOptimalAction = j; } fprintf(outputFileFd, "%.15f,", optimistic->crtOptimalValue); printf("%uth action done\n", j+1); fflush(outputFileFd); } fprintf(outputFileFd, "%u\n", crtOptimalAction); freeState(initial); printf("%uth initial state processed\n", i+1); fflush(outputFileFd); } fclose(outputFileFd); fclose(initFileFd); optimistic_uninitInstance(&optimistic); freeGenerativeModel(); freeGenerativeModelParameters(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { struct arg_lit *list = arg_lit0("lL",NULL, "list files"); struct arg_lit *recurse = arg_lit0("R",NULL, "recurse through subdirectories"); struct arg_int *repeat = arg_int0("k","scalar",NULL, "define scalar value k (default is 3)"); struct arg_str *defines = arg_strn("D","define","MACRO",0,argc+2, "macro definitions"); struct arg_file *outfile = arg_file0("o",NULL,"<output>", "output file (default is \"-\")"); struct arg_lit *verbose = arg_lit0("v","verbose,debug", "verbose messages"); struct arg_lit *help = arg_lit0(NULL,"help", "print this help and exit"); struct arg_lit *version = arg_lit0(NULL,"version", "print version information and exit"); struct arg_file *infiles = arg_filen(NULL,NULL,NULL,1,argc+2, "input file(s)"); struct arg_end *end = arg_end(20); void* argtable[] = {list,recurse,repeat,defines,outfile,verbose,help,version,infiles,end}; const char* progname = "myprog"; int nerrors; int exitcode=0; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n",progname); exitcode=1; goto exit; } /* set any command line default values prior to parsing */ repeat->ival[0]=3; outfile->filename[0]="-"; /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc,argv,argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout,argtable,"\n"); printf("This program demonstrates the use of the argtable2 library\n"); printf("for parsing command line arguments.\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); exitcode=0; goto exit; } /* special case: '--version' takes precedence error reporting */ if (version->count > 0) { printf("'%s' example program for the \"argtable\" command line argument parser.\n",progname); printf("September 2003, Stewart Heitmann\n"); exitcode=0; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout,end,progname); printf("Try '%s --help' for more information.\n",progname); exitcode=1; goto exit; } /* special case: uname with no command line options induces brief help */ if (argc==1) { printf("Try '%s --help' for more information.\n",progname); exitcode=0; goto exit; } /* normal case: take the command line options at face value */ exitcode = mymain(list->count, recurse->count, repeat->ival[0], defines->sval, defines->count, outfile->filename[0], verbose->count, infiles->filename, infiles->count); exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return exitcode; }
int main(int argc, char *argv[]) { struct arg_dbl *_dt = arg_dbl0("t", "time-step", NULL, "time step for time history integration"); struct arg_dbl *_d = arg_dbl0("d", "duration", NULL, "the duration of the analysis"); struct arg_dbl *_a = arg_dbl0("a", "alpha", NULL, "Reynolds damping alpha"); struct arg_dbl *_b = arg_dbl0("b", "beta", NULL, "Reynolds damping beta"); struct arg_dbl *_E = arg_dbl0("E", "youngs-modulus", NULL, "the material stiffness"); struct arg_dbl *_A = arg_dbl0("A", "area", NULL, "the member's cross-sectional stiffness"); struct arg_dbl *_I = arg_dbl0("I", "moment-of-interia", NULL, "the member's moment of interia"); struct arg_dbl *_m = arg_dbl0("m", "mass", NULL, "the mass at the top of the member"); struct arg_dbl *_F = arg_dbl0("F", "force", NULL, "the force applied at the top of the member"); struct arg_dbl *_h = arg_dbl0("h", "height", NULL, "the height of the member"); _dt->dval[0] = 0.1; _d->dval[0] = 10; _a->dval[0] = 0.0115; _b->dval[0] = 0.0115; _A->dval[0] = 0.0002; _E->dval[0] = 200000000; _I->dval[0] = 0.0000000133333; _m->dval[0] = 10; _F->dval[0] = 40; _h->dval[0] = 2; struct arg_end *end = arg_end(10); void* argtable[] = {_dt,_d,_a,_b,_A,_E,_I,_m,_F,_h,end}; const char* progname = "sdof-step"; int exitcode = 0, returnvalue = 0; int nerrors = arg_nullcheck(argtable); if(nerrors != 0) { cerr << "Not enough memory to proceed" << endl; arg_print_errors(stderr,end,progname); arg_freetable(argtable,sizeof(argtable)/sizeof(argtable[0])); return nerrors; } nerrors = arg_parse(argc, argv, argtable); if(nerrors != 0) { arg_print_errors(stderr,end,progname); cerr << "Usage: " << endl; arg_print_syntaxv(stderr,argtable,"\n"); return(nerrors); } FILE* param = fopen("parameters.txt","w"); fprintf(param,"Input Parameters:\n"); fprintf(param,"Time step: %lf\n",_dt->dval[0]); fprintf(param,"Duration: %lf\n",_d->dval[0]); fprintf(param,"alpha: %lf\n",_a->dval[0]); fprintf(param,"beta: %lf\n",_b->dval[0]); fprintf(param,"area: %lf\n",_A->dval[0]); fprintf(param,"I: %lf\n",_I->dval[0]); fprintf(param,"E: %lf\n",_E->dval[0]); fprintf(param,"mass: %lf\n",_m->dval[0]); fprintf(param,"h: %lf\n",_h->dval[0]); fprintf(param,"F: %lf\n",_F->dval[0]); fclose(param); double* x = new double[3]; double* v = new double[3]; double* a = new double[3]; bool* constrainType = new bool[3]; double* constrainValue = new double[3]; double* mass = new double[3]; Node** nodes = new Node*[2]; x[0] = x[1] = x[2] = 0.0; v[0] = v[1] = v[2] = a[0] = a[1] = a[2] = 0.0; constrainType[0] = Node::DISP; constrainType[1] = Node::DISP; constrainType[2] = Node::DISP; constrainValue[0] = 0.0; constrainValue[1] = 0.0; constrainValue[2] = 0.0; mass[0] = _m->dval[0]; mass[1] = _m->dval[0]; mass[2] = _m->dval[0]/4; nodes[0] = new Node(x, v, a, 3, constrainType, constrainValue, mass, 0); // set y coord of second node x[1] = _h->dval[0]; constrainType[0] = Node::FORCE; constrainType[1] = Node::FORCE; constrainType[2] = Node::FORCE; cerr << "about to make the second node" << endl; nodes[1] = new Node(x, v, a, 3, constrainType, constrainValue, mass, 1); cerr << "made 2nd node" << endl; Element** elements = new Element*[1]; elements[0] = new LinearBeam(nodes, 2, _A->dval[0], _E->dval[0], _I->dval[0]); cerr << "generated elements" << endl; double dt = _dt->dval[0]; double time = _d->dval[0]; int nSteps = (int) (time / dt); cerr << "Number of Time Steps: " << nSteps << endl; double wf = 2; cerr << "bo" << endl; double **loads; cerr << "bi" << endl; loads = new double*[6]; for(int i = 0; i < 6; i++) { loads[i] = new double[nSteps]; } cerr << "ba" << endl; double E = _E->dval[0]; double I = _I->dval[0]; double L = _h->dval[0]; double k = 3*E*I/(L*L*L); double w = sqrt(k/_m->dval[0]); double T = 2*M_PI/w; cerr << "Period is " << T << endl; for(int i = 0; i < nSteps; i++) { for(int j = 0; j < 6; j++) loads[j][i] = 0.0; } loads[3][2] = _F->dval[0]; FILE* load = fopen("load.csv", "w"); for(int i = 0; i < nSteps; i++) { for(int j = 0; j < 6; j++) fprintf(load,"%lf,",loads[j][i]); fprintf(load,"\n");; } Enoch* enoch = new Enoch(nodes,elements,loads,2,1,nSteps, dt, _a->dval[0], _b->dval[0], 0.5, 0.25); enoch->run(); }
int main(int argc, char *argv[]) { struct arg_int *lport = arg_int0("p", "port", "<localport>", "listening port (default is 8888)"); struct arg_int *debug = arg_int0("d", "debug", "<level>", "debug output level (default is 4)"); #ifdef PUBKEY_DATA_ struct arg_str *key = arg_str0("k", "key", "<keyfile>", "public key file (default is built-in)"); #else struct arg_str *key = arg_str0("k", "key", "<keyfile>", "public key file (default is pubkey)"); #endif #ifdef ROOTPEM_DATA_ struct arg_str *certdb= arg_str0(NULL, "certdb", "<certfile>", "trusted CA database (default is built-in)"); #else struct arg_str *certdb= arg_str0(NULL, "certdb", "<certfile>", "trusted CA database (default is root.pem)"); #endif struct arg_lit *help = arg_lit0(NULL,"help", "print this help and exit"); struct arg_str *host = arg_str1(NULL, NULL, "<host>[:port]", "non-blocked TLS server"); struct arg_end *end = arg_end(20); void *argtable[] = {lport, debug, key, certdb, help, host, end}; const char* progname = "telex-client"; int nerrors; int ret=0; assert(!arg_nullcheck(argtable)); // defaults: lport->ival[0] = 8888; debug->ival[0] = 3; #ifdef PUBKEY_DATA_ key->sval[0] = NULL; #else key->sval[0] = "pubkey"; #endif #ifdef ROOTPEM_DATA_ certdb->sval[0] = NULL; #else certdb->sval[0] = "root.pem"; #endif nerrors = arg_parse(argc,argv,argtable); if (help->count > 0) { printf("Usage: %s", progname); arg_print_syntax(stdout,argtable,"\n"); printf("\nEstablishes covert, encrypted tunnels, disguised as connections to <host>.\n\n"); arg_print_glossary(stdout,argtable," %-25s %s\n"); printf("\n"); ret = 0; } else if (nerrors > 0) { arg_print_errors(stdout,end,progname); printf("Try '%s --help' for more information.\n", progname); ret = 1; } else if (argc == 1) { printf("Try '%s --help' for more information.\n", progname); ret = 0; } else { int port = 443; char hstr[255]; assert(host->sval[0]); strncpy(hstr, host->sval[0], sizeof(hstr)-1); char *pstr=0; strtok(hstr, ":"); pstr = strtok(NULL, ":"); if (pstr) { port = strtol(pstr, NULL, 10); if (port < 1 || port > 65535) { fprintf(stderr, "Invalid remote port: %d", port); return 1; } } printf("WARNING: This software is an experimental prototype intended for\n"); printf(" researchers. It does not provide strong security and is\n"); printf(" UNSAFE FOR REAL-WORLD USE. For details of current limitations\n"); printf(" of our proof-of-concept, please see telex-client/ISSUES.\n"); ret = telex_client(lport->ival[0], port, debug->ival[0], hstr, key->sval[0], certdb->sval[0]); } arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0])); return ret; }
int main(int argc, char** argv) { int exitstatus = 0; /* declare CL args */ arg_lit_t *help = (arg_lit_t*) arg_lit0("h", "help", "prints the command glossary"); arg_lit_t *myip = (arg_lit_t*) arg_lit0("m", NULL, "prints the external ip of the interface currently being used"); arg_lit_t *bounce_opt = (arg_lit_t*) arg_lit0("b", NULL, "creates a bouncer to send the message received back to the sender"); arg_lit_t *listen_opt = (arg_lit_t*) arg_lit0("l", NULL, "creates a listener to print the messages received"); arg_file_t *proto = (arg_file_t*) arg_filen("p", "protocol", "acronym", 0, 1, "specify the protocol being manipulated"); arg_file_t *source = (arg_file_t*) arg_filen("s", "source", "x.x.x.x", 0, 1, "specify the source IP"); arg_file_t *dest = (arg_file_t*) arg_filen("d", "dest", "x.x.x.x", 0, 1, "specify the destination IP"); arg_int_t *sport = (arg_int_t*) arg_intn(NULL, "srcport", "short", 0, 1, "specify the source port if applicable"); arg_int_t *dport = (arg_int_t*) arg_intn(NULL, "dstport", "short", 0, 1, "specify the destination port if applicable"); arg_str_t *mcontent = (arg_str_t*) arg_strn(NULL, NULL, "string", 0, 1, "message content as a string"); arg_end_t *end = (arg_end_t*) arg_end(20); void *argtable[] = {help,myip,bounce_opt,listen_opt,proto,source, dest,sport,dport,mcontent,end}; if(arg_nullcheck(argtable) != 0) { fprintf(stderr, "error: insufficient memory"); exitstatus = -1; goto exit_prog; } /* parse and act */ int nerrors = arg_parse(argc,argv,argtable); if(nerrors == 0) { char sourceipbuf[INET6_ADDRSTRLEN]; size_t contentlen = 0; char message_content[MAX_MESSAGELEN + 1]; /* get glossary */ if(help->count) { arg_print_glossary(stdout, argtable, "%-25s %s\n"); } /* get current IP address */ else if(myip->count) { if(getmyip(sourceipbuf) == 0) { printf("Your packets will have the source IP address %s\n", sourceipbuf); } else { fprintf(stderr, "error: could not get your IP address.\n"); exitstatus = -1; goto exit_prog; } } /* start bouncer */ else if(bounce_opt->count) { if(!proto->count) { fprintf(stderr, "error: expected <protocol> specified.\n"); exitstatus = -1; goto exit_prog; } enum Protocol protocol = parse_protocol(proto->filename[0]); if(protocol == proto_UDP) { if(!sport->count) { fprintf(stderr, "error: expected <srcport> specified.\n"); exitstatus = -1; goto exit_prog; } printf("Starting bouncer for UDP packets on port %u...\n", sport->ival[0]); /* start_udp_listener(sport->ival[0], bounce_udp_packet);*/ } else { fprintf(stderr, "Bouncing for %s packets is not supported.\n", proto->filename[0]); exitstatus = -1; goto exit_prog; } } /* start listener */ else if(listen_opt->count) { if(!proto->count) { fprintf(stderr, "error: expected <protocol> specified.\n"); exitstatus = -1; goto exit_prog; } enum Protocol protocol = parse_protocol(proto->filename[0]); if(protocol == proto_UDP) { if(!sport->count) { fprintf(stderr, "error: expected <srcport> specified.\n"); exitstatus = -1; goto exit_prog; } printf("Starting listener for UDP packets on port %u...\n", sport->ival[0]); char filter[FILTER_BUFLEN]; memset(filter, 0, FILTER_BUFLEN); sprintf(filter, "udp dst port %i", sport->ival[0]); start_listener(filter, print_udp_packet); /* start_udp_listener(sport->ival[0], print_packet);*/ } else { fprintf(stderr, "Listening for %s packets is not supported.\n", proto->filename[0]); exitstatus = -1; goto exit_prog; } } /* send packet */ else { /* take into account stdin reading if necessary */ if(!mcontent->count) { contentlen = read(STDIN_FILENO, message_content, MAX_MESSAGELEN); if(contentlen < 0) { fprintf(stderr, "error: could not read message from stdin.\n"); perror("read"); exitstatus = -1; goto exit_prog; } message_content[contentlen] = '\0'; } else { int tempstrlen = strlen(mcontent->sval[0]); contentlen = tempstrlen > MAX_MESSAGELEN ? MAX_MESSAGELEN : tempstrlen; memcpy(message_content, mcontent->sval[0], contentlen); message_content[contentlen] = '\0'; } if(!proto->count || !dest->count) { fprintf(stderr, "error: expected <protocol> and <dest> specified.\n"); exitstatus = -1; goto exit_prog; } if(!source->count) { if(getmyip(sourceipbuf) != 0) { fprintf(stderr, "error: could not get your IP address.\n"); exitstatus = -1; goto exit_prog; } } else { strncpy(sourceipbuf, source->filename[0], INET6_ADDRSTRLEN); } enum Protocol protocol = parse_protocol(proto->filename[0]); if(protocol == proto_ICMP) { time_t t; if(time(&t) == -1) { fprintf(stderr, "error: could not get timestamp.\n"); exitstatus = -1; goto exit_prog; } printf("Sending ICMP ping packet...\nSource -> %s\n" "Destination -> %s\n" "Message -> %i\n", sourceipbuf, dest->filename[0], (int) t); /* construct ICMP header */ int err; int payloadsize = sizeof(icmpheader_t) + sizeof(time_t); char ip_payload[payloadsize]; /* copy in timestamp */ /* we must do this first for the checksum calculation */ t = htonl(t); memcpy(ip_payload + sizeof(icmpheader_t), &t, sizeof(time_t)); /* identifier is lower 16 bits, sequence number is upper 16 bits */ uint32_t rest = htons(0x00); rest <<= 16; rest |= htons(0x7b); if((err = fill_icmp_header((icmpheader_t*) ip_payload, 8, 0, rest, sizeof(time_t))) != 0) { fprintf(stderr, "error: could not fill icmp header, returned %i.\n", err); exitstatus = -1; goto exit_prog; } /* send the ip packet */ ipheader_t iph; iph.ip_p = 1; /* ICMP */ inet_aton(sourceipbuf, (struct in_addr*) &iph.ip_src); inet_aton(dest->filename[0], (struct in_addr*) &iph.ip_dst); if((err = send_ip_packet(&iph, ip_payload, payloadsize)) != 0) { fprintf(stderr, "error: could not send ip packet, returned %i.\n", err); exitstatus = -1; goto exit_prog; } } else if(protocol == proto_UDP) { /* get port info */ unsigned short srcport = sport->count ? (unsigned short) sport->ival[0] : 0; if(!dport->count) { fprintf(stderr, "error: <dstport> specified.\n"); exitstatus = -1; goto exit_prog; } unsigned short dstport = (unsigned short) dport->ival[0]; printf("Sending UDP packet...\nSource -> %s:%i\n" "Destination -> %s:%i\n" "Message Length -> %u bytes\n", sourceipbuf, srcport, dest->filename[0], dstport, (unsigned int) contentlen); /* construct UDP header */ int err; int payloadsize = sizeof(udpheader_t) + contentlen; char ip_payload[payloadsize]; if((err = fill_udp_header((udpheader_t*) ip_payload, srcport, dstport, contentlen)) != 0) { fprintf(stderr, "error: could not fill udp header, returned %i.\n", err); exitstatus = -1; goto exit_prog; } /* set up IP payload */ memcpy(ip_payload + sizeof(udpheader_t), message_content, contentlen); /* send the ip packet */ ipheader_t iph; iph.ip_p = 17; /* UDP */ inet_aton(sourceipbuf, (struct in_addr*) &iph.ip_src); inet_aton(dest->filename[0], (struct in_addr*) &iph.ip_dst); if((err = send_ip_packet(&iph, ip_payload, payloadsize)) != 0) { fprintf(stderr, "error: could not send ip packet, returned %i.\n", err); exitstatus = -1; goto exit_prog; } } else if(protocol == proto_TCP) { printf("TCP currently not supported.\n"); } else { fprintf(stderr, "error: protocol %s is not supported.\n", proto->filename[0]); } } } else { arg_print_errors(stdout, end, argv[0]); exitstatus = -1; goto exit_prog; } exit_prog: arg_freetable(argtable, sizeof(argtable)/sizeof(argtable[0])); exit(exitstatus); }
int main(int argc, char **argv) { struct arg_int *channels = arg_int0("c", "channels", "<n>", "define number of channels (default is 1)"); struct arg_int *subscribers = arg_int0("s", "subscribers", "<n>", "define number of subscribers (default is 1)"); struct arg_str *server_name = arg_str0("S", "server", "<hostname>", "server hostname where messages will be published (default is \"127.0.0.1\")"); struct arg_int *server_port = arg_int0("P", "port", "<n>", "server port where messages will be published (default is 9080)"); struct arg_int *timeout = arg_int0(NULL, "timeout", "<n>", "timeout when waiting events on communication to the server (default is 1000)"); struct arg_int *verbose = arg_int0("v", "verbose", "<n>", "increase output messages detail (0 (default) - no messages, 1 - info messages, 2 - debug messages, 3 - trace messages"); struct arg_lit *help = arg_lit0(NULL, "help", "print this help and exit"); struct arg_lit *version = arg_lit0(NULL, "version", "print version information and exit"); struct arg_end *end = arg_end(20); void* argtable[] = { channels, subscribers, server_name, server_port, timeout, verbose, help, version, end }; const char* progname = "subscriber"; int nerrors; int exitcode = EXIT_SUCCESS; /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ printf("%s: insufficient memory\n", progname); exitcode = EXIT_FAILURE; goto exit; } /* set any command line default values prior to parsing */ subscribers->ival[0] = DEFAULT_CONCURRENT_CONN; channels->ival[0] = DEFAULT_NUM_CHANNELS; server_name->sval[0] = DEFAULT_SERVER_HOSTNAME; server_port->ival[0] = DEFAULT_SERVER_PORT; timeout->ival[0] = DEFAULT_TIMEOUT; verbose->ival[0] = 0; /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc, argv, argtable); /* special case: '--help' takes precedence over error reporting */ if (help->count > 0) { printf(DESCRIPTION_SUBSCRIBER, progname, VERSION, COPYRIGHT); printf("Usage: %s", progname); arg_print_syntax(stdout, argtable, "\n"); arg_print_glossary(stdout, argtable, " %-25s %s\n"); exitcode = EXIT_SUCCESS; goto exit; } /* special case: '--version' takes precedence error reporting */ if (version->count > 0) { printf(DESCRIPTION_SUBSCRIBER, progname, VERSION, COPYRIGHT); exitcode = EXIT_SUCCESS; goto exit; } /* If the parser returned any errors then display them and exit */ if (nerrors > 0) { /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout, end, progname); printf("Try '%s --help' for more information.\n", progname); exitcode = EXIT_FAILURE; goto exit; } verbose_messages = verbose->ival[0]; /* normal case: take the command line options at face value */ exitcode = main_program(channels->ival[0], subscribers->ival[0], server_name->sval[0], server_port->ival[0], timeout->ival[0]); exit: /* deallocate each non-null entry in argtable[] */ arg_freetable(argtable, sizeof(argtable) / sizeof(argtable[0])); return exitcode; }
int main(int argc, char* argv[]) { double discountFactor = 0.9; FILE* initFileFd = NULL; FILE** combinedFd = NULL; FILE* optimalFd = NULL; optimistic_instance* optimistic = NULL; random_search_instance* random_search = NULL; uct_instance* uct = NULL; uniform_instance* uniform = NULL; unsigned int maxDepth = 0; unsigned int i = 0; unsigned int n = 0; state** initialStates = NULL; unsigned int timestamp = time(NULL); double* optimalValues = NULL; int readFscanf = -1; struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state"); struct arg_int* d = arg_int1("d", NULL, "<n>", "Maximum depth of an uniform tree which the number of call per step"); struct arg_int* k = arg_int1("k", NULL, "<n>", "Branching factor of the problem"); struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs"); struct arg_file* optimal = arg_file1(NULL, "optimal", "<file>", "File containing the optimal values"); struct arg_end* end = arg_end(6); void* argtable[6]; int nerrors = 0; argtable[0] = initFile; argtable[1] = where; argtable[2] = d; argtable[3] = k; argtable[4] = optimal; argtable[5] = end; if(arg_nullcheck(argtable) != 0) { printf("error: insufficient memory\n"); arg_freetable(argtable, 6); return EXIT_FAILURE; } nerrors = arg_parse(argc, argv, argtable); if(nerrors > 0) { printf("%s:", argv[0]); arg_print_syntax(stdout, argtable, "\n"); arg_print_errors(stdout, end, argv[0]); arg_freetable(argtable, 6); return EXIT_FAILURE; } initGenerativeModelParameters(); K = k->ival[0]; initGenerativeModel(); optimalFd = fopen(optimal->filename[0], "r"); initFileFd = fopen(initFile->filename[0], "r"); readFscanf = fscanf(initFileFd, "%u\n", &n); initialStates = (state**)malloc(sizeof(state*) * n); for(i = 0; i < n; i++) { char str[1024]; readFscanf = fscanf(initFileFd, "%s\n", str); initialStates[i] = makeState(str); } maxDepth = d->ival[0]; combinedFd = (FILE**)malloc(sizeof(FILE*) * maxDepth); for(i = 1; i <= maxDepth; i++) { char str[1024]; sprintf(str, "%s/%u_combined_%u_%u.csv", where->filename[0], timestamp, K, i); combinedFd[i - 1] = fopen(str, "w"); fprintf(combinedFd[i - 1], "n,optimistic,random search,uct,uniform\n"); } arg_freetable(argtable, 6); optimalValues = (double*)malloc(sizeof(double) * K); optimistic = optimistic_initInstance(initialStates[0], discountFactor); random_search = random_search_initInstance(initialStates[0], discountFactor); uct = uct_initInstance(initialStates[0], discountFactor); uniform = uniform_initInstance(initialStates[0], discountFactor); for(i = 0; i < n; i++) { unsigned int j = 1; unsigned int maxNbIterations = K; unsigned int optimalAction = 0; char str[1024]; readFscanf = fscanf(optimalFd, "%s\n", str); optimalValues[0] = strtod(strtok(str, ","), NULL); printf("%.15f,",optimalValues[0]); for(; j < K; j++) { optimalValues[j] = strtod(strtok(NULL, ","), NULL); printf("%.15f,",optimalValues[j]); } optimalAction = atol(strtok(NULL, ",")); printf("%u\n",optimalAction); for(j = 1; j <= maxDepth; j++) { unsigned int crtOptimalAction = getActionId(optimistic_planning(optimistic, maxNbIterations)); fprintf(combinedFd[j - 1], "%u,", maxNbIterations); fprintf(combinedFd[j - 1], "%.15f,", crtOptimalAction == optimalAction ? 0.0 : optimalValues[optimalAction] - optimalValues[crtOptimalAction]); maxNbIterations += pow(K, j+1); } if(i < (n - 1)) optimistic_resetInstance(optimistic, initialStates[i+1]); printf("optimistic: %uth initial state processed\n", i+1); fflush(NULL); maxNbIterations = K; for(j = 1; j <= maxDepth; j++) { unsigned int crtOptimalAction = getActionId(random_search_planning(random_search, maxNbIterations)); fprintf(combinedFd[j - 1], "%.15f,", crtOptimalAction == optimalAction ? 0.0 : optimalValues[optimalAction] - optimalValues[crtOptimalAction]); maxNbIterations += pow(K, j+1); } if(i < (n - 1)) random_search_resetInstance(random_search, initialStates[i + 1]); printf("random_search: %uth initial state processed\n", i+1); fflush(NULL); maxNbIterations = K; for(j = 1; j <= maxDepth; j++) { unsigned int crtOptimalAction = getActionId(uct_planning(uct, maxNbIterations)); fprintf(combinedFd[j - 1], "%.15f,", crtOptimalAction == optimalAction ? 0.0 : optimalValues[optimalAction] - optimalValues[crtOptimalAction]); maxNbIterations += pow(K, j+1); } if(i < (n - 1)) uct_resetInstance(uct, initialStates[i + 1]); printf("uct: %uth initial state processed\n", i+1); fflush(NULL); maxNbIterations = K; for(j = 1; j <= maxDepth; j++) { unsigned int crtOptimalAction = getActionId(uniform_planning(uniform, maxNbIterations)); fprintf(combinedFd[j - 1], "%.15f\n", crtOptimalAction == optimalAction ? 0.0 : optimalValues[optimalAction] - optimalValues[crtOptimalAction]); maxNbIterations += pow(K, j+1); } if(i < (n - 1)) uniform_resetInstance(uniform, initialStates[i + 1]); printf("uniform: %uth initial state processed\n", i+1); printf("%uth initial state processed\n", i+1); fflush(NULL); } for(i = 0; i < maxDepth; i++) { fclose(combinedFd[i]); } for(i = 0; i < n; i++) freeState(initialStates[i]); free(initialStates); free(combinedFd); optimistic_uninitInstance(&optimistic); random_search_uninitInstance(&random_search); uct_uninitInstance(&uct); uniform_uninitInstance(&uniform); freeGenerativeModel(); freeGenerativeModelParameters(); return EXIT_SUCCESS; }
int main(int argc, char* argv[]) { #ifdef BALL double discountFactor = 0.9; #else #ifdef CART_POLE double discountFactor = 0.95; #else #ifdef DOUBLE_CART_POLE double discountFactor = 0.95; #else #ifdef MOUNTAIN_CAR double discountFactor = 0.99; #else #ifdef ACROBOT double discountFactor = 0.95; #else #ifdef BOAT double discountFactor = 0.95; #else #ifdef SWIMMER double discountFactor = 0.95; #endif #endif #endif #endif #endif #endif #endif FILE* initFileFd = NULL; state** initialStates = NULL; FILE* results = NULL; char str[1024]; unsigned int i = 0; unsigned int nbInitialStates = 0; unsigned int* ns = NULL; unsigned int nbN = 0; double* Ls = NULL; unsigned int nbL = 0; unsigned int nbSteps = 0; unsigned int timestamp = time(NULL); int readFscanf = -1; lipschitzian_instance* lipschitzian = NULL; struct arg_file* initFile = arg_file1(NULL, "init", "<file>", "File containing the inital state"); struct arg_int* s = arg_int1("s", NULL, "<n>", "Number of steps"); struct arg_str* r = arg_str1("n", NULL, "<s>", "List of ressources"); struct arg_str* z = arg_str1("L", NULL, "<s>", "List of Lipschitz coefficients to try"); struct arg_file* where = arg_file1(NULL, "where", "<file>", "Directory where we save the outputs"); struct arg_end* end = arg_end(6); int nerrors = 0; void* argtable[6]; argtable[0] = initFile; argtable[1] = r; argtable[2] = s; argtable[3] = z; argtable[4] = where; argtable[5] = end; if(arg_nullcheck(argtable) != 0) { printf("error: insufficient memory\n"); arg_freetable(argtable, 6); return EXIT_FAILURE; } nerrors = arg_parse(argc, argv, argtable); if(nerrors > 0) { printf("%s:", argv[0]); arg_print_syntax(stdout, argtable, "\n"); arg_print_errors(stdout, end, argv[0]); arg_freetable(argtable, 6); return EXIT_FAILURE; } initGenerativeModelParameters(); initGenerativeModel(); initFileFd = fopen(initFile->filename[0], "r"); readFscanf = fscanf(initFileFd, "%u\n", &nbInitialStates); initialStates = (state**)malloc(sizeof(state*) * nbInitialStates); for(; i < nbInitialStates; i++) { readFscanf = fscanf(initFileFd, "%s\n", str); initialStates[i] = makeState(str); } fclose(initFileFd); nbSteps = s->ival[0]; Ls = parseDoubleList((char*)z->sval[0], &nbL); ns = parseUnsignedIntList((char*)r->sval[0], &nbN); sprintf(str, "%s/%u_results_%s_%s.csv", where->filename[0], timestamp, z->sval[0], r->sval[0]); results = fopen(str, "w"); lipschitzian = lipschitzian_initInstance(NULL, discountFactor, 0.0); for(i = 0; i < nbN; i++) { /* Loop on the computational ressources */ fprintf(results, "%u", ns[i]); printf("Starting with %u computational ressources\n", ns[i]); fflush(NULL); unsigned int j = 0; for(; j < nbL; j++) { /* Loop on the Lispchitz constant */ unsigned int k = 0; double average = 0.0; lipschitzian->L = Ls[j]; for(; k < nbInitialStates; k++) { /* Loop on the initial states */ unsigned int l = 0; double sumRewards = 0.0; state* crt = copyState(initialStates[k]); lipschitzian_resetInstance(lipschitzian, crt); for(; l < nbSteps; l++) { /* Loop on the step */ char isTerminal = 0; double reward = 0.0; state* nextState = NULL; double* optimalAction = lipschitzian_planning(lipschitzian, ns[i]); isTerminal = nextStateReward(crt, optimalAction, &nextState, &reward) < 0 ? 1 : 0; free(optimalAction); freeState(crt); crt = nextState; sumRewards += reward; lipschitzian_resetInstance(lipschitzian,crt); if(isTerminal) break; } average += sumRewards; freeState(crt); printf("Computation of the %u initial state done with L=%f\n", k, Ls[j]); fflush(NULL); } average = average /(double)nbInitialStates; fprintf(results, ",%.15f", average); printf("Computation with L=%f and n=%u done\n", Ls[j], ns[i]); fflush(NULL); } fprintf(results,"\n"); printf("Computation with %u computational ressources done\n\n", ns[i]); fflush(NULL); } fclose(results); arg_freetable(argtable, 6); for(i = 0; i < nbInitialStates; i++) freeState(initialStates[i]); free(initialStates); lipschitzian_uninitInstance(&lipschitzian); free(ns); free(Ls); freeGenerativeModel(); freeGenerativeModelParameters(); return EXIT_SUCCESS; }
int main(int argc, char** argv) { int i, ret; int nerrors[NUMBER_OF_DIFFERENT_SYNTAXES + 1]; /* argtable setup */ /* SYNTAX 1: [--info] */ info1 = arg_lit1(NULL, "info", "Show information about the FLI filterwheel"); end1 = arg_end(20); void * argtable1[] = {info1, end1}; argtable[1] = argtable1; /* SYNTAX 2: [--set-filter] */ setfilter2 = arg_int1(NULL, "set-filter", "N", "Set the filter N"); end2 = arg_end(20); void * argtable2[] = {setfilter2, end2}; argtable[2] = argtable2; /* SYNTAX 3: [--home] */ home3 = arg_lit1(NULL, "home", "Homes the filterwheel"); end3 = arg_end(20); void * argtable3[] = {home3, end3}; argtable[3] = argtable3; /* SYNTAX 4: [--help]*/ help4 = arg_lit1(NULL, "help", "Print this help"); end4 = arg_end(20); void * argtable4[] = {help4, end4}; argtable[4] = argtable4; /* verify all argtable[] entries were allocated successfully */ for (i = 1; i <= NUMBER_OF_DIFFERENT_SYNTAXES; i++) { if (arg_nullcheck(argtable[i]) != 0) { printf("%s: insufficient memory\n", progname); return EXIT_FAILURE; } } /* parse all argument possibilities */ for (i = 1; i <= NUMBER_OF_DIFFERENT_SYNTAXES; i++) { nerrors[i] = arg_parse(argc, argv, argtable[i]); } /* select the right command */ /* --info */ if (nerrors[1] == 0) { if (info1->count > 0) { ret = filter_info(); if (ret) return ret; return 0; } /* --set-filter */ } else if (nerrors[2] == 0) { if (setfilter2->count > 0) { ret = filter_set_filter(setfilter2->ival[0]); if (ret) return ret; return 0; } /* --home */ } else if (nerrors[3] == 0) { if (home3->count > 0) { ret = filter_home(1); if (ret) return ret; return 0; } /* --help */ } else if (nerrors[4] == 0) { if (help4) { ret = argtable_help(progname, NUMBER_OF_DIFFERENT_SYNTAXES, argtable); if (ret) return ret; return 0; } /* incorrect or partially incorrect argument syntaxes */ } else { if (setfilter2->count > 0) { arg_print_errors(stdout, end2, progname); printf("usage: %s ", progname); arg_print_syntax(stdout, argtable2, "\n"); } else { printf("%s: unable to parse arguments, see syntax below:\n", progname); ret = argtable_help(progname, NUMBER_OF_DIFFERENT_SYNTAXES, argtable); if (ret) return ret; return 0; } return EXIT_FAILURE; } /* no command line options at all */ printf("Try '%s --help' for more information.\n", progname); return (EXIT_SUCCESS); }