int main(int argc, char *argv[]) { pid_t pid = getpid(); // get process id int i, cycle, rc; long clktck = sysconf(_SC_CLK_TCK); // [note] obtain the number of clock ticks per second.(man 2 times) struct tms t; // [note] man 2 times clock_t starttick, stoptick; // [note] clock_t - CPU usage counts sigset_t mask; FILE * output = DEFAULT_OP; colour = colours[pid % N_COLOUR]; // [hwx] randomly select colour for this process if (argc > 2 || (argc == 2 && !isdigit((int)argv[1][0]))) PrintUsage(argv[0]); fprintf(output,"%s%7d; START" BLACK NORMAL "\n", colour, (int) pid); fflush(output); signal (SIGINT, SignalHandler); // hook up signal handler signal (SIGQUIT, SignalHandler); signal (SIGHUP, SignalHandler); signal (SIGTERM, SignalHandler); signal (SIGABRT, SignalHandler); // signal (SIGCONT, SignalHandler); // do this intrinsically after return from SIGTSTP // due to Darwin/BSD inconsistent SIGCONT behaviour signal (SIGTSTP, SignalHandler); rc = setpriority(PRIO_PROCESS, 0, 20); // [note] be nice, lower priority by 20 // linux is [-20, 19] cycle = argc < 2 ? DEFAULT_TIME : atoi(argv[1]); // get tick count if (cycle <= 0) cycle = 1; for (i = 0; i < cycle;) { // tick if (signal_SIGCONT) { signal_SIGCONT = FALSE; fprintf(output,"%s%7d; SIGCONT" BLACK NORMAL "\n", colour, (int) pid); fflush(output); } starttick = times (&t); // use timer to ascertain whether 'tick' should be reported rc = sleep(1); stoptick = times (&t); if (rc == 0 || (stoptick-starttick) > clktck/2) // [hwx] more than 0.5 second? fprintf(output,"%s%7d; tick %d" BLACK NORMAL "\n", colour, (int) pid, ++i); if (signal_SIGINT) { fprintf(output,"%s%7d; SIGINT" BLACK NORMAL "\n", colour, (int) pid); exit(0); } if (signal_SIGQUIT) { fprintf(output,"%s%7d; SIGQUIT" BLACK NORMAL "\n", colour, (int) pid); exit(0); } if (signal_SIGHUP) { fprintf(output,"%s%7d; SIGHUP" BLACK NORMAL "\n", colour, (int) pid); exit(0); } /* [note] more about how to handle SIGTSTP, see *TLPI* and *APUE* */ if (signal_SIGTSTP) { signal_SIGTSTP = FALSE; fprintf(output,"%s%7d; SIGTSTP" BLACK NORMAL "\n", colour, (int) pid); fflush(output); sigemptyset (&mask); // unblock SIGSTP if necessary (BSD/OS X) sigaddset (&mask, SIGTSTP); sigprocmask (SIG_UNBLOCK, &mask, NULL); signal(SIGTSTP, SIG_DFL); // reset trap to default raise (SIGTSTP); // now suspend ourselves // kill(getpid(), sig); signal(SIGTSTP, SignalHandler); // reset trap on return from suspension signal_SIGCONT = TRUE; // set flag here rather than trap signal } if (signal_SIGABRT) { fprintf(output,"%s%7d; SIGABRT" BLACK NORMAL "\n", colour, (int) pid); fflush(output); signal (SIGABRT, SIG_DFL); raise (SIGABRT); } if (signal_SIGTERM) { fprintf(output,"%s%7d; SIGTERM" BLACK NORMAL "\n", colour, (int) pid); exit(0); } fflush(output); } exit(0); }
int main(int argc, char* argv[]) { int opt; while ((opt = getopt(argc, argv, "t:c:")) != -1) { switch (opt) { case 't': TEST = atoi(optarg); break; case 'c': CONNECTIVITY = atoi(optarg); break; default: PrintUsage(); return -1; } } if ((TEST <= TEST_INVALID || TEST >= MAX_TESTS) || (CONNECTIVITY < CT_ADAPTER_DEFAULT || CONNECTIVITY >= MAX_CT)) { PrintUsage(); return -1; } /* Initialize OCStack*/ if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK) { OC_LOG(ERROR, TAG, "OCStack init error"); return 0; } if(CONNECTIVITY == CT_ADAPTER_DEFAULT || CONNECTIVITY == CT_IP) { OC_CONNTYPE = CT_ADAPTER_IP; } else { OC_LOG(INFO, TAG, "Default Connectivity type selected..."); OC_CONNTYPE = CT_ADAPTER_IP; } InitDiscovery(); // Break from loop with Ctrl+C OC_LOG(INFO, TAG, "Entering occlient main loop..."); signal(SIGINT, handleSigInt); while (!gQuitFlag) { if (OCProcess() != OC_STACK_OK) { OC_LOG(ERROR, TAG, "OCStack process error"); return 0; } sleep(2); } OC_LOG(INFO, TAG, "Exiting occlient main loop..."); if (OCStop() != OC_STACK_OK) { OC_LOG(ERROR, TAG, "OCStack stop error"); } return 0; }
int main(int argc, char * argv[]) { kern_return_t err; bool verbose; int ch; int argIndex; // Set gProgramName to the last path component of argv[0] gProgramName = strrchr(argv[0], '/'); if (gProgramName == NULL) { gProgramName = argv[0]; } else { gProgramName += 1; } // Parse our options. verbose = false; do { ch = getopt(argc, argv, "w"); if (ch != -1) { switch (ch) { case 'w': verbose = true; break; case '?': default: PrintUsage(); exit(EXIT_FAILURE); break; } } } while (ch != -1); // Handle the remaining arguments. If none, we work against ourselves. // Otherwise each string is treated as a process name, and we look that // up using FindProcessByName. if (argv[optind] == NULL) { err = PrintProcessPortSpace(getpid(), verbose); } else { for (argIndex = optind; argIndex < argc; argIndex++) { pid_t pid; if (argIndex > optind) { fprintf(stdout, "\n"); } if (argv[argIndex][0] == 0) { err = EINVAL; } else { err = FindProcessByName(argv[argIndex], &pid); } if (err == 0) { fprintf(stdout, "Mach ports for '%s' (%lld):\n", argv[argIndex], (long long) pid); fprintf(stdout, "\n"); err = PrintProcessPortSpace(pid, verbose); } if (err != 0) { break; } } } if (err != 0) { fprintf(stderr, "%s: Failed with error %d.\n", gProgramName, err); } return (err == 0) ? EXIT_SUCCESS : EXIT_FAILURE; }
/** * @brief Parses the application's command-line arguments * * @param[in] argc The number of input arguments * @param[in] argv The input arguments * @param[in] rank The MPI rank of the calling process * @param[in] size The total number of MPI processes available * @param[out] domSize The parsed domain size (2D) * @param[out] topSize The parsed topology size (2D) * @param[out] useFastSwap The parsed flag for fast block swap * @return The parsing status (STATUS_OK indicates a successful parse) */ int ParseCommandLineArguments(int argc, char ** argv, int rank, int size, int2 * domSize, int2 * topSize, int * useFastSwap) { int canPrint = (rank == MPI_MASTER_RANK); int argIdx; // If help is requested, all other arguments will be ignored if ((FindAndClearArgument("-h", argc, argv) != -1) || (FindAndClearArgument("--help", argc, argv) != -1)) { if (canPrint) { PrintUsage(argv[0]); } // This simply prevents the application from continuing return STATUS_ERR; } // Check if fast swapping was requested * useFastSwap = (FindAndClearArgument("-fs", argc, argv) != -1); // Topology information must always be present argIdx = FindAndClearArgument("-t", argc, argv); if (argIdx == -1) { OneErrPrintf(canPrint, "Error: Could not find the topology information.\n"); return STATUS_ERR; } else { topSize->x = ExtractNumber(argIdx + 1, argc, argv); topSize->y = ExtractNumber(argIdx + 2, argc, argv); // At least the first topology dimension must be specified if (topSize->x <= 0) { OneErrPrintf(canPrint, "Error: The topology size is invalid (first value: %d)\n", topSize->x); return STATUS_ERR; } // If the second topology dimension is missing, it will default to 1 if (topSize->y <= 0) { topSize->y = 1; } } // The domain size information is optional argIdx = FindAndClearArgument("-d", argc, argv); if (argIdx == -1) { domSize->x = domSize->y = DEFAULT_DOMAIN_SIZE; } else { domSize->x = ExtractNumber(argIdx + 1, argc, argv); domSize->y = ExtractNumber(argIdx + 2, argc, argv); // At least the first domain dimension must be specified if (domSize->x < MIN_DOM_SIZE) { OneErrPrintf(canPrint, "Error: The local domain size must be at least %d (currently: %d)\n", MIN_DOM_SIZE, domSize->x); return STATUS_ERR; } // If the second domain dimension is missing, it will default to the first dimension's value if (domSize->y <= 0) { domSize->y = domSize->x; } } // At the end, there should be no other arguments that haven't been parsed for (int i = 1; i < argc; ++i) { if (strlen(argv[i]) > 0) { OneErrPrintf(canPrint, "Error: Unknown argument (\"%s\")\n", argv[i]); return STATUS_ERR; } } // If we reach this point, all arguments were parsed successfully if (canPrint) { printf("Topology size: %d x %d\n", topSize->x, topSize->y); printf("Local domain size (current node): %d x %d\n", domSize->x, domSize->y); printf("Global domain size (all nodes): %d x %d\n", topSize->x * domSize->x, topSize->y * domSize->y); } return STATUS_OK; }
static void ProcessCmdLine(struct JoystickData *params, LPSTR lpCmdLine) { int i, j, buffer_index; /* Options are { 'poll', 'max-range', 'min-range', 'joystick chosen', 'verbose', help' } */ char options[] = { 'p', 'a', 'i', 'j', 'v', 'h' }; char buffer[32]; char command; for (i = 0; lpCmdLine[i] != '\0'; i++) { if (lpCmdLine[i] == '/' || lpCmdLine[i] == '-') { /* Find valid command */ BOOL valid = FALSE; command = lpCmdLine[++i]; for (j = 0; j < NUMELEMS(options) && !valid; j++) if (options[j] == command) valid = TRUE; if (!valid) goto invalid; /* Skip extra spaces */ while (lpCmdLine[++i] == ' '); /* If the next word is a parameter, copy it. * Parameters dont start with - or /, that's for commands. * The isdigit call is to test for negative numbers (-1 for example) * and to not confuse them with commands */ buffer_index = 0; if ((lpCmdLine[i] != '-' || isdigit(lpCmdLine[i + 1])) && lpCmdLine[i] != '/') { /* Copy the word and don't let it overflow */ while (lpCmdLine[i] != ' ' && lpCmdLine[i] != '\0' && buffer_index < sizeof(buffer)) { buffer[buffer_index] = lpCmdLine[i]; buffer_index++; i++; } } buffer[buffer_index] = '\0'; /* Process command and extract parameter */ switch (command) { case 'p': if (strlen(buffer) == 0) goto invalid; params->poll_time = atoi(buffer); break; case 'a': if (strlen(buffer) == 0) goto invalid; params->axes_max = atoi(buffer); break; case 'i': if (strlen(buffer) == 0) goto invalid; params->axes_min = atoi(buffer); break; case 'j': if (strlen(buffer) == 0) goto invalid; params->chosen_joystick = atoi(buffer); break; case 'v': gVerbose = TRUE; case 'h': PrintUsage(); exit(0); break; } } } return; invalid: printf("Invalid parameters or command line option '%c'\n", command); printf("Try using -h for help with commands and syntax\n"); exit(1); }
int main( int argc, char *argv[]) { char **myargv; char *aLine; char *firstdir = ""; #ifdef MUST_DISABLE_SIGFPE signal(SIGFPE, SIG_IGN); #endif #ifdef MUST_DISABLE_FPMASK fpsetmask(0); #endif /* initialize locale settings according to localeconv(3) */ setlocale(LC_ALL, ""); #if defined(HAVE_LIBINTL_H) && defined(BUILD_LIBINTL) bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR); textdomain(GETTEXT_PACKAGE); #endif if (argc == 1) { PrintUsage(""); return 0; } if (((argc == 2) || (argc == 3)) && !strcmp("-", argv[1])) { #if HAVE_GETRUSAGE struct rusage myusage; struct timeval starttime; struct timeval currenttime; gettimeofday(&starttime, NULL); #endif RemoteMode = 1; if ((argc == 3) && strcmp("", argv[2])) { if ( #ifdef HAVE_GETUID getuid() #else 1 #endif == 0) { #ifdef HAVE_CHROOT if (chroot(argv[2]) != 0) { fprintf(stderr, "ERROR: chroot %s: %s\n", argv[2],rrd_strerror(errno)); exit(errno); } ChangeRoot = 1; firstdir = "/"; #else fprintf(stderr, "ERROR: change root is not supported by your OS " "or at least by this copy of rrdtool\n"); exit(1); #endif } else { firstdir = argv[2]; } } if (strcmp(firstdir, "")) { if (chdir(firstdir) != 0) { fprintf(stderr, "ERROR: chdir %s %s\n", firstdir,rrd_strerror(errno)); exit(errno); } } while (fgetslong(&aLine, stdin)) { char *aLineOrig = aLine; if ((argc = CountArgs(aLine)) == 0) { free(aLine); printf("ERROR: not enough arguments\n"); continue; } if ((myargv = (char **) malloc((argc + 1) * sizeof(char *))) == NULL) { perror("malloc"); exit(1); } if ((argc = CreateArgs(argv[0], aLine, myargv)) < 0) { printf("ERROR: creating arguments\n"); } else { if ( HandleInputLine(argc, myargv, stdout) == 0 ) { #if HAVE_GETRUSAGE getrusage(RUSAGE_SELF, &myusage); gettimeofday(¤ttime, NULL); printf("OK u:%1.2f s:%1.2f r:%1.2f\n", (double) myusage.ru_utime.tv_sec + (double) myusage.ru_utime.tv_usec / 1000000.0, (double) myusage.ru_stime.tv_sec + (double) myusage.ru_stime.tv_usec / 1000000.0, (double) (currenttime.tv_sec - starttime.tv_sec) + (double) (currenttime.tv_usec - starttime.tv_usec) / 1000000.0); #else printf("OK\n"); #endif } } fflush(stdout); /* this is important for pipes to work */ free(myargv); free(aLineOrig); } } else if (argc == 2) { PrintUsage(argv[1]); exit(0); } else if (argc == 3 && !strcmp(argv[1], "help")) { PrintUsage(argv[2]); exit(0); } else { exit(HandleInputLine(argc, argv, stderr)); } return 0; }
int Tk_ParseArgv( Tcl_Interp *interp, /* Place to store error message. */ Tk_Window tkwin, /* Window to use for setting Tk options. NULL * means ignore Tk option specs. */ int *argcPtr, /* Number of arguments in argv. Modified to * hold # args left in argv at end. */ const char **argv, /* Array of arguments. Modified to hold those * that couldn't be processed here. */ const Tk_ArgvInfo *argTable, /* Array of option descriptions */ int flags) /* Or'ed combination of various flag bits, * such as TK_ARGV_NO_DEFAULTS. */ { register const Tk_ArgvInfo *infoPtr; /* Pointer to the current entry in the table * of argument descriptions. */ const Tk_ArgvInfo *matchPtr;/* Descriptor that matches current argument. */ const char *curArg; /* Current argument */ register char c; /* Second character of current arg (used for * quick check for matching; use 2nd char. * because first char. will almost always be * '-'). */ int srcIndex; /* Location from which to read next argument * from argv. */ int dstIndex; /* Index into argv to which next unused * argument should be copied (never greater * than srcIndex). */ int argc; /* # arguments in argv still to process. */ size_t length; /* Number of characters in current argument. */ char *endPtr; /* Used for identifying junk in arguments. */ int i; if (flags & TK_ARGV_DONT_SKIP_FIRST_ARG) { srcIndex = dstIndex = 0; argc = *argcPtr; } else { srcIndex = dstIndex = 1; argc = *argcPtr-1; } while (argc > 0) { curArg = argv[srcIndex]; srcIndex++; argc--; length = strlen(curArg); if (length > 0) { c = curArg[1]; } else { c = 0; } /* * Loop throught the argument descriptors searching for one with the * matching key string. If found, leave a pointer to it in matchPtr. */ matchPtr = NULL; for (i = 0; i < 2; i++) { if (i == 0) { infoPtr = argTable; } else { infoPtr = defaultTable; } for (; (infoPtr != NULL) && (infoPtr->type != TK_ARGV_END); infoPtr++) { if (infoPtr->key == NULL) { continue; } if ((infoPtr->key[1] != c) || (strncmp(infoPtr->key, curArg, length) != 0)) { continue; } if ((tkwin == NULL) && ((infoPtr->type == TK_ARGV_CONST_OPTION) || (infoPtr->type == TK_ARGV_OPTION_VALUE) || (infoPtr->type == TK_ARGV_OPTION_NAME_VALUE))) { continue; } if (infoPtr->key[length] == 0) { matchPtr = infoPtr; goto gotMatch; } if (flags & TK_ARGV_NO_ABBREV) { continue; } if (matchPtr != NULL) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "ambiguous option \"%s\"", curArg)); Tcl_SetErrorCode(interp, "TK", "ARG", "AMBIGUOUS", curArg, NULL); return TCL_ERROR; } matchPtr = infoPtr; } } if (matchPtr == NULL) { /* * Unrecognized argument. Just copy it down, unless the caller * prefers an error to be registered. */ if (flags & TK_ARGV_NO_LEFTOVERS) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "unrecognized argument \"%s\"", curArg)); Tcl_SetErrorCode(interp, "TK", "ARG", "UNRECOGNIZED", curArg, NULL); return TCL_ERROR; } argv[dstIndex] = curArg; dstIndex++; continue; } /* * Take the appropriate action based on the option type */ gotMatch: infoPtr = matchPtr; switch (infoPtr->type) { case TK_ARGV_CONSTANT: *((int *) infoPtr->dst) = PTR2INT(infoPtr->src); break; case TK_ARGV_INT: if (argc == 0) { goto missingArg; } *((int *) infoPtr->dst) = strtol(argv[srcIndex], &endPtr, 0); if ((endPtr == argv[srcIndex]) || (*endPtr != 0)) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "expected %s argument for \"%s\" but got \"%s\"", "integer", infoPtr->key, argv[srcIndex])); Tcl_SetErrorCode(interp, "TK", "ARG", "INTEGER", curArg,NULL); return TCL_ERROR; } srcIndex++; argc--; break; case TK_ARGV_STRING: if (argc == 0) { goto missingArg; } *((const char **) infoPtr->dst) = argv[srcIndex]; srcIndex++; argc--; break; case TK_ARGV_UID: if (argc == 0) { goto missingArg; } *((Tk_Uid *) infoPtr->dst) = Tk_GetUid(argv[srcIndex]); srcIndex++; argc--; break; case TK_ARGV_REST: *((int *) infoPtr->dst) = dstIndex; goto argsDone; case TK_ARGV_FLOAT: if (argc == 0) { goto missingArg; } *((double *) infoPtr->dst) = strtod(argv[srcIndex], &endPtr); if ((endPtr == argv[srcIndex]) || (*endPtr != 0)) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "expected %s argument for \"%s\" but got \"%s\"", "floating-point", infoPtr->key, argv[srcIndex])); Tcl_SetErrorCode(interp, "TK", "ARG", "FLOAT", curArg, NULL); return TCL_ERROR; } srcIndex++; argc--; break; case TK_ARGV_FUNC: { typedef int (ArgvFunc)(char *, const char *, const char *); ArgvFunc *handlerProc = (ArgvFunc *) infoPtr->src; if (handlerProc(infoPtr->dst, infoPtr->key, argv[srcIndex])) { srcIndex++; argc--; } break; } case TK_ARGV_GENFUNC: { typedef int (ArgvGenFunc)(char *, Tcl_Interp *, const char *, int, const char **); ArgvGenFunc *handlerProc = (ArgvGenFunc *) infoPtr->src; argc = handlerProc(infoPtr->dst, interp, infoPtr->key, argc, argv+srcIndex); if (argc < 0) { return TCL_ERROR; } break; } case TK_ARGV_HELP: PrintUsage(interp, argTable, flags); Tcl_SetErrorCode(interp, "TK", "ARG", "HELP", NULL); return TCL_ERROR; case TK_ARGV_CONST_OPTION: Tk_AddOption(tkwin, infoPtr->dst, infoPtr->src, TK_INTERACTIVE_PRIO); break; case TK_ARGV_OPTION_VALUE: if (argc < 1) { goto missingArg; } Tk_AddOption(tkwin, infoPtr->dst, argv[srcIndex], TK_INTERACTIVE_PRIO); srcIndex++; argc--; break; case TK_ARGV_OPTION_NAME_VALUE: if (argc < 2) { Tcl_SetObjResult(interp, Tcl_ObjPrintf( "\"%s\" option requires two following arguments", curArg)); Tcl_SetErrorCode(interp, "TK", "ARG", "NAME_VALUE", curArg, NULL); return TCL_ERROR; } Tk_AddOption(tkwin, argv[srcIndex], argv[srcIndex+1], TK_INTERACTIVE_PRIO); srcIndex += 2; argc -= 2; break; default: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "bad argument type %d in Tk_ArgvInfo", infoPtr->type)); Tcl_SetErrorCode(interp, "TK", "API_ABUSE", NULL); return TCL_ERROR; } } /* * If we broke out of the loop because of an OPT_REST argument, copy the * remaining arguments down. */ argsDone: while (argc) { argv[dstIndex] = argv[srcIndex]; srcIndex++; dstIndex++; argc--; } argv[dstIndex] = NULL; *argcPtr = dstIndex; return TCL_OK; missingArg: Tcl_SetObjResult(interp, Tcl_ObjPrintf( "\"%s\" option requires an additional argument", curArg)); Tcl_SetErrorCode(interp, "TK", "ARG", "MISSING", curArg, NULL); return TCL_ERROR; }
int main ( int argc, char** argv ) { MRI* mri = NULL; int zX = 256; int zY = 256; int zZ = 256; int err = NO_ERROR; int nX = 0; int nY = 0; int nZ = 0; float sizeX = 1.0; float sizeY = 1.0; float sizeZ = 1.0; int setMethod = SET_METHOD_XYZ; int setValue = 0; char fnVol[256] = "new_volume.mgz"; int i; char* arg = NULL; for ( i = 1; i < argc; i++ ) { arg = argv[i]; if ( argv[i] && *argv[i] != '-' ) { printf( "ERROR: Unrecognized argument %s\n", argv[i] ); PrintUsage( NULL ); exit( 1 ); } while ( arg[0] == '-' ) arg = arg+1; if ( strlen(arg) <= 0 ) continue; if ( strcmp(arg,"h") == 0 || strcmp(arg,"help") == 0 ) { PrintUsage( NULL ); exit( 0 ); } if ( strcmp(arg,"f") == 0 || strcmp(arg,"filename") == 0 ) { if ( i+1 >= argc ) { PrintUsage( "No argument to filename option." ); exit( 1 ); } strcpy( fnVol, argv[i+1] ); i++; } if ( strcmp(arg,"x") == 0 || strcmp(arg,"width") == 0 ) { if ( i+1 >= argc ) { PrintUsage( "No argument to width option." ); exit( 1 ); } zX = atoi(argv[i+1]); i++; } if ( strcmp(arg,"y") == 0 || strcmp(arg,"height") == 0 ) { if ( i+1 >= argc ) { PrintUsage( "No argument to height option." ); exit( 1 ); } zY = atoi(argv[i+1]); i++; } if ( strcmp(arg,"z") == 0 || strcmp(arg,"depth") == 0 ) { if ( i+1 >= argc ) { PrintUsage( "No argument to depth option." ); exit( 1 ); } zZ = atoi(argv[i+1]); i ++; } if ( strcmp(arg,"sizex") == 0 ) { if ( i+1 >= argc ) { PrintUsage( "No argument to sizex option." ); exit( 1 ); } sizeX = atof(argv[i+1]); i++; } if ( strcmp(arg,"sizey") == 0 ) { if ( i+1 >= argc ) { PrintUsage( "No argument to sizey option." ); exit( 1 ); } sizeY = atof(argv[i+1]); i++; } if ( strcmp(arg,"sizez") == 0 ) { if ( i+1 >= argc ) { PrintUsage( "No argument to sizez optoin." ); exit( 1 ); } sizeZ = atof(argv[i+1]); i++; } if ( strcmp(arg,"set-method") == 0 ) { if ( i+1 >= argc ) { PrintUsage( "No argument to set-method option." ); exit( 1 ); } if ( strcmp( argv[i+1], "xyz" ) == 0 ) { setMethod = SET_METHOD_XYZ; i++; printf( "set_method is xyz\n" ); } else if ( strcmp( argv[i+1], "random" ) == 0 ) { setMethod = SET_METHOD_RANDOM; i++; printf( "set_method is random\n" ); } else if ( strncmp( argv[i+1], "constant", 9 ) == 0 ) { if ( i+2 >= argc ) { PrintUsage( "No value argument to constant method option." ); exit( 1 ); } setMethod = SET_METHOD_CONSTANT; setValue = atoi( argv[i+2] ); i+=2; printf( "set_method is constant, %d\n", setValue ); } else { PrintUsage( "Unrecognized argument to set-method option" ); exit( 1 ); } } } printf( "Creating volume %s\n" " width = %d height = %d depth = %d\n" " xsize = %f ysize = %f zsize = %f\n" " set method = %s, constant = %d\n", fnVol, zX, zY, zZ, sizeX, sizeY, sizeZ, sSetMethods[setMethod], setValue ); mri = MRIalloc( zX, zY, zZ, MRI_UCHAR ); if ( NULL == mri ) { fprintf( stderr, "Couldn't create volume.\n" ); return 1; } MRIsetResolution( mri, sizeX, sizeY, sizeZ ); switch ( setMethod ) { case SET_METHOD_CONSTANT: MRIvalueFill( mri, 0 ); break; case SET_METHOD_RANDOM: for ( nZ = 0; nZ < zZ; nZ++ ) { for ( nY = 0; nY < zY; nY++ ) { for ( nX = 0; nX < zX; nX++ ) { MRIvox( mri, nX, nY, nZ ) = (int)((random()/(float)RAND_MAX)*255.0); } } } break; case SET_METHOD_XYZ: for ( nZ = 0; nZ < zZ; nZ++ ) { for ( nY = 0; nY < zY; nY++ ) { for ( nX = 0; nX < zX; nX++ ) { MRIvox( mri, nX, nY, nZ ) = (((float)nZ/(float)zZ)*255.0/3.0) + (((float)nY/(float)zY)*255.0/3.0) + (((float)nX/(float)zX)*255.0/3.0) ; } } } break; default: for ( nZ = (zZ/2) - (zZ/4); nZ < (zZ/2) + (zZ/4); nZ++ ) { for ( nY = (zY/2) - (zY/4); nY < (zY/2) + (zY/4); nY++ ) { for ( nX = (zX/2) - (zX/4); nX < (zX/2) + (zX/4); nX++ ) { MRIvox( mri, nX, nY, nZ ) = 255; } } } } err = MRIwrite( mri, fnVol ); if ( NO_ERROR != err ) { fprintf( stderr, "Couldn't write volume.\n" ); return 1; } MRIfree( &mri ); return 0; }
int main(int argc, char *argv[]) { FILE *fp; char *fastaFileName=NULL; int minUnitLength=-1, maxUnitLength=-1; int minLength=-1; char unit[MAX_UNIT_LENGTH+1]="\0"; RGBinary rg; int c; while((c = getopt(argc, argv, "f:m:r:M:h")) >= 0) { switch(c) { case 'f': fastaFileName=strdup(optarg); break; case 'h': return PrintUsage(); case 'm': minUnitLength=atoi(optarg); break; case 'M': maxUnitLength=atoi(optarg); break; case 'r': minLength=atoi(optarg); break; default: fprintf(stderr, "Unrecognized option: -%c\n", c); return 1; } } if(1 == argc || argc != optind) { return PrintUsage(); } if(NULL == fastaFileName) { PrintError(Name, "fastaFileName", "Command line option", Exit, InputArguments); } if(minUnitLength <= 0) { PrintError(Name, "minUnitLength", "Command line option", Exit, InputArguments); } if(maxUnitLength <= 0) { PrintError(Name, "maxUnitLength", "Command line option", Exit, InputArguments); } if(minLength <= 0) { PrintError(Name, "minLength", "Command line option", Exit, InputArguments); } assert(minUnitLength <= maxUnitLength); assert(maxUnitLength <= MAX_UNIT_LENGTH); if(!(fp = fdopen(fileno(stdout), "w"))) { PrintError(Name, "stdout", "Could not open stdout for writing", Exit, OpenFileError); } /* Read in the rg binary file */ RGBinaryReadBinary(&rg, NTSpace, fastaFileName); fprintf(stderr, "Currently on:\n%2d %9d", -1, -1); /* For each contig */ int curContig, curContigIndex; for(curContig=1, curContigIndex=0; curContig <= rg.numContigs && curContigIndex < rg.numContigs; curContig++, curContigIndex++) { /* For each starting position */ int curPos; int prevBestUnitLength=-1; int prevBestStart=-1; int prevBestLength=-1; int prevBestEnd=-1; for(curPos=1; curPos <= rg.contigs[curContigIndex].sequenceLength; curPos++) { if(curPos%BREPEAT_ROTATE_NUM==0) { fprintf(stderr, "\r%2d %9d", curContig, curPos); } if(ToLower(RGBinaryGetBase(&rg, curContig, curPos)) != 'n') { /* For each unit length */ int bestEnd=-1; char bestUnit[MAX_UNIT_LENGTH+1]="\0"; int bestUnitLength=-1; int curUnitLength; for(curUnitLength=minUnitLength;curUnitLength<=maxUnitLength;curUnitLength++) { /* For each unit length */ /* Check bounds */ if(curPos + curUnitLength - 1 <= rg.contigs[curContigIndex].sequenceLength) { /* Get the current unit */ int i; for(i=0;i<curUnitLength;i++) { unit[i] = ToLower(RGBinaryGetBase(&rg, curContig, curPos+i)); } unit[curUnitLength]='\0'; int end = curPos+curUnitLength-1; /* extend the unit */ int cont=1; int curStart; for(curStart=curPos + curUnitLength;cont==1 && curStart <= rg.contigs[curContigIndex].sequenceLength-curUnitLength+1;curStart+=curUnitLength) { /* Check that the bases match cur */ int j; for(j=0;j<curUnitLength;j++) { if(unit[j] != ToLower(RGBinaryGetBase(&rg, curContig, curStart+j))) { cont = 0; } } if(cont == 1) { end = curStart+curUnitLength-1; } } if(end-curPos+1 >= minLength && (end - curPos +1 ) > curUnitLength && (bestEnd <= 0 || end-curPos+1 > (bestEnd - curPos + 1))) { bestEnd = end; strcpy(bestUnit, unit); bestUnitLength = curUnitLength; } } } if(bestEnd > 0 && bestUnitLength < (bestEnd - curPos + 1)) { assert(bestEnd-curPos+1 >= minLength); if(curPos == prevBestStart + 1 && prevBestUnitLength == bestUnitLength && prevBestLength == (bestEnd-curPos+1)) { /* Skip */ } else if(bestEnd <= prevBestEnd) { /* Skip */ } else { fprintf(fp, "contig%d:%d-%d\t%d\t%d\t%s\n", curContig, curPos, bestEnd, bestEnd-curPos+1, bestUnitLength, bestUnit); fflush(fp); } prevBestUnitLength = bestUnitLength; prevBestStart = curPos; prevBestLength = bestEnd-curPos+1; prevBestEnd = bestEnd; } } } } fprintf(stderr, "\n%s", BREAK_LINE); fprintf(stderr, "Cleaning up.\n"); /* Delete the rg */ RGBinaryDelete(&rg); fclose(fp); fprintf(stderr, "Terminating successfully.\n"); fprintf(stderr, "%s", BREAK_LINE); return 0; }
int main (int argc, char *argv[]) { DisplayModeRec *Mode; int HDisplay = 0, VDisplay = 0; float VRefresh = 0.0; Bool Reduced = FALSE, Verbose = FALSE, IsCVT; Bool Interlaced = FALSE; int n; if ((argc < 3) || (argc > 7)) { PrintUsage(argv[0]); return 1; } /* This doesn't filter out bad flags properly. Bad flags get passed down * to atoi/atof, which then return 0, so that these variables can get * filled next time round. So this is just a cosmetic problem. */ for (n = 1; n < argc; n++) { if (!strcmp(argv[n], "-r") || !strcmp(argv[n], "--reduced")) Reduced = TRUE; else if (!strcmp(argv[n], "-i") || !strcmp(argv[n], "--interlaced")) Interlaced = TRUE; else if (!strcmp(argv[n], "-v") || !strcmp(argv[n], "--verbose")) Verbose = TRUE; else if (!strcmp(argv[n], "-h") || !strcmp(argv[n], "--help")) { PrintUsage(argv[0]); return 0; } else if (!HDisplay) { HDisplay = atoi(argv[n]); if (!HDisplay) { PrintUsage(argv[0]); return 1; } } else if (!VDisplay) { VDisplay = atoi(argv[n]); if (!VDisplay) { PrintUsage(argv[0]); return 1; } } else if (!VRefresh) { VRefresh = atof(argv[n]); if (!VRefresh) { PrintUsage(argv[0]); return 1; } } else { PrintUsage(argv[0]); return 1; } } if (!HDisplay || !VDisplay) { PrintUsage(argv[0]); return 0; } /* Default to 60.0Hz */ if (!VRefresh) VRefresh = 60.0; /* Horizontal timing is always a multiple of 8: round up. */ if (HDisplay & 0x07) { HDisplay &= ~0x07; HDisplay += 8; } if (Reduced) { if ((VRefresh / 60.0) != floor(VRefresh / 60.0)) { fprintf(stderr, "\nERROR: Multiple of 60Hz refresh rate required for " " reduced blanking.\n"); PrintUsage(argv[0]); return 0; } } IsCVT = CVTCheckStandard(HDisplay, VDisplay, VRefresh, Reduced, Verbose); Mode = xf86CVTMode(HDisplay, VDisplay, VRefresh, Reduced, Interlaced); PrintComment(Mode, IsCVT, Reduced); PrintModeline(Mode, HDisplay, VDisplay, VRefresh, Reduced); return 0; }
int HandleCLIOptions(int argc,char *argv[], OPTIONS *options) { int i,firstnonoption=0; for (i=1; i< argc;i++) { if (argv[i][0] == '/' || argv[i][0] == '-') { switch (argv[i][1]) { /* An argument -? means help is requested */ case '?': PrintUsage(argv[0]); break; case 'h': case 'H': if (!stricmp(argv[i]+1,"help")) { PrintUsage(argv[0]); } if (!stricmp(argv[i]+1,"height")) { //also might mean height if (i+1<argc) { options->height = strtol(argv[i+1], NULL, 0); i++; } } break; case 'n': case 'N': if (!stricmp(argv[i]+1,"north") || *(argv[i]+2)==0) { //if it's north or n (terminated with 0) if (i+1<argc) { options->north = strtod(argv[i+1], NULL); i++; } } break; case 's': case 'S': if (!stricmp(argv[i]+1,"south") || *(argv[i]+2)==0) { //if it's north or n (terminated with 0) if (i+1<argc) { options->south = strtod(argv[i+1], NULL); i++; } } break; case 'w': case 'W': if (!stricmp(argv[i]+1,"west") || *(argv[i]+2)==0) { //if it's north or n (terminated with 0) if (i+1<argc) { options->west = strtod(argv[i+1], NULL); i++; } } if (!stricmp(argv[i]+1,"width")) { //also might mean height if (i+1<argc) { options->width = strtol(argv[i+1], NULL, 0); i++; } } break; case 'e': case 'E': if (!stricmp(argv[i]+1,"east") || *(argv[i]+2)==0) { //if it's north or n (terminated with 0) if (i+1<argc) { options->east = strtod(argv[i+1], NULL); i++; } } break; case 'x': case 'X': if (i+1<argc) { options->width = strtol(argv[i+1], NULL, 0); i++; } break; case 'y': case 'Y': if (i+1<argc) { options->height = strtol(argv[i+1], NULL, 0); i++; } break; /* //I've stopped using zoom as an argument case 'z': case 'Z': if (i+1<argc) { options->zoom = strtod(argv[i+1], NULL); i++; //move to the next variable, we've got a zoom } break; */ case 'g': //the grid case 'G': if (i+1<argc) { options->gridsize = strtod(argv[i+1], NULL); i++; } break; case 'c': //how to cycle through the colours case 'C': if (i+1<argc) { if (!stricmp(argv[i+1],"day")) options->colourcycle=60*60*24; else if (!stricmp(argv[i+1],"week")) options->colourcycle=60*60*24*7; else if (!stricmp(argv[i+1],"month")) options->colourcycle=60*60*24*30.4375; else if (!stricmp(argv[i+1],"halfyear")) options->colourcycle=60*60*24*182.625; else if (!stricmp(argv[i+1],"year")) options->colourcycle=60*60*24*365.25; else if (!stricmp(argv[i+1],"hour")) options->colourcycle=60*60; else options->colourcycle = strtol(argv[i+1], NULL, 0); i++; } break; case 'p': case 'P': if (!stricmp(argv[i]+1,"preset") || *(argv[i]+2)==0) { //preset or just p if (i+1<argc) { LoadPreset(options, argv[i+1]); i++; } } break; case 'a': //alpha value case 'A': if (i+1<argc) { options->alpha = strtod(argv[i+1], NULL); i++; } break; case 'f': //from time case 'F': if (i+1<argc) { options->fromtimestamp = strtol(argv[i+1], NULL,0); i++; } break; case 't': //to time case 'T': if (i+1<argc) { options->totimestamp = strtol(argv[i+1], NULL,0); i++; } break; case 'k': case 'K': if (i+1<argc) { options->kmlfilenameinput = argv[i+1]; i++; } break; case 'i': case 'I': if (i+1<argc) { options->jsonfilenameinput = argv[i+1]; i++; } break; case 'o': case 'O': if (i+1<argc) { options->pngfilenameinput = argv[i+1]; i++; } break; default: fprintf(stderr,"unknown option %s\n",argv[i]); break; } } else { options->pngfilenameinput = argv[i]; firstnonoption = i; break; } } return firstnonoption; }
static void ProcOptList( int pass ) { char buff[80]; char err_buff[CMD_LEN]; char *curr; unsigned long mem; SetupChar(); /* initialize scanner */ for( ;; ) { SkipSpaces(); if( !OptDelim( CurrChar ) ) break; NextChar(); curr = buff; #ifndef __GUI__ if( CurrChar == '?' ) { PrintUsage( MSG_USAGE_BASE ); StartupErr( "" ); } #endif while( isalnum( CurrChar ) ) { *curr++ = CurrChar; NextChar(); } if( curr == buff ) { if( OptDelim( CurrChar ) ) { NextChar(); SkipSpaces(); break; } OptError( LIT_ENG( STARTUP_No_Recog_Optn ) ); } switch( Lookup( OptNameTab, buff, curr - buff ) ) { case OPT_CONTINUE_UNEXPECTED_BREAK: _SwitchOn( SW_CONTINUE_UNEXPECTED_BREAK ); break; case OPT_DEFERSYM: _SwitchOn( SW_DEFER_SYM_LOAD ); break; case OPT_DOWNLOAD: DownLoadTask = true; break; case OPT_NOEXPORTS: _SwitchOn( SW_NO_EXPORT_SYMS ); break; case OPT_LOCALINFO: if( pass == 2 ) { char *symfile = GetFileName( pass ); FindLocalDebugInfo( symfile ); _Free( symfile ); } break; case OPT_INVOKE: if( pass == 2 ) _Free( InvokeFile ); InvokeFile = GetFileName( pass ); break; case OPT_NOINVOKE: if( pass == 2 ) _Free( InvokeFile ); InvokeFile = NULL; break; case OPT_NOSOURCECHECK: _SwitchOff( SW_CHECK_SOURCE_EXISTS ); break; case OPT_NOSYMBOLS: _SwitchOff( SW_LOAD_SYMS ); break; case OPT_NOMOUSE: _SwitchOff( SW_USE_MOUSE ); break; case OPT_DYNAMIC: mem = GetMemory(); if( pass == 1 ) { if( mem < MIN_MEM_SIZE ) mem = MIN_MEM_SIZE; MemSize = mem; } break; case OPT_DIP: { int i; for( i = 0; DipFiles[i] != NULL; ++i ) ; DipFiles[i] = GetFileName( pass ); } break; case OPT_TRAP: if( pass == 2 ) _Free( TrapParms ); TrapParms = GetFileName( pass ); SkipSpaces(); if( CurrChar == TRAP_PARM_SEPARATOR ) { NextChar(); GetTrapParm( pass ); } else if( CurrChar == '{' ) { GetTrapParm( pass ); } break; #ifdef ENABLE_TRAP_LOGGING case OPT_TRAP_DEBUG_FLUSH: if( pass == 2 ) _Free( TrapTraceFileName ); TrapTraceFileName = GetFileName( pass ); TrapTraceFileFlush = true; break; case OPT_TRAP_DEBUG: if( pass == 2 ) _Free( TrapTraceFileName ); TrapTraceFileName = GetFileName( pass ); TrapTraceFileFlush = false; break; #endif case OPT_REMOTE_FILES: _SwitchOn( SW_REMOTE_FILES ); break; case OPT_LINES: DUISetNumLines( GetValue() ); break; case OPT_COLUMNS: DUISetNumColumns( GetValue() ); break; #ifdef BACKWARDS case OPT_NO_FPU: case OPT_NO_ALTSYM: break; case OPT_REGISTERS: GetValue(); break; #endif case OPT_INITCMD: GetInitCmd( pass ); break; case OPT_POWERBUILDER: _SwitchOn( SW_POWERBUILDER ); break; case OPT_HELP: #ifndef __GUI__ PrintUsage( MSG_USAGE_BASE ); StartupErr( "" ); #endif break; default: if( !ProcSysOption( buff, curr - buff, pass ) && !DUIScreenOption( buff, curr - buff, pass ) ) { Format( err_buff, LIT_ENG( STARTUP_Invalid_Option ), buff, curr - buff ); StartupErr( err_buff ); } break; } } }
void GetFlags(int nargs, char **args, int **nreps, int *flsizeKB, int *mflop, int **ROUTs, int *ldagap, int **Ns, int **Ms, int **UPLOs, int **SDs) { int *NBs=NULL, *ns=NULL, *ms=NULL, *ups=NULL, *sds=NULL, *ip; int i, k, n; *ROUTs = NULL; *ldagap = 0; *flsizeKB = L2SIZE/1024; *nreps = NULL; *mflop = 0; for (i=1; i < nargs; i++) { if (args[i][0] != '-') PrintUsage(args[0], i, args[i]); switch(args[i][1]) { case 'n': /* -n or -nb */ ns = GetIntList(nargs, args, i, 1); i += ns[0] + 1; break; case 'm': /* -m # <M1> ... <M#> */ ms = GetIntList(nargs, args, i, 1); i += ms[0] + 1; break; case 'N': /* -N or -NB */ case 'M': /* -M <Mstart> <Mend> <Minc>\n"); */ if (i+3 >= nargs) PrintUsage(args[0], i, NULL); ip = IntRange2IntList(atoi(args[i+1]),atoi(args[i+2]),atoi(args[i+3])); if (args[i][0] == 'M') ms = ip; else /* -N <Nstart> <Nend> <Ninc>\n"); */ ns = ip; i += 3; break; case 'R': /* -R # <rout1> ... <routN#> */ *ROUTs = RoutNames2IntList(nargs, args, i); i += (*ROUTs)[0] + 1; break; case '#': /* set nreps */ if (args[i][2] == 't') /* -#t N1 reps1 ... Nt repst */ { *nreps = GetIntList(nargs, args, i, 2); i += ((*nreps)[0] << 1) + 1; } else /* -# <reps> */ { if (++i >= nargs) PrintUsage(args[0], i, NULL); *nreps = GetIntList2(0, atoi(args[i])); } break; case 'f': /* -f <flushKB> */ if (++i >= nargs) PrintUsage(args[0], i, NULL); *flsizeKB = atoi(args[i]); break; case 'F': /* -F <mflop> */ if (++i >= nargs) PrintUsage(args[0], i, NULL); *mflop = atoi(args[i]); break; case 'U': /* -U <nup> <u1> ... <uN>;[u,l,q,g] */ if (++i >= nargs) PrintUsage(args[0], i, NULL); n = atoi(args[i]); ATL_assert(n > 0); ups = malloc(sizeof(int)*(n+1)); ups[0] = n; for (k=0; k < n; k++) { if (++i >= nargs) PrintUsage(args[0], i, NULL); switch(args[i][0]) { case 'U': case 'u': ups[k+1] = LAUpper; break; case 'l': case 'L': default: ups[k+1] = LALower; break; } } break; case 'S': /* -S <#> <side1> ... <sideN> */ if (++i >= nargs) PrintUsage(args[0], i, NULL); n = atoi(args[i]); ATL_assert(n > 0); sds = malloc(sizeof(int)*(n+1)); sds[0] = n; for (k=0; k < n; k++) { if (++i >= nargs) PrintUsage(args[0], i, NULL); switch(args[i][0]) { case 'L': case 'l': sds[k+1] = LALeft; break; default: sds[k+1] = LARight; break; } } break; case 'a': /* -a <ldagap> */ if (++i >= nargs) PrintUsage(args[0], i, NULL); *ldagap = atoi(args[i]); break; default: PrintUsage(args[0], i, args[i]); } } /* * Take default values */ if (!(*ROUTs)) *ROUTs = GetIntList1(LAgeqrf); if (!(*nreps)) *nreps = GetIntList2(0, 1); if (!ns) ns = GetIntList1(1000); if (!ms) ms = GetIntList1(0); if (!ups) ups = GetIntList1(LAUpper); if (!sds) sds = GetIntList1(LARight); *Ns = ns; *Ms = ms; *UPLOs = ups; *SDs = sds; }
void ParseCommandLine(int argc, char *argv[]) { int count, val; if (argc < 2) return; if (strcmp(argv[1],"-user")==0) { ParseCommandLineUpdateUser(argc,argv); exit(0); } for (count=1; count < argc; count++) { val=MatchTokenFromList(argv[count],ArgStrings,MATCH_TOKEN_CASE); switch (val) { case ARG_PROXY: Settings.Flags |= MODE_FTP_PROXY; break; case ARG_CHHOME: Settings.Flags |= FLAG_CHHOME; break; case ARG_SYSLOG: Settings.Flags |= FLAG_SYSLOG; break; case ARG_INETD: case ARG_INETD2: Settings.Flags |= MODE_INETD; break; case ARG_CHROOT: Settings.Flags|=FLAG_CHROOT; Settings.Chroot=CopyStr(Settings.Chroot,argv[++count]); break; case ARG_CHSHARE: Settings.Flags|=FLAG_CHSHARE; Settings.Chroot=CopyStr(Settings.Chroot,argv[++count]); break; case ARG_PORT: case ARG_PORT2: Settings.Port=atoi(argv[++count]); break; case ARG_NODEMON: Settings.Flags &= ~FLAG_DEMON; break; case ARG_CONFIG_FILE: Settings.ConfigFile=CopyStr(Settings.ConfigFile,argv[++count]); break; case ARG_AUTH_METHODS: Settings.AuthMethods=CopyStr(Settings.AuthMethods,argv[++count]); break; case ARG_AUTH_FILE: Settings.AuthFile=CopyStr(Settings.AuthFile,argv[++count]); break; case ARG_LOGFILE: case ARG_LOGFILE2: Settings.LogPath=CopyStr(Settings.LogPath,argv[++count]); break; case ARG_ALLOWUSERS: Settings.AllowUsers=CopyStr(Settings.AllowUsers,argv[++count]); break; case ARG_DENYUSERS: Settings.DenyUsers=CopyStr(Settings.DenyUsers,argv[++count]); break; case ARG_NOPASV: Settings.Flags |= FLAG_NOPASV; break; case ARG_DCLOW: Settings.DataConnectionLowPort=atoi(argv[++count]); break; case ARG_DCHIGH: Settings.DataConnectionHighPort=atoi(argv[++count]); break; case ARG_IDLE: Settings.DefaultIdle=atoi(argv[++count]); break; case ARG_MAXIDLE: Settings.MaxIdle=atoi(argv[++count]); break; case ARG_MLOCKS: Settings.Flags |= FLAG_MLOCK; break; case ARG_ALOCKS: Settings.Flags |= FLAG_ALOCK; break; case ARG_MALOCKS: Settings.Flags |= FLAG_MLOCK | FLAG_ALOCK; break; case ARG_BINDADDRESS: case ARG_INTERFACE: Settings.BindAddress=CopyStr(Settings.BindAddress,argv[++count]); break; case ARG_IPV4: Settings.BindAddress=CopyStr(Settings.BindAddress,"0.0.0.0"); break; case ARG_UPDATE_PASSWORD: Settings.UpdatePasswordType=CopyStr(Settings.UpdatePasswordType, argv[++count]); break; case ARG_CONFIRM_TRANSFER: Settings.ConfirmTransfer=MatchTokenFromList(argv[++count],HashNames,0); break; /* case ARG_PERMITTEDCOMMANDS: Settings.PermittedCommands=CopyStr(Settings.PermittedCommands,argv[++count]); break; */ case ARG_HELP1: case ARG_HELP2: case ARG_HELP3: PrintUsage(); break; case ARG_VERSION: case ARG_VERSION2: printf("metaftpd %s\n",Version); exit(0); break; } } if ( (! (Settings.Flags & MODE_FTP_SERVER)) && (! (Settings.Flags & MODE_FTP_PROXY)) ) { Settings.Flags |= MODE_FTP_SERVER; } }
void GetFlags(int nargs, char **args, int *MFLOP, int *CacheSize, TYPE *thresh, int *ldagap, int *nuplo, enum ATLAS_UPLO **Uplo, int *N0, int *NN, int *incN) { int i, j, n; char ch; *MFLOP = 0; #ifdef L2SIZE *CacheSize = L2SIZE; #else *CacheSize = 4*1024*1024; #endif *thresh = 100.0; *N0 = *NN = *incN = -1; *ldagap = 0; *nuplo = -1; for (i=1; i < nargs; i++) { if (args[i][0] != '-') PrintUsage(args[0]); switch(args[i][1]) { case 'T': *thresh = atof(args[++i]); break; case 'C': *CacheSize = 1024*atoi(args[++i]); break; case 'l': *ldagap = atoi(args[++i]); break; case 'n': *N0 = *NN = *incN = atoi(args[++i]); break; case 'N': *N0 = atoi(args[++i]); *NN = atoi(args[++i]); *incN = atoi(args[++i]); break; case 'F': *MFLOP = atoi(args[++i]); break; case 'U': *nuplo = atoi(args[++i]); if (*nuplo <= 0) PrintUsage(args[0]); *Uplo = malloc(*nuplo * sizeof(enum ATLAS_UPLO)); ATL_assert(*Uplo); for (j=0; j != *nuplo; j++) { if (args[i] == NULL) PrintUsage(args[0]); ch = *args[++i]; if (ch == 'u' || ch == 'U') (*Uplo)[j] = AtlasUpper; else if (ch == 'l' || ch == 'L') (*Uplo)[j] = AtlasLower; else PrintUsage(args[0]); } break; default: PrintUsage(args[0]); } } if (*N0 == -1) { *N0 = 100; *NN = 1000; *incN = 100; } if (*nuplo == -1) { *nuplo = 1; *Uplo = malloc(sizeof(enum ATLAS_UPLO)); ATL_assert(*Uplo); **Uplo = AtlasLower; } }
int main(int argc, char **argv) { Uint8* RawMooseData; SDL_RWops* handle; SDL_Surface* screen; SDL_Surface* MooseFrame[MOOSEFRAMES_COUNT]; SDL_Overlay* overlay; SDL_Rect overlayrect; SDL_Event event; Uint32 lastftick; int paused=0; int resized=0; int i; int fps=12; int fpsdelay; int overlay_format=SDL_YUY2_OVERLAY; int scale=5; while ( argc > 1 ) { if (strcmp(argv[1], "-fps")== 0) { if (argv[2]) { fps = atoi(argv[2]); if (fps==0) { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); return -1; } if ((fps<0) || (fps>1000)) { fprintf(stderr, "The -fps option must be in range from 1 to 1000, default is 12.\n"); return -1; } argv += 2; argc -= 2; } else { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); return -1; } } else if (strcmp(argv[1], "-format") == 0) { if (argv[2]) { if (!strcmp(argv[2],"YV12")) overlay_format = SDL_YV12_OVERLAY; else if(!strcmp(argv[2],"IYUV")) overlay_format = SDL_IYUV_OVERLAY; else if(!strcmp(argv[2],"YUY2")) overlay_format = SDL_YUY2_OVERLAY; else if(!strcmp(argv[2],"UYVY")) overlay_format = SDL_UYVY_OVERLAY; else if(!strcmp(argv[2],"YVYU")) overlay_format = SDL_YVYU_OVERLAY; else { fprintf(stderr, "The -format option %s is not recognized, see help for info.\n", argv[2]); return -1; } argv += 2; argc -= 2; } else { fprintf(stderr, "The -format option requires an argument, default is YUY2.\n"); return -1; } } else if (strcmp(argv[1], "-scale") == 0) { if (argv[2]) { scale = atoi(argv[2]); if (scale==0) { fprintf(stderr, "The -scale option requires an argument [from 1 to 50], default is 5.\n"); return -1; } if ((scale<0) || (scale>50)) { fprintf(stderr, "The -scale option must be in range from 1 to 50, default is 5.\n"); return -1; } argv += 2; argc -= 2; } else { fprintf(stderr, "The -fps option requires an argument [from 1 to 1000], default is 12.\n"); return -1; } } else if ((strcmp(argv[1], "-help") == 0 ) || (strcmp(argv[1], "-h") == 0)) { PrintUsage(argv[0]); return 0; } else { fprintf(stderr, "Unrecognized option: %s.\n", argv[1]); return -1; } break; } RawMooseData=(Uint8*)malloc(MOOSEFRAME_SIZE * MOOSEFRAMES_COUNT); if (RawMooseData==NULL) { fprintf(stderr, "Can't allocate memory for movie !\n"); free(RawMooseData); return 1; } /* load the trojan moose images */ handle=SDL_RWFromFile("moose.dat", "rb"); if (handle==NULL) { fprintf(stderr, "Can't find the file moose.dat !\n"); free(RawMooseData); return 2; } SDL_RWread(handle, RawMooseData, MOOSEFRAME_SIZE, MOOSEFRAMES_COUNT); SDL_RWclose(handle); if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) { fprintf(stderr, "Couldn't initialize SDL: %s\n", SDL_GetError()); free(RawMooseData); return 3; } atexit(SDL_Quit); /* Set video mode */ if ( (screen=SDL_SetVideoMode(MOOSEPIC_W*scale, MOOSEPIC_H*scale, 0, SDL_RESIZABLE | SDL_SWSURFACE)) == NULL ) { fprintf(stderr, "Couldn't set video mode: %s\n", 0, SDL_GetError()); free(RawMooseData); return 4; } /* Set the window manager title bar */ SDL_WM_SetCaption("SDL test overlay: running moose", "testoverlay2"); for (i=0; i<MOOSEFRAMES_COUNT; i++) { MooseFrame[i]=SDL_CreateRGBSurfaceFrom(RawMooseData+i*MOOSEFRAME_SIZE, MOOSEPIC_W, MOOSEPIC_H, 8, MOOSEPIC_W, 0, 0, 0, 0); if (MooseFrame[i]==NULL) { fprintf(stderr, "Couldn't create SDL_Surfaces:%s\n", 0, SDL_GetError()); free(RawMooseData); return 5; } SDL_SetColors(MooseFrame[i], MooseColors, 0, 84); { SDL_Surface *newsurf; SDL_PixelFormat format; format.palette=NULL; format.BitsPerPixel=32; format.BytesPerPixel=4; #if SDL_BYTEORDER == SDL_LIL_ENDIAN format.Rshift=0; format.Gshift=8; format.Bshift=16; #else format.Rshift=24; format.Gshift=16; format.Bshift=8; #endif format.Ashift=0; format.Rmask=0xff<<format.Rshift; format.Gmask=0xff<<format.Gshift; format.Bmask=0xff<<format.Bshift; format.Amask=0; format.Rloss=0; format.Gloss=0; format.Bloss=0; format.Aloss=8; format.colorkey=0; format.alpha=0; newsurf=SDL_ConvertSurface(MooseFrame[i], &format, SDL_SWSURFACE); if(!newsurf) { fprintf(stderr, "Couldn't convert picture to 32bits RGB: %s\n", SDL_GetError()); return 6; } SDL_FreeSurface(MooseFrame[i]); MooseFrame[i]=newsurf; } } free(RawMooseData); overlay=SDL_CreateYUVOverlay(MOOSEPIC_W, MOOSEPIC_H, overlay_format, screen); if (!overlay) { fprintf(stderr, "Couldn't create overlay: %s\n", SDL_GetError()); return 7; } printf("Created %dx%dx%d %s %s overlay\n",overlay->w,overlay->h,overlay->planes, overlay->hw_overlay?"hardware":"software", overlay->format==SDL_YV12_OVERLAY?"YV12": overlay->format==SDL_IYUV_OVERLAY?"IYUV": overlay->format==SDL_YUY2_OVERLAY?"YUY2": overlay->format==SDL_UYVY_OVERLAY?"UYVY": overlay->format==SDL_YVYU_OVERLAY?"YVYU": "Unknown"); for(i=0; i<overlay->planes; i++) { printf(" plane %d: pitch=%d\n", i, overlay->pitches[i]); } overlayrect.x=0; overlayrect.y=0; overlayrect.w=MOOSEPIC_W*scale; overlayrect.h=MOOSEPIC_H*scale; /* set the start frame */ i=0; fpsdelay=1000/fps; /* Ignore key up events, they don't even get filtered */ SDL_EventState(SDL_KEYUP, SDL_IGNORE); lastftick=SDL_GetTicks(); /* Loop, waiting for QUIT or RESIZE */ while (1) { if (SDL_PollEvent(&event)) { switch (event.type) { case SDL_VIDEORESIZE: screen=SDL_SetVideoMode(event.resize.w, event.resize.h, 0, SDL_RESIZABLE | SDL_SWSURFACE); overlayrect.w=event.resize.w; overlayrect.h=event.resize.h; if (paused) { resized=1; } break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_SPACE) { paused=!paused; break; } if (event.key.keysym.sym != SDLK_ESCAPE) { break; } case SDL_QUIT: SDL_FreeYUVOverlay(overlay); for (i=0; i<MOOSEFRAMES_COUNT; i++) { SDL_FreeSurface(MooseFrame[i]); } return 0; } } if ((!paused)||(resized)) { if (((SDL_GetTicks()-lastftick)>fpsdelay)||(resized)) { lastftick=SDL_GetTicks(); switch (overlay_format) { case SDL_YUY2_OVERLAY: ConvertRGBtoYUY2(MooseFrame[i], overlay, 0, 100); break; case SDL_YV12_OVERLAY: ConvertRGBtoYV12(MooseFrame[i], overlay, 0, 100); break; case SDL_UYVY_OVERLAY: ConvertRGBtoUYVY(MooseFrame[i], overlay, 0, 100); break; case SDL_YVYU_OVERLAY: ConvertRGBtoYVYU(MooseFrame[i], overlay, 0, 100); break; case SDL_IYUV_OVERLAY: ConvertRGBtoIYUV(MooseFrame[i], overlay, 0, 100); break; } SDL_DisplayYUVOverlay(overlay, &overlayrect); if (!resized) { i++; if (i==10) { i=0; } } else { resized=0; } } } /* kind of timeslice to OS */ SDL_Delay(1); } return 0; }
int main(int argc,char *argv[]) { #else int TTBin2OTH(int argc,char *argv[]) { #endif char* infile = NULL; char* folder = NULL; char* name = NULL; char* extension = NULL; int calctype = -1; int strip = 0; FILE* ifp; FILE* ofp; char outfile[1024]; unsigned char* buffer; int length; unsigned char* outbuffer; unsigned int outlength; int n; char* tmpfilename = "bin2oth.tmp"; int quiet = 0; // check for too less arguments if (argc < 4) { #ifndef EMBEDDED_USE PrintUsage(); #endif return 1; } // parse arguments for (n=1; n<argc; n++) { if (!strcmp(argv[n], "-89")) calctype = CALC_TI89; else if (!strcmp(argv[n], "-92")) calctype = CALC_TI92P; else if (!strcmp(argv[n], "-strip")) strip = 1; else if (!strcmp(argv[n], "-quiet")) quiet = 1; else if (argv[n][0] == '-') { fprintf(stderr,"ERROR: invalid option %s",argv[n]); return 1; } else if (!extension) extension = argv[n]; else if (!infile) infile = argv[n]; else if (!name) name = argv[n]; else if (!folder) folder = argv[n]; else { #ifndef EMBEDDED_USE PrintUsage(); #endif return 1; } } // check if all necessary arguments are supplied if (!infile || !name || calctype == -1 || !extension) { #ifndef EMBEDDED_USE PrintUsage(); #endif return 1; } n = strlen(extension); if (n<1 || n>4) { fprintf(stderr,"ERROR: extension length must be between 1 and 4 characters\n"); return 1; } if (strip) { char* params[4]; params[0] = ""; params[1] = "-quiet"; params[2] = infile; params[3] = tmpfilename; if (TTStrip(4,params)) { fprintf(stderr,"ERROR: stripping inputfile %s failed\n",infile); return 1; } infile = tmpfilename; } #ifndef EMBEDDED_USE if (!quiet) PRINT_ID("TTBin2OTH"); #endif if (!(ifp = fopen(infile,"rb"))) { fprintf(stderr,"ERROR: cannot open inputfile %s\n",infile); if (strip) remove(tmpfilename); return 1; } if (calctype == CALC_TI89) sprintf(outfile,"%s.89y",name); else sprintf(outfile,"%s.9xy",name); if (!(ofp = fopen(outfile,"wb"))) { fprintf(stderr,"ERROR: cannot open outputfile %s\n",outfile); fclose(ifp); if (strip) remove(tmpfilename); return 1; } // read infile into buffer fseek(ifp,0,SEEK_END); length = ftell(ifp); buffer = (unsigned char*)malloc(length); if (!buffer) { fprintf(stderr,"ERROR: cannot allocate memory (%d bytes)\n",length); fclose(ifp); fclose(ofp); if (strip) remove(tmpfilename); return 1; } rewind(ifp); fread(buffer,1,length,ifp); fclose(ifp); outbuffer = DataBuffer2OTHBuffer(calctype,folder,name,extension,length,buffer,&outlength); n = 0; if (!outbuffer) { n = 1; } else { if (fwrite(outbuffer,outlength,1,ofp) != 1) { fprintf(stderr,"ERROR: cannot write %u bytes to outputfile to %s\n",outlength,outfile); n = 1; } else { if (!quiet) fprintf(stdout,"%u bytes written to %s\n",outlength,outfile); } free(outbuffer); } free(buffer); fclose(ofp); if (strip) remove(tmpfilename); return n; }
int GetFlags(int nargs, char **args, int *CacheLevel, enum OSTYPE *OS, enum ASMDIA *asmd, char **targ) { int i, flag=0, k; *CacheLevel = 0; *targ = NULL; for (i=1; i < nargs; i++) { if (args[i][0] != '-') PrintUsage(args[0],i); switch(args[i][1]) { case 'T': if (++i >= nargs) PrintUsage(args[0], i); *targ = args[i]; break; case 's': if (++i >= nargs) PrintUsage(args[0], i); *asmd = atoi(args[i]); break; case 'O': if (++i >= nargs) PrintUsage(args[0], i); *OS = atoi(args[i]); break; case 'n': flag |= Pncpu; break; case 'c': flag |= Pncache; break; case 'C': if (++i >= nargs) PrintUsage(args[0], i); *CacheLevel = atoi(args[i]); break; case 'v': if (++i >= nargs) PrintUsage(args[0], i); k = atoi(args[i]); if (k) flag |= Pverb; break; case 'm': flag |= PMhz; break; case 'a': flag |= Parch; break; case 'b': flag |= P64; break; case 't': flag |= Pthrottle; break; default: PrintUsage(args[0], i); } } if (!flag) flag = Parch; return(flag); }
/* HandleInputLine is NOT thread safe - due to readdir issues, resolving them portably is not really simple. */ int HandleInputLine( int argc, char **argv, FILE * out) { #if defined(HAVE_OPENDIR) && defined (HAVE_READDIR) DIR *curdir; /* to read current dir with ls */ struct dirent *dent; #endif #if defined(HAVE_SYS_STAT_H) struct stat st; #endif /* Reset errno to 0 before we start. */ if (RemoteMode) { if (argc > 1 && strcmp("quit", argv[1]) == 0) { if (argc > 2) { printf("ERROR: invalid parameter count for quit\n"); return (1); } exit(0); } #if defined(HAVE_OPENDIR) && defined(HAVE_READDIR) && defined(HAVE_CHDIR) if (argc > 1 && strcmp("cd", argv[1]) == 0) { if (argc > 3) { printf("ERROR: invalid parameter count for cd\n"); return (1); } #if ! defined(HAVE_CHROOT) || ! defined(HAVE_GETUID) if (getuid() == 0 && !ChangeRoot) { printf ("ERROR: chdir security problem - rrdtool is running as " "root but not chroot!\n"); return (1); } #endif if (chdir(argv[2]) != 0) { printf("ERROR: chdir %s %s\n", argv[2], rrd_strerror(errno)); return (1); } return (0); } if (argc > 1 && strcmp("pwd", argv[1]) == 0) { char *cwd; /* To hold current working dir on call to pwd */ if (argc > 2) { printf("ERROR: invalid parameter count for pwd\n"); return (1); } cwd = getcwd(NULL, MAXPATH); if (cwd == NULL) { printf("ERROR: getcwd %s\n", rrd_strerror(errno)); return (1); } printf("%s\n", cwd); free(cwd); return (0); } if (argc > 1 && strcmp("mkdir", argv[1]) == 0) { if (argc > 3) { printf("ERROR: invalid parameter count for mkdir\n"); return (1); } #if ! defined(HAVE_CHROOT) || ! defined(HAVE_GETUID) if (getuid() == 0 && !ChangeRoot) { printf ("ERROR: mkdir security problem - rrdtool is running as " "root but not chroot!\n"); return (1); } #endif if(mkdir(argv[2], 0777)!=0) { printf("ERROR: mkdir %s: %s\n", argv[2],rrd_strerror(errno)); return (1); } return (0); } if (argc > 1 && strcmp("ls", argv[1]) == 0) { if (argc > 2) { printf("ERROR: invalid parameter count for ls\n"); return (1); } if ((curdir = opendir(".")) != NULL) { while ((dent = readdir(curdir)) != NULL) { if (!stat(dent->d_name, &st)) { if (S_ISDIR(st.st_mode)) { printf("d %s\n", dent->d_name); } if (strlen(dent->d_name) > 4 && S_ISREG(st.st_mode)) { if (!strcmp (dent->d_name + NAMLEN(dent) - 4, ".rrd") || !strcmp(dent->d_name + NAMLEN(dent) - 4, ".RRD")) { printf("- %s\n", dent->d_name); } } } } closedir(curdir); } else { printf("ERROR: opendir .: %s\n", rrd_strerror(errno)); return (errno); } return (0); } #endif /* opendir and readdir */ } if (argc < 3 || strcmp("help", argv[1]) == 0 || strcmp("--help", argv[1]) == 0 || strcmp("-help", argv[1]) == 0 || strcmp("-?", argv[1]) == 0 || strcmp("-h", argv[1]) == 0) { PrintUsage(""); return 0; } if (strcmp("create", argv[1]) == 0) rrd_create(argc - 1, &argv[1]); else if (strcmp("dump", argv[1]) == 0) rrd_dump(argc - 1, &argv[1]); else if (strcmp("info", argv[1]) == 0 || strcmp("updatev", argv[1]) == 0) { rrd_info_t *data; if (strcmp("info", argv[1]) == 0) data = rrd_info(argc - 1, &argv[1]); else data = rrd_update_v(argc - 1, &argv[1]); rrd_info_print(data); rrd_info_free(data); } else if (strcmp("--version", argv[1]) == 0 || strcmp("version", argv[1]) == 0 || strcmp("v", argv[1]) == 0 || strcmp("-v", argv[1]) == 0 || strcmp("-version", argv[1]) == 0) printf("RRDtool " PACKAGE_VERSION " Copyright by Tobi Oetiker, 1997-2008 (%f)\n", rrd_version()); else if (strcmp("restore", argv[1]) == 0) rrd_restore(argc - 1, &argv[1]); else if (strcmp("resize", argv[1]) == 0) rrd_resize(argc - 1, &argv[1]); else if (strcmp("last", argv[1]) == 0) printf("%ld\n", rrd_last(argc - 1, &argv[1])); else if (strcmp("lastupdate", argv[1]) == 0) { rrd_lastupdate(argc - 1, &argv[1]); } else if (strcmp("first", argv[1]) == 0) printf("%ld\n", rrd_first(argc - 1, &argv[1])); else if (strcmp("update", argv[1]) == 0) rrd_update(argc - 1, &argv[1]); else if (strcmp("fetch", argv[1]) == 0) { time_t start, end, ti; unsigned long step, ds_cnt, i, ii; rrd_value_t *data, *datai; char **ds_namv; if (rrd_fetch (argc - 1, &argv[1], &start, &end, &step, &ds_cnt, &ds_namv, &data) != -1) { datai = data; printf(" "); for (i = 0; i < ds_cnt; i++) printf("%20s", ds_namv[i]); printf("\n\n"); for (ti = start + step; ti <= end; ti += step) { printf("%10lu:", ti); for (ii = 0; ii < ds_cnt; ii++) printf(" %0.10e", *(datai++)); printf("\n"); } for (i = 0; i < ds_cnt; i++) free(ds_namv[i]); free(ds_namv); free(data); } } else if (strcmp("xport", argv[1]) == 0) { int xxsize; unsigned long int j = 0; time_t start, end, ti; unsigned long step, col_cnt, row_cnt; rrd_value_t *data, *ptr; char **legend_v; int enumds = 0; int i; size_t vtag_s = strlen(COL_DATA_TAG) + 10; char *vtag = malloc(vtag_s); for (i = 2; i < argc; i++) { if (strcmp("--enumds", argv[i]) == 0) enumds = 1; } if (rrd_xport (argc - 1, &argv[1], &xxsize, &start, &end, &step, &col_cnt, &legend_v, &data) != -1) { char *old_locale = setlocale(LC_NUMERIC, "C"); row_cnt = (end - start) / step; ptr = data; printf("<?xml version=\"1.0\" encoding=\"%s\"?>\n\n", XML_ENCODING); printf("<%s>\n", ROOT_TAG); printf(" <%s>\n", META_TAG); printf(" <%s>%lld</%s>\n", META_START_TAG, (long long int) start + step, META_START_TAG); printf(" <%s>%lu</%s>\n", META_STEP_TAG, step, META_STEP_TAG); printf(" <%s>%lld</%s>\n", META_END_TAG, (long long int) end, META_END_TAG); printf(" <%s>%lu</%s>\n", META_ROWS_TAG, row_cnt, META_ROWS_TAG); printf(" <%s>%lu</%s>\n", META_COLS_TAG, col_cnt, META_COLS_TAG); printf(" <%s>\n", LEGEND_TAG); for (j = 0; j < col_cnt; j++) { char *entry = NULL; entry = legend_v[j]; printf(" <%s>%s</%s>\n", LEGEND_ENTRY_TAG, entry, LEGEND_ENTRY_TAG); free(entry); } free(legend_v); printf(" </%s>\n", LEGEND_TAG); printf(" </%s>\n", META_TAG); printf(" <%s>\n", DATA_TAG); for (ti = start + step; ti <= end; ti += step) { printf(" <%s>", DATA_ROW_TAG); printf("<%s>%lld</%s>", COL_TIME_TAG, (long long int)ti, COL_TIME_TAG); for (j = 0; j < col_cnt; j++) { rrd_value_t newval = DNAN; if (enumds == 1) snprintf(vtag, vtag_s, "%s%lu", COL_DATA_TAG, j); else snprintf(vtag, vtag_s, "%s", COL_DATA_TAG); newval = *ptr; if (isnan(newval)) { printf("<%s>NaN</%s>", vtag, vtag); } else { printf("<%s>%0.10e</%s>", vtag, newval, vtag); }; ptr++; } printf("</%s>\n", DATA_ROW_TAG); } free(data); printf(" </%s>\n", DATA_TAG); printf("</%s>\n", ROOT_TAG); setlocale(LC_NUMERIC, old_locale); } free(vtag); } else if (strcmp("graph", argv[1]) == 0) { char **calcpr; #ifdef notused /*XXX*/ const char *imgfile = argv[2]; /* rrd_graph changes argv pointer */ #endif int xsize, ysize; double ymin, ymax; int i; int tostdout = (strcmp(argv[2], "-") == 0); int imginfo = 0; for (i = 2; i < argc; i++) { if (strcmp(argv[i], "--imginfo") == 0 || strcmp(argv[i], "-f") == 0) { imginfo = 1; break; } } if (rrd_graph (argc - 1, &argv[1], &calcpr, &xsize, &ysize, NULL, &ymin, &ymax) != -1) { if (!tostdout && !imginfo) printf("%dx%d\n", xsize, ysize); if (calcpr) { for (i = 0; calcpr[i]; i++) { if (!tostdout) printf("%s\n", calcpr[i]); free(calcpr[i]); } free(calcpr); } } } else if (strcmp("graphv", argv[1]) == 0) { rrd_info_t *grinfo = NULL; /* 1 to distinguish it from the NULL that rrd_graph sends in */ grinfo = rrd_graph_v(argc - 1, &argv[1]); if (grinfo) { rrd_info_print(grinfo); rrd_info_free(grinfo); } } else if (strcmp("tune", argv[1]) == 0) rrd_tune(argc - 1, &argv[1]); else if (strcmp("flushcached", argv[1]) == 0) rrd_flushcached(argc - 1, &argv[1]); else { rrd_set_error("unknown function '%s'", argv[1]); } if (rrd_test_error()) { fprintf(out, "ERROR: %s\n", rrd_get_error()); rrd_clear_error(); return 1; } return (0); }
void GetFlags(int nargs, char **args, char *pre, int *l2size, int *MFLOP, char *cta, int *M, int *N, TYPE *alpha, int *lda, TYPE *beta, char *outnam) { char ctmp; int i, cas=0, iflag=0; int l1mul=75; *cta = 'N'; outnam[0] = '\0'; *l2size = L2SIZE; #if defined(DREAL) *pre = 'd'; #elif defined(SREAL) *pre = 's'; #elif defined(SCPLX) *pre = 'c'; #elif defined(DCPLX) *pre = 'z'; #endif #ifdef ATL_nkflop *MFLOP = (ATL_nkflop) / 1000.0; if (*MFLOP < 1) *MFLOP = 1; #else *MFLOP = 100; #endif *lda = *M = *N = 1000; *beta = *alpha = ATL_rone; #ifdef TCPLX beta[1] = alpha[1] = ATL_rzero; #endif for (i=1; i < nargs; i++) { if (args[i][0] != '-') PrintUsage(args[0]); switch(args[i][1]) { case 'C': /* case */ cas = atoi(args[++i]); break; case 'F': /* mflops */ *MFLOP = atoi(args[++i]); break; case '2': *l2size = atoi(args[++i])*1024; break; case 'f': /* iflag */ iflag = atoi(args[++i]); break; case 'L': *lda = atoi(args[++i]); break; case 'l': /* mflops */ l1mul = atoi(args[++i]); break; case 'A': /* trans */ i++; ctmp = toupper(args[i][0]); if (ctmp == 'n') ctmp = 'N'; else if (ctmp == 't') ctmp = 'T'; else if (ctmp != 'N' && ctmp != 'T') PrintUsage(args[0]); *cta = ctmp; break; case 'm': *M = atoi(args[++i]); break; case 'n': *N = atoi(args[++i]); break; case 'b': *beta = atof(args[++i]); #ifdef TCPLX beta[1] = atof(args[++i]); #endif break; case 'o': strcpy(outnam, args[++i]); break; default: PrintUsage(args[0]); } } #ifdef SYMM_ if (*M > *N) *N = *M; else if (*N > *M) *M = *N; #endif if (*cta == 'N') { ATL_assert(*lda >= Mmax(1,*M)); } else { ATL_assert(*lda >= Mmax(1,*N)); } if (outnam[0] == '\0') { #ifdef SYMM_ if (ATL_MVNoBlock(iflag)) sprintf(outnam, "res/%csymv%c_%d_0", *pre,*cta, cas); else sprintf(outnam, "res/%csymv%c_%d_%d", *pre,*cta, cas, l1mul); #else if (ATL_MVNoBlock(iflag)) sprintf(outnam, "res/%cgemv%c_%d_0", *pre,*cta, cas); else sprintf(outnam, "res/%cgemv%c_%d_%d", *pre,*cta, cas, l1mul); #endif } }
main(int argc, char *argv[]) { ListNode *Curr, *Next; int OverrideType=TYPE_NONE; char *Tempstr=NULL; int result; //HTTPSetFlags(HTTP_NOCOMPRESS); StdIn=STREAMFromFD(0); STREAMSetTimeout(StdIn,0); ParseEnvironmentVariables(); DownloadQueue=ListCreate(); Tempstr=MCopyStr(Tempstr,"Movgrab ",Version,NULL); HTTPSetUserAgent(Tempstr); FormatPreference=CopyStr(FormatPreference,"mp4,flv,webm,m4v,mov,mpg,mpeg,wmv,avi,3gp,reference,mp3,m4a,wma,m3u8,m3u8-stream"); AddOutputFile("", TRUE); ParseCommandLine(argc, argv, DownloadQueue, &OverrideType); CheckSettings(); if (StrLen(Proxy)) { if (! SetGlobalConnectionChain(Proxy)) { printf("ERROR: Failed to set proxy settings to '%s'\n",Proxy); exit(1); } } if (Flags & FLAG_PRINT_USAGE) PrintUsage(); else if (Flags & FLAG_PRINT_VERSION) PrintVersion(); else if (! (Flags & FLAG_STDIN)) { if (ListSize(DownloadQueue)==0) PrintUsage(); } while (1) { if ((Flags & FLAG_STDIN) && (ListSize(DownloadQueue)==0) ) { Tempstr=STREAMReadLine(Tempstr,StdIn); StripTrailingWhitespace(Tempstr); ListAddItem(DownloadQueue,CopyStr(NULL,Tempstr)); } Curr=ListGetNext(DownloadQueue); while (Curr) { if (Flags & FLAG_TEST_SITES) { fprintf(stderr,"Checking %-20s ",Curr->Tag); fflush(NULL); } result=GrabMovie((char *) Curr->Item,OverrideType); Next=ListGetNext(Curr); //must do this after grab movie //incase more items added while grabbing if (Flags & FLAG_TEST_SITES) { if (result) fprintf(stderr," okay\n"); else fprintf(stderr," BROKEN\n"); } ListDeleteNode(Curr); Curr=Next; } if (Flags & FLAG_TEST_SITES) break; if (! (Flags & FLAG_STDIN)) break; } }
int main(int argc, char * argv[]) { int isActivated = 0; #ifndef _WIN32 signal(SIGPIPE, SIG_IGN); #endif #ifdef _WIN32 extern char* optarg; #endif int ch; ProgName = argv[0]; PrintUsage(); while ((ch = getopt(argc,argv, "hd:p:n:N:P:H:T:")) != EOF) { switch(ch) { case 'h': PrintUsage(); return 0; break; case 'd': ConfigIP =optarg; break; case 'p': ConfigPort =optarg; break; case 'n': ConfigName =optarg; break; case 'N': ConfigUName =optarg; break; case 'P': ConfigPWD =optarg; break; case 'H': ConfigDHost =optarg; break; case 'T': ConfigDPort =optarg; break; case '?': return 0; break; default: break; } } isActivated = EasyPusher_Activate(KEY); switch(isActivated) { case EASY_ACTIVATE_INVALID_KEY: printf("KEY is EASY_ACTIVATE_INVALID_KEY!\n"); break; case EASY_ACTIVATE_TIME_ERR: printf("KEY is EASY_ACTIVATE_TIME_ERR!\n"); break; case EASY_ACTIVATE_PROCESS_NAME_LEN_ERR: printf("KEY is EASY_ACTIVATE_PROCESS_NAME_LEN_ERR!\n"); break; case EASY_ACTIVATE_PROCESS_NAME_ERR: printf("KEY is EASY_ACTIVATE_PROCESS_NAME_ERR!\n"); break; case EASY_ACTIVATE_VALIDITY_PERIOD_ERR: printf("KEY is EASY_ACTIVATE_VALIDITY_PERIOD_ERR!\n"); break; case EASY_ACTIVATE_SUCCESS: printf("KEY is EASY_ACTIVATE_SUCCESS!\n"); break; } if(EASY_ACTIVATE_SUCCESS != isActivated) return -1; HI_S32 s32Ret = HI_SUCCESS; HI_S_STREAM_INFO struStreamInfo; HI_NET_DEV_Init(); s32Ret = HI_NET_DEV_Login(&u32Handle, ConfigUName, ConfigPWD, ConfigDHost, atoi(ConfigDPort)); if (s32Ret != HI_SUCCESS) { HI_NET_DEV_DeInit(); return -1; } //HI_NET_DEV_SetEventCallBack(u32Handle, OnEventCallback, &a); HI_NET_DEV_SetStreamCallBack(u32Handle, (HI_ON_STREAM_CALLBACK)OnStreamCallback, NULL); //HI_NET_DEV_SetDataCallBack(u32Handle, OnDataCallback, &a); struStreamInfo.u32Channel = HI_NET_DEV_CHANNEL_1; struStreamInfo.blFlag = HI_TRUE;; struStreamInfo.u32Mode = HI_NET_DEV_STREAM_MODE_TCP; struStreamInfo.u8Type = HI_NET_DEV_STREAM_ALL; s32Ret = HI_NET_DEV_StartStream(u32Handle, &struStreamInfo); if (s32Ret != HI_SUCCESS) { HI_NET_DEV_Logout(u32Handle); u32Handle = 0; return -1; } EASY_MEDIA_INFO_T mediainfo; memset(&mediainfo, 0x00, sizeof(EASY_MEDIA_INFO_T)); mediainfo.u32VideoCodec = EASY_SDK_VIDEO_CODEC_H264; mediainfo.u32VideoFps = 25; mediainfo.u32AudioCodec = EASY_SDK_AUDIO_CODEC_G711A;//SDK output Audio PCMA mediainfo.u32AudioSamplerate = 8000; mediainfo.u32AudioChannel = 1; fPusherHandle = EasyPusher_Create(); EasyPusher_SetEventCallback(fPusherHandle, __EasyPusher_Callback, 0, NULL); EasyPusher_StartStream(fPusherHandle, ConfigIP, atoi(ConfigPort), ConfigName, "admin", "admin", &mediainfo, 1024, false);//1M缓冲区 printf("Press Enter exit...\n"); getchar(); EasyPusher_StopStream(fPusherHandle); EasyPusher_Release(fPusherHandle); fPusherHandle = 0; HI_NET_DEV_StopStream(u32Handle); HI_NET_DEV_Logout(u32Handle); HI_NET_DEV_DeInit(); return 0; }
/** Update Capsule image. @param[in] ImageHandle The image handle. @param[in] SystemTable The system table. @retval EFI_SUCCESS Command completed successfully. @retval EFI_UNSUPPORTED Command usage unsupported. @retval EFI_INVALID_PARAMETER Command usage invalid. @retval EFI_NOT_FOUND The input file can't be found. **/ EFI_STATUS EFIAPI UefiMain ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) { EFI_STATUS Status; RETURN_STATUS RStatus; UINTN FileSize[MAX_CAPSULE_NUM]; VOID *CapsuleBuffer[MAX_CAPSULE_NUM]; EFI_CAPSULE_BLOCK_DESCRIPTOR *BlockDescriptors; EFI_CAPSULE_HEADER *CapsuleHeaderArray[MAX_CAPSULE_NUM + 1]; UINT64 MaxCapsuleSize; EFI_RESET_TYPE ResetType; BOOLEAN NeedReset; BOOLEAN NoReset; CHAR16 *CapsuleName; UINTN CapsuleNum; UINTN Index; Status = GetArg(); if (EFI_ERROR(Status)) { Print(L"Please use UEFI SHELL to run this application!\n", Status); return Status; } if (Argc < 2) { PrintUsage(); return EFI_UNSUPPORTED; } if (StrCmp(Argv[1], L"-D") == 0) { if (Argc != 3) { Print(L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } Status = DumpCapsule(Argv[2]); return Status; } if (StrCmp(Argv[1], L"-G") == 0) { Status = CreateBmpFmp(); return Status; } if (StrCmp(Argv[1], L"-N") == 0) { Status = CreateNestedFmp(); return Status; } if (StrCmp(Argv[1], L"-S") == 0) { Status = DmpCapsuleStatusVariable(); return EFI_SUCCESS; } if (StrCmp(Argv[1], L"-C") == 0) { Status = ClearCapsuleStatusVariable(); return Status; } if (StrCmp(Argv[1], L"-P") == 0) { if (Argc == 2) { DumpFmpData(); } if (Argc >= 3) { if (StrCmp(Argv[2], L"GET") != 0) { Print(L"CapsuleApp: Unrecognized option(%s).\n", Argv[2]); return EFI_UNSUPPORTED; } else { if (Argc != 7) { Print(L"CapsuleApp: Incorrect parameter count.\n"); return EFI_UNSUPPORTED; } EFI_GUID ImageTypeId; UINTN ImageIndex; // // FMP->GetImage() // RStatus = StrToGuid (Argv[3], &ImageTypeId); if (RETURN_ERROR (RStatus) || (Argv[3][GUID_STRING_LENGTH] != L'\0')) { Print (L"Invalid ImageTypeId - %s\n", Argv[3]); return EFI_INVALID_PARAMETER; } ImageIndex = StrDecimalToUintn(Argv[4]); if (StrCmp(Argv[5], L"-O") != 0) { Print(L"CapsuleApp: NO output file name.\n"); return EFI_UNSUPPORTED; } DumpFmpImage(&ImageTypeId, ImageIndex, Argv[6]); } } return EFI_SUCCESS; } if (StrCmp(Argv[1], L"-E") == 0) { DumpEsrtData(); return EFI_SUCCESS; } if (Argv[1][0] == L'-') { Print(L"CapsuleApp: Unrecognized option(%s).\n", Argv[1]); return EFI_UNSUPPORTED; } CapsuleFirstIndex = 1; NoReset = FALSE; if ((Argc > 1) && (StrCmp(Argv[Argc - 1], L"-NR") == 0)) { NoReset = TRUE; CapsuleLastIndex = Argc - 2; } else { CapsuleLastIndex = Argc - 1; } CapsuleNum = CapsuleLastIndex - CapsuleFirstIndex + 1; if (CapsuleFirstIndex > CapsuleLastIndex) { Print(L"CapsuleApp: NO capsule image.\n"); return EFI_UNSUPPORTED; } if (CapsuleNum > MAX_CAPSULE_NUM) { Print(L"CapsuleApp: Too many capsule images.\n"); return EFI_UNSUPPORTED; } ZeroMem(&CapsuleBuffer, sizeof(CapsuleBuffer)); ZeroMem(&FileSize, sizeof(FileSize)); BlockDescriptors = NULL; for (Index = 0; Index < CapsuleNum; Index++) { CapsuleName = Argv[CapsuleFirstIndex + Index]; Status = ReadFileToBuffer(CapsuleName, &FileSize[Index], &CapsuleBuffer[Index]); if (EFI_ERROR(Status)) { Print(L"CapsuleApp: capsule image (%s) is not found.\n", CapsuleName); goto Done; } if (!IsValidCapsuleHeader (CapsuleBuffer[Index], FileSize[Index])) { Print(L"CapsuleApp: Capsule image (%s) is not a valid capsule.\n", CapsuleName); return EFI_INVALID_PARAMETER; } } // // Every capsule use 2 descriptor 1 for data 1 for end // Status = BuildGatherList(CapsuleBuffer, FileSize, CapsuleNum, &BlockDescriptors); if (EFI_ERROR(Status)) { goto Done; } // // Call the runtime service capsule. // NeedReset = FALSE; for (Index = 0; Index < CapsuleNum; Index++) { CapsuleHeaderArray[Index] = (EFI_CAPSULE_HEADER *) CapsuleBuffer[Index]; if ((CapsuleHeaderArray[Index]->Flags & CAPSULE_FLAGS_PERSIST_ACROSS_RESET) != 0) { NeedReset = TRUE; } } CapsuleHeaderArray[CapsuleNum] = NULL; // // Inquire platform capability of UpdateCapsule. // Status = gRT->QueryCapsuleCapabilities (CapsuleHeaderArray, CapsuleNum, &MaxCapsuleSize, &ResetType); if (EFI_ERROR(Status)) { Print (L"CapsuleApp: failed to query capsule capability - %r\n", Status); goto Done; } for (Index = 0; Index < CapsuleNum; Index++) { if (FileSize[Index] > MaxCapsuleSize) { Print (L"CapsuleApp: capsule is too large to update, %ld is allowed\n", MaxCapsuleSize); Status = EFI_UNSUPPORTED; goto Done; } } // // Check whether the input capsule image has the flag of persist across system reset. // if (NeedReset) { Status = gRT->UpdateCapsule(CapsuleHeaderArray,CapsuleNum,(UINTN) BlockDescriptors); if (Status != EFI_SUCCESS) { Print (L"CapsuleApp: failed to update capsule - %r\n", Status); goto Done; } // // For capsule with CAPSULE_FLAGS_PERSIST_ACROSS_RESET + CAPSULE_FLAGS_INITIATE_RESET, // a system reset should have been triggered by gRT->UpdateCapsule() calling above. // // For capsule with CAPSULE_FLAGS_PERSIST_ACROSS_RESET and without CAPSULE_FLAGS_INITIATE_RESET, // check if -NR (no-reset) has been specified or not. // if (!NoReset) { // // For capsule who has reset flag and no -NR (no-reset) has been specified, after calling UpdateCapsule service, // trigger a system reset to process capsule persist across a system reset. // gRT->ResetSystem (ResetType, EFI_SUCCESS, 0, NULL); } } else { // // For capsule who has no reset flag, only call UpdateCapsule Service without a // system reset. The service will process the capsule immediately. // Status = gRT->UpdateCapsule (CapsuleHeaderArray,CapsuleNum,(UINTN) BlockDescriptors); if (Status != EFI_SUCCESS) { Print (L"CapsuleApp: failed to update capsule - %r\n", Status); } } Status = EFI_SUCCESS; Done: for (Index = 0; Index < CapsuleNum; Index++) { if (CapsuleBuffer[Index] != NULL) { FreePool (CapsuleBuffer[Index]); } } CleanGatherList(BlockDescriptors, CapsuleNum); return Status; }
int main(int argc, char **argv) { const char *lexiconDir = getenv("DEVELOPERS_TAGGER_LEXICON"); char *opt = NULL; int i; for (i=1; i<argc && argv[i][0] == '-'; i++) if (argv[i][1] == 'l') { if (++i < argc) lexiconDir = argv[i]; else return PrintUsage(argv[0]); } else if (argv[i][1] == 's') { if (++i < argc) { xSettingsFile = argv[i]; ReadSettings(lexiconDir, xSettingsFile); } else return PrintUsage(argv[0]); } else if (argv[i][1] == 'o') { xOptimize = true; opt = argv[i]+2; } else if (argv[i][1] == 'f') { if (++i < argc) xScope = atof(argv[i]); else return PrintUsage(argv[0]); } else for (int j=1; argv[i][j]; j++) switch(argv[i][j]) { case 'Q': neg(xExtractTesaurus); break; case 'Z': neg(xExtractKeyWords); break; case 'A': neg(xPrintAllWords); break; case 'B': neg(xPrintLemma); break; case 'C': neg(xPrintCorrectTag); break; case 'D': neg(xTestInflections); break; case 'F': neg(xCountFaults); break; case 'G': neg(xGuessRulesForWords); break; case 'H': neg(xSelectUnknownLemmas); break; case 'I': neg(xGenerateInflections); break; case 'J': neg(xPrintWordInfo); break; case 'K': neg(xNoCollocations); break; case 'L': neg(xListMultipleLemmas); break; case 'M': neg(xPrintAllWordTags); break; case 'P': neg(xCompoundRequirePrefix); break; case 'N': neg(xListNewWords); break; case 'S': neg(xPrintSelectedTag); break; case 'U': neg(xPrintUnknownLemmas); break; //jonas case 'a': neg(xAmbiguousNewWords); break; case 'b': neg(xNoTagging); break; // jonas case 'c': neg(xMorfCapital); break; case 'd': neg(xTagTrigramsUsed); break; case 'e': neg(xEvaluateTagging); break; case 'f': std::cerr << "this shouldn't happen" << std::endl; break; case 'g': neg(xGoldenRatio); break; case 'h': neg(xCheckLexicons); break; case 'i': neg(xIgnoreCitation); break; case 'j': xMinLastChars = atoi(argv[i]+j+1); argv[i][j+1]=0; break; case 'k': neg(xMorfCommonSuffix); break; case 'l': std::cerr << "this shouldn't happen" << std::endl; break; case 'm': neg(xTestFeatures); break; case 'n': neg(xMorfNonCapital); break; case 'O': neg(xOptimizeImportantParameters); break; case 'o': std::cerr << "this shouldn't happen" << std::endl; break; case 'p': neg(xCountPunctuationMarksAsWords); break; case 'q': xTaggingEquation = atoi(argv[i]+j+1); argv[i][j+1]=0; break; case 'r': neg(xRandomize); break; case 's': std::cerr << "this shouldn't happen" << std::endl; break; case 't': neg(xTakeTime); break; case 'u': neg(xAnalyzeNewWords); break; case 'v': neg(xVerbose); break; case 'w': neg(xNewWordsMemberTaggingOnly); break; case 'x': neg(xCheckLetters); break; case 'y': xMaxLastChars = atoi(argv[i]+j+1); argv[i][j+1]=0; break; case 'z': neg(xReadSettings); break; // jonas case 'E': neg(xGenerateExtraWordTags); break; case 'W': neg(xWarnAll); break; case 'R': neg(xRepeatTest); break; //jonas case 'X': neg(xSimplifyText); break; default: return PrintUsage(argv[0]); } if (i == argc) { argv[i] = getenv("DEVELOPERS_TAGGER_OPT_TEXT"); if (!argv[i]) return PrintUsage(argv[0]); argc++; } if (!lexiconDir) return PrintUsage(argv[0]); xPrint = xPrintCorrectTag || xPrintSelectedTag || xPrintAllWords; std::cout.precision(5); if (xCheckLetters) { CheckHash(); // doLetterTest(); return 0; } DevelopersTagger tagger; tagger.Load(lexiconDir); if (xExtractTesaurus) { tagger.ExtractTesaurusWordTags("/afs/nada.kth.se/misc/tcs/lexicons/riksdan/tesaurus/tesaurus.txt"); return 0; } if(xReadSettings) { // jonas ReadSettings(tagger.LexiconDir(), "settings"); } if (xExtractKeyWords) { tagger.LoadTesaurus("/afs/nada.kth.se/misc/tcs/granska/suc/lexicons/tesaurus.wtl", "/afs/nada.kth.se/misc/tcs/lexicons/riksdan/tesaurus/tesaurus.txt"); std::ifstream in; tagger.ExtractIndexWords(&argv[i], argc-i); return 0; } Message(MSG_COUNTS, "during loading"); if (xPrintUnknownLemmas) return 0; if (xCheckLexicons) tagger.LexiconCheck(); if (xGenerateExtraWordTags) { tagger.GenerateExtraWordTags(xSelectUnknownLemmas); return 0; } if (xGenerateInflections) { tagger.GenerateInflections(); return 0; } if (xGuessRulesForWords) { tagger.GuessRulesForWords(); return 0; } if (xTestInflections) { tagger.TestInflections(); return 0; } for (; i<argc; i++) { std::ifstream in; in.open(argv[i]); if(!in) { std::cerr << "could not open " << argv[i] << std::endl; continue; } in.seekg (0, std::ios::end); // jonas int inlength = in.tellg(); // jonas in.seekg (0, std::ios::beg); // jonas if(inlength < 1000) inlength = 1000; tagger.SetStream(&in, inlength);//jonas tagger.SetStream(&in, !strcmp(Extension(argv[i]), "html")); if (xOptimize) { tagger.Optimize(opt); if (xPrint) tagger.GetText().Print(); } else { if (strcmp(Extension(argv[i]), "wt")) { /* do ordinary tagging */ xEvaluateTagging = false; xTaggedText = false; xPrintCorrectTag = false; if (!xPrint) xPrint = true; else xPrintAllWords = true; tagger.ReadText(); tagger.TagText(); if (xTakeTime) tagger.PrintTimes(); if (xPrintAllWords || xPrintCorrectTag || xOutputWTL) tagger.GetText().Print(); in.close(); return 0; } else { // extension is .wt xTaggedText = true; tagger.ReadTaggedText(); } Message(MSG_COUNTS, "during text reading"); if (xRepeatTest) RepeatTest(tagger); else { tagger.ResetWords(); if(xNoTagging) tagger.DontTagText(); // use "correct" tags as tagging else tagger.TagText(); if (xTakeTime) tagger.PrintTimes(); if (xListNewWords) { const Tagger *t = &tagger; t->NewWords().PrintObjects(); } else { if (xPrint) tagger.GetText().Print(); if (xEvaluateTagging) tagger.EvaluateTagging(); } } } in.close(); } if (xCheckLexicons) tagger.PrintStatistics(); Message(MSG_COUNTS, "during tagging"); return 0; }
int main(int argc, char** argv) { CCmdLineParser cmdline; ClientCmdLineArgs args; StunClientLogicConfig config; ClientSocketConfig socketconfig; bool fError = false; uint32_t loglevel = LL_ALWAYS; #ifdef DEBUG loglevel = LL_DEBUG; #endif Logging::SetLogLevel(loglevel); cmdline.AddNonOption(&args.strRemoteServer); cmdline.AddNonOption(&args.strRemotePort); cmdline.AddOption("localaddr", required_argument, &args.strLocalAddr); cmdline.AddOption("localport", required_argument, &args.strLocalPort); cmdline.AddOption("mode", required_argument, &args.strMode); cmdline.AddOption("family", required_argument, &args.strFamily); cmdline.AddOption("protocol", required_argument, &args.strProtocol); cmdline.AddOption("verbosity", required_argument, &args.strVerbosity); cmdline.AddOption("help", no_argument, &args.strHelp); if (argc <= 1) { PrintUsage(true); return -1; } cmdline.ParseCommandLine(argc, argv, 1, &fError); if (args.strHelp.length() > 0) { PrintUsage(false); return -2; } if (fError) { PrintUsage(true); return -3; } if (args.strVerbosity.length() > 0) { int level = atoi(args.strVerbosity.c_str()); if (level >= 0) { Logging::SetLogLevel(level); } } if (FAILED(CreateConfigFromCommandLine(args, &config, &socketconfig))) { Logging::LogMsg(LL_ALWAYS, "Can't start client"); PrintUsage(true); return -4; } DumpConfig(config, socketconfig); if (socketconfig.socktype == SOCK_STREAM) { TcpClientLoop(config, socketconfig); } else { UdpClientLoop(config, socketconfig); } return 0; }
//------------------------------------------------------------------------------ // Main Entry Point Definition int main(int argc, char** argv) { struct UtilConfig cfg; memset(&cfg, 0, sizeof(cfg)); // Parse command line options ParseOptions(argc, argv, &cfg); if (cfg.opID == OPT_NONE) { fprintf(stderr, "No operation specified!\n"); PrintUsage(argv[0]); exit(1); } // Create a client instance KineticClientConfig client_config = { .logFile = "stdout", .logLevel = cfg.logLevel, }; cfg.client = KineticClient_Init(&client_config); if (cfg.client == NULL) { fprintf(stderr, "Failed creating a client instance!\n"); return 1; } // Establish a session with the Kinetic Device KineticStatus status = KineticClient_CreateSession(&cfg.config, cfg.client, &cfg.session); if (status != KINETIC_STATUS_SUCCESS) { fprintf(stderr, "Failed connecting to host %s:%d (status: %s)\n", cfg.config.host, cfg.config.port, Kinetic_GetStatusDescription(status)); return 1; } // Establish an admin session with the Kinetic Device cfg.adminConfig.useSsl = true; status = KineticClient_CreateSession(&cfg.adminConfig, cfg.client, &cfg.adminSession); if (status != KINETIC_STATUS_SUCCESS) { fprintf(stderr, "Failed connecting to host %s:%d (status: %s)\n", cfg.config.host, cfg.config.port, Kinetic_GetStatusDescription(status)); return 1; } // Execute the specified operation // ReportConfiguration(cmd, &cfg); status = ExecuteOperation(&cfg); if (status != KINETIC_STATUS_SUCCESS) { fprintf(stderr, "Failed executing operation!\n"); return 1; } return 0; } static void PrintEntry(KineticEntry * entry) { assert(entry); entry->key.array.data[entry->key.bytesUsed] = '\0'; entry->value.array.data[entry->value.bytesUsed] = '\0'; printf( "Kinetic Entry:\n" " key: %s\n" " value: %s\n", (char*)entry->key.array.data, (char*)entry->value.array.data); }
int main(int argc, char* argv[]) { uint8_t addr[20] = {0}; uint8_t* paddr = NULL; uint16_t port = USE_RANDOM_PORT; uint8_t ifname[] = "eth0"; int opt; while ((opt = getopt(argc, argv, "u:t:")) != -1) { switch(opt) { case 'u': UNICAST_DISCOVERY = atoi(optarg); break; case 't': TEST_CASE = atoi(optarg); break; default: PrintUsage(); return -1; } } if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) || (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) ) { PrintUsage(); return -1; } /*Get Ip address on defined interface and initialize coap on it with random port number * this port number will be used as a source port in all coap communications*/ if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr, sizeof(addr)) == ERR_SUCCESS) { OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr); paddr = addr; } /* Initialize OCStack*/ if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK) { OC_LOG(ERROR, TAG, "OCStack init error"); return 0; } InitDiscovery(); // Break from loop with Ctrl+C OC_LOG(INFO, TAG, "Entering occlient main loop..."); signal(SIGINT, handleSigInt); while (!gQuitFlag) { if (OCProcess() != OC_STACK_OK) { OC_LOG(ERROR, TAG, "OCStack process error"); return 0; } sleep(2); } OC_LOG(INFO, TAG, "Exiting occlient main loop..."); if (OCStop() != OC_STACK_OK) { OC_LOG(ERROR, TAG, "OCStack stop error"); } return 0; }
void ConfigureEntry(struct UtilConfig * cfg, const char* key, const char* tag, const char* version, KineticAlgorithm algorithm, bool force, const char* value) { assert(cfg != NULL); // Setup to write some test data cfg->entry = (KineticEntry) { .key = ByteBuffer_CreateAndAppendCString(cfg->keyData, sizeof(cfg->keyData), key), .tag = ByteBuffer_CreateAndAppendCString(cfg->tagData, sizeof(cfg->tagData), tag), .newVersion = ByteBuffer_CreateAndAppendCString(cfg->newVersionData, sizeof(cfg->newVersionData), version), .dbVersion = ByteBuffer_Create(cfg->versionData, sizeof(cfg->versionData), 0), .algorithm = algorithm, .value = ByteBuffer_CreateAndAppendCString(cfg->valueData, sizeof(cfg->valueData), value), .force = force, }; } int ParseOptions( const int argc, char** const argv, struct UtilConfig * cfg) { // Create an ArgP processor to parse arguments struct { OptionID opID; int logLevel; char host[HOST_NAME_MAX]; int port; int tlsPort; int64_t clusterVersion; int64_t identity; char hmacKey[KINETIC_MAX_KEY_LEN]; char logType[64]; char deviceLogName[64]; char key[64]; char version[64]; char tag[64]; KineticAlgorithm algorithm; bool force; char value[1024]; } opts = { .logLevel = 0, .host = "localhost", .port = KINETIC_PORT, .tlsPort = KINETIC_TLS_PORT, .clusterVersion = 0, .identity = 1, .hmacKey = "asdfasdf", .logType = "utilizations", .key = "foo", .tag = "SomeTagValue", .algorithm = KINETIC_ALGORITHM_SHA1, .force = true, .value = "Hello!", }; // Create configuration for long format options struct option long_options[] = { // Help {"help", no_argument, 0, OPT_HELP}, // Commands {"noop", no_argument, 0, OPT_NOOP}, {"put", no_argument, 0, OPT_PUT}, {"get", no_argument, 0, OPT_GET}, {"delete", no_argument, 0, OPT_DELETE}, {"getnext", no_argument, 0, OPT_GETNEXT}, {"getprevious", no_argument, 0, OPT_GETPREVIOUS}, {"getlog", no_argument, 0, OPT_GETLOG}, {"getdevicespecificlog", no_argument, 0, OPT_GETDEVICESPECIFICLOG}, {"seterasepin", no_argument, 0, OPT_SETERASEPIN}, {"instanterase", no_argument, 0, OPT_INSTANTERASE}, {"secureerase", no_argument, 0, OPT_SECUREERASE}, {"setlockpin", no_argument, 0, OPT_SETLOCKPIN}, {"lockdevice", no_argument, 0, OPT_LOCKDEVICE}, {"unlockdevice", no_argument, 0, OPT_UNLOCKDEVICE}, {"setclusterversion", no_argument, 0, OPT_SETCLUSTERVERSION}, {"setacl", no_argument, 0, OPT_SETACL}, {"updatefirmware", no_argument, 0, OPT_UPDATEFIRMWARE}, // Options {"loglevel", required_argument, 0, OPT_LOGLEVEL}, {"host", required_argument, 0, OPT_HOST}, {"port", required_argument, 0, OPT_PORT}, {"tlsport", required_argument, 0, OPT_TLSPORT}, {"identity", required_argument, 0, OPT_IDENTITY}, {"hmackey", required_argument, 0, OPT_HMACKEY}, {"clusterversion", required_argument, 0, OPT_CLUSTERVERSION}, {"file", required_argument, 0, OPT_FILE}, {"newclusterversion", required_argument, 0, OPT_NEWCLUSTERVERSION}, {"pin", required_argument, 0, OPT_PIN}, {"newpin", required_argument, 0, OPT_NEWPIN}, {"logtype", required_argument, 0, OPT_LOGTYPE}, {"devicelogname", required_argument, 0, OPT_DEVICELOGNAME}, {"key", required_argument, 0, OPT_KEY}, {"value", required_argument, 0, OPT_VALUE}, {0, 0, 0, 0}, }; // Parse the options from the command line extern char *optarg; extern int optind; int option, optionIndex = 0; while ((option = getopt_long(argc, argv, "?lhptics:", long_options, &optionIndex)) != -1) { switch (option) { case 0: // If this option, just set the flag if (long_options[optionIndex].flag != 0) {break;} // assert(false); // break; case OPT_LOGLEVEL: opts.logLevel = atoi(optarg); break; case OPT_HOST: strncpy(opts.host, optarg, sizeof(opts.host)); break; case OPT_PORT: opts.port = atoi(optarg); break; case OPT_TLSPORT: opts.tlsPort = atoi(optarg); break; case OPT_IDENTITY: opts.identity = atoi(optarg); break; case OPT_HMACKEY: strncpy(opts.hmacKey, optarg, sizeof(opts.hmacKey)-1); break; case OPT_KEY: strncpy(opts.key, optarg, sizeof(opts.key)-1); break; case OPT_VALUE: strncpy(opts.value, optarg, sizeof(opts.value)-1); break; case OPT_CLUSTERVERSION: opts.clusterVersion = (int64_t)atol(optarg); break; case OPT_NEWCLUSTERVERSION: cfg->newClusterVersion = (int64_t)atol(optarg); break; case OPT_FILE: strncpy(cfg->file, optarg, sizeof(cfg->file)-1); break; case OPT_PIN: strncpy(cfg->pin, optarg, sizeof(cfg->pin)-1); break; case OPT_NEWPIN: strncpy(cfg->newPin, optarg, sizeof(cfg->newPin)-1); break; case OPT_LOGTYPE: strncpy(opts.logType, optarg, sizeof(opts.logType)-1); break; case OPT_DEVICELOGNAME: strncpy(cfg->deviceLogName, optarg, sizeof(cfg->deviceLogName)-1); break; case OPT_NOOP: case OPT_PUT: case OPT_GET: case OPT_DELETE: case OPT_GETNEXT: case OPT_GETPREVIOUS: case OPT_GETLOG: case OPT_GETDEVICESPECIFICLOG: case OPT_SETERASEPIN: case OPT_INSTANTERASE: case OPT_SECUREERASE: case OPT_SETLOCKPIN: case OPT_LOCKDEVICE: case OPT_UNLOCKDEVICE: case OPT_SETCLUSTERVERSION: case OPT_SETACL: case OPT_UPDATEFIRMWARE: if ((int)opts.opID == 0) { opts.opID = option; break; } fprintf(stderr, "Multiple operations specified!\n"); PrintUsage(argv[0]); exit(-1); case OPT_HELP: PrintUsage(argv[0]); exit(0); default: PrintUsage(argv[0]); exit(-1); } } // Configure client cfg->logLevel = opts.logLevel; // Configure session cfg->config = (KineticSessionConfig) { .port = opts.port, .clusterVersion = opts.clusterVersion, .identity = opts.identity, .hmacKey = ByteArray_Create(cfg->hmacKeyData, strlen(opts.hmacKey)), }; memcpy(cfg->hmacKeyData, opts.hmacKey, strlen(opts.hmacKey)); strncpy(cfg->config.host, opts.host, sizeof(cfg->config.host)-1); // Configure admin session cfg->adminConfig = cfg->config; cfg->adminConfig.port = opts.tlsPort; cfg->adminConfig.useSsl = true; // Populate and configure the entry to be used for operations ConfigureEntry(cfg, opts.key, opts.tag, opts.version, opts.algorithm, opts.force, opts.value); cfg->opID = opts.opID; // Parse log type from string if (strcmp("utilizations", opts.logType) == 0) { cfg->logType = KINETIC_DEVICE_INFO_TYPE_UTILIZATIONS; } else if (strcmp("temperatures", opts.logType) == 0) { cfg->logType = KINETIC_DEVICE_INFO_TYPE_TEMPERATURES; } else if (strcmp("capacities", opts.logType) == 0) { cfg->logType = KINETIC_DEVICE_INFO_TYPE_CAPACITIES; } else if (strcmp("configuration", opts.logType) == 0) { cfg->logType = KINETIC_DEVICE_INFO_TYPE_CONFIGURATION; } else if (strcmp("statistics", opts.logType) == 0) { cfg->logType = KINETIC_DEVICE_INFO_TYPE_STATISTICS; } else if (strcmp("messages", opts.logType) == 0) { cfg->logType = KINETIC_DEVICE_INFO_TYPE_MESSAGES; } else if (strcmp("limits", opts.logType) == 0) { cfg->logType = KINETIC_DEVICE_INFO_TYPE_LIMITS; } else { fprintf(stderr, "Invalid log info type: %s\n", opts.logType); exit(1); } return optind; }
int main(int argc, char *argv[]) { int button, buttonCount; #if defined(DEBUG) int daemonize = 0; #else int daemonize = 1; #endif // Setup signal handling before we start signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); signal(SIGQUIT, signal_handler); int c; while( (c = getopt(argc, argv, "nh|help")) != -1) { switch(c){ case 'h': PrintUsage(argc, argv); exit(0); break; case 'n': daemonize = 0; break; default: PrintUsage(argc, argv); exit(0); break; } } syslog(LOG_INFO, "%s daemon starting up", DAEMON_NAME); // Setup syslog logging - see SETLOGMASK(3) #if defined(DEBUG) setlogmask(LOG_UPTO(LOG_DEBUG)); openlog(DAEMON_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER); #else setlogmask(LOG_UPTO(LOG_INFO)); openlog(DAEMON_NAME, LOG_CONS, LOG_USER); #endif /* Our process ID and Session ID */ pid_t pid, sid; if (daemonize) { syslog(LOG_INFO, "starting the daemonizing process"); /* Fork off the parent process */ pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Change the current working directory */ if ((chdir("/")) < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } //**************************************************** // TODO: Insert core of your daemon processing here //**************************************************** while(1){ button = buttonCheck(); if(button == 0){ //Debounce protector while(button == 0){ button = buttonCheck();} if(buttonCount == 0) buttonCount = 1; else buttonCount = 0; if(buttonCount == 1){ //Kill the code system("kill -9 'cat /var/run/studentCode.pid'"); //Print program termination message. system("wall /programKillMsg"); setLED(4); } //Reset the robot fullReset(); if( buttonCount == 0){ //Print message system("wall /resetMessage"); //Run the code again. system("/RUNCODE/runMe"); } usleep(500000); } } syslog(LOG_INFO, "%s daemon exiting", DAEMON_NAME); //**************************************************** // TODO: Free any allocated resources before exiting //**************************************************** exit(0); }
bool ParseProgramOptions(int32 &return_code, int32 argc, char **argv) { // Convert the argument list to a vector of strings for convenience vector<string> options(argv, argv + argc); return_code = 0; for (uint32 i = 1; i < options.size(); i++) { if (options[i] == "-c" || options[i] == "--check") { if (CheckFiles() == true) { return_code = 0; } else { return_code = 1; } return false; } else if (options[i] == "-d" || options[i] == "--debug") { if ((i + 1) >= options.size()) { cerr << "Option " << options[i] << " requires an argument." << endl; PrintUsage(); return_code = 1; return false; } if (EnableDebugging(options[i + 1]) == false) { return_code = 1; return false; } i++; } else if (options[i] == "--disable-audio") { hoa_audio::AUDIO_ENABLE = false; } else if (options[i] == "-h" || options[i] == "--help") { PrintUsage(); return_code = 0; return false; } else if (options[i] == "-i" || options[i] == "--info") { if (PrintSystemInformation() == true) { return_code = 0; } else { return_code = 1; } return false; } else if (options[i] == "-r" || options[i] == "--reset") { if (ResetSettings() == true) { return_code = 0; } else { return_code = 1; } return_code = 0; return false; } else { cerr << "Unrecognized option: " << options[i] << endl; PrintUsage(); return_code = 1; return false; } } return true; } // bool ParseProgramOptions(int32_t &return_code, int32_t argc, char **argv)