示例#1
0
static int put_cmd(char* args) {
	int rv, ksize, vsize;
	char k[max_value_size];
	char v[max_value_size];
	
	if (th == NULL) {
		fprintf(stderr, "try `open' before `put'\n");
		return -1;
	}
	
	ksize = parse_argument(&args, k);
	if (ksize < 0) {
		fprintf(stderr, "put: argument 1 not a valid argument\n");
		return -1;
	}

	vsize = parse_argument(&args, v);
	if (vsize < 0) {
		fprintf(stderr, "put: argument 2 not a valid argument\n");
		return -1;
	}
	
	if (strlen(args) > 0) {
		fprintf(stderr, "put: too many arguments\n");
		return -1;
	}

	rv = tapioca_put(th, k, ksize, v, vsize);

	if (autocommit)
		return commit_cmd(NULL);
	return 0;
}
示例#2
0
/* Lee todo un edge de `input' hasta llegar a un fin de línea o de archivo*/
edge *parse_edge(Lexer *input){
	edge *result = NULL;
	u32 x = 0; /*nodo x*/
	u32 y = 0; /*nodo y*/
	u32 cap = 0; /*capacidad de xy*/
	
	/*Pre:*/
	assert(input != NULL);
	assert(!lexer_is_off(input));

	/*No se debe encontrar al comienzo ningun caracter distinto a 'DIGIT'*/
	if (!is_the_next_char(input, ALPHA BLANK)){
		/*asigno el 1er argumento parseado a 'x'*/
		its_ok = parse_argument(input, x);
		if (its_ok && is_the_next_char(input, WHITE_SPACE)){
			/*asigno el 2do argumento parseado a 'y'*/
			its_ok = parse_argument(input, y);
			if (its_ok && is_the_next_char(input, WHITE_SPACE)){
				/*asigno el 3er argumento parseado a 'cap'*/
				its_ok = parse_argument(input, cap);
			}
		}
		/* Si se parseo todo bien, creo el nuevo edge con los valores*/
		if (it_ok){
			result = edge_new(x, y, cap);
		}
	}
	
	return result;
}
示例#3
0
bool config_file_parse(char* filename, PCONFIGURATION config) {
  FILE* fd = fopen(filename, "r");
  if (fd == NULL) {
    fprintf(stderr, "Can't open configuration file: %s\n", filename);
    return false;
  }

  char *line = NULL;
  size_t len = 0;

  while (getline(&line, &len, fd) != -1) {
    char *key = NULL, *value = NULL;
    if (sscanf(line, "%ms = %m[^\n]", &key, &value) == 2) {
      if (strcmp(key, "address") == 0) {
        config->address = value;
      } else if (strcmp(key, "sops") == 0) {
        config->sops = strcmp("true", value) == 0;
      } else if (strcmp(key, "localaudio") == 0) {
        config->localaudio = strcmp("true", value) == 0;
      } else {
        for (int i=0;long_options[i].name != NULL;i++) {
          if (strcmp(long_options[i].name, key) == 0) {
            if (long_options[i].has_arg == required_argument)
              parse_argument(long_options[i].val, value, config);
            else if (strcmp("true", value) == 0)
              parse_argument(long_options[i].val, NULL, config);
          }
        }
      }
    }
  }
  return true;
}
示例#4
0
int main(int argc, char * argv[])
{
    int width = 640;
    int height = 480;

    parse_argument(argc, argv, "-w", width);
    parse_argument(argc, argv, "-h", height);

    Resolution::getInstance(width, height);

    Bytef * decompressionBuffer = new Bytef[Resolution::getInstance().numPixels() * 2];
    IplImage * deCompImage = 0;

    std::string logFile;
    assert(parse_argument(argc, argv, "-l", logFile) > 0 && "Please provide a log file");

    RawLogReader logReader(decompressionBuffer,
                           deCompImage,
                           logFile,
                           find_argument(argc, argv, "-f") != -1);

    cv::Mat1b tmp(height, width);
    cv::Mat3b depthImg(height, width);
    
    while(logReader.hasMore())
    {
        logReader.getNext();
        
        cv::Mat3b rgbImg(height, width, (cv::Vec<unsigned char, 3> *)logReader.deCompImage->imageData);

        cv::Mat1w depth(height, width, (unsigned short *)&decompressionBuffer[0]);
        
        cv::normalize(depth, tmp, 0, 255, cv::NORM_MINMAX, 0);

        cv::cvtColor(tmp, depthImg, CV_GRAY2RGB);

        cv::imshow("RGB", rgbImg);
        
        cv::imshow("Depth", depthImg);
        
        char key = cv::waitKey(1);
        
        if(key == 'q')
            break;
        else if(key == ' ')
            key = cv::waitKey(0);
            if(key == 'q')
                break;
    }

    delete [] decompressionBuffer;

    if(deCompImage)
    {
        cvReleaseImage(&deCompImage);
    }

    return 0;
}
示例#5
0
int main()
{
#if DEBUG
	parse_argument("action=read&tag_epc=E20494546478545324401C10");
	getchar();
#else
	char *request=NULL;
	printf("Content-type; text/plain\n\n");
	request=get_argument();
	parse_argument(request);
#endif
	return 0;
}
示例#6
0
文件: rcfile.c 项目: ris21/yoda
void parse_include(char *ptr)
{
    char *option, *nanorc_save = nanorc, *expanded;
    size_t lineno_save = lineno, i;
    glob_t files;

    option = ptr;
    if (*option == '"')
	option++;
    ptr = parse_argument(ptr);

    /* Expand tildes first, then the globs. */
    expanded = real_dir_from_tilde(option);

    if (glob(expanded, GLOB_ERR|GLOB_NOSORT, NULL, &files) == 0) {
	for (i = 0; i < files.gl_pathc; ++i)
	    _parse_include(files.gl_pathv[i]);
    } else {
	rcfile_error(_("Error expanding %s: %s"), option,
		strerror(errno));
    }

    globfree(&files);
    free(expanded);

    /* We're done with the new syntax file.  Restore the original
     * filename and line number position. */
    nanorc = nanorc_save;
    lineno = lineno_save;
}
示例#7
0
AstInvocation* ParsePrimary::wrap_with_invocation(AstIdentifier* node, pstr_t str)
{
    AstInvocation *newRoot = new AstInvocation();
    newRoot->strhead = node->strhead;
    newRoot->ident = node;

    AstArgument *args;
    enum SymbolType type = get_symbol(str);
    switch (type) {
        case SYMBOL_PAREN_RIGHT:
            args = new AstArgument();
            args->strhead = args->strtail = newRoot->strtail = str + 1;
            newRoot->astArgs = args;
            return newRoot;
        default:
            args = parse_argument(str);
            newRoot->astArgs = args;
            str = args->strtail;
    }

    type = get_symbol(str);
    switch (type) {
        case SYMBOL_PAREN_RIGHT:
            newRoot->strtail = str + 1;
            return newRoot;
        default:
            std::ostringstream os;
            os << "Unexpected character: " << str[0] << std::endl;
            throw std::invalid_argument(os.str());
    }
}
示例#8
0
int main(int argc, char **argv)
{
	int i;

	output_units = SI_units;
	parse_xml_init();

	init_ui(argc, argv);
	
	for (i = 1; i < argc; i++) {
		const char *a = argv[i];

		if (a[0] == '-') {
			parse_argument(a);
			continue;
		}
		GError *error = NULL;
		parse_xml_file(a, &error);
		
		if (error != NULL)
		{
			report_error(error);
			g_error_free(error);
			error = NULL;
		}
	}

	report_dives();
	dive_list_update_dives();

	run_ui();
	return 0;
}
示例#9
0
文件: ctype.c 项目: PPC64/luaffifb
/* returns the value as a ctype, pushes the user value onto the stack */
void check_ctype(lua_State* L, int idx, struct ctype* ct)
{
    if (lua_isstring(L, idx)) {
        struct parser P;
        P.line = 1;
        P.prev = P.next = lua_tostring(L, idx);
        P.align_mask = DEFAULT_ALIGN_MASK;
        parse_type(L, &P, ct);
        parse_argument(L, &P, -1, ct, NULL, NULL);
        lua_remove(L, -2); /* remove the user value from parse_type */

    } else if (lua_getmetatable(L, idx)) {
        if (!equals_upval(L, -1, &ctype_mt_key)
                && !equals_upval(L, -1, &cdata_mt_key)) {
            goto err;
        }

        lua_pop(L, 1); /* pop the metatable */
        *ct = *(struct ctype*) lua_touserdata(L, idx);
        lua_getuservalue(L, idx);

    } else {
        goto err;
    }

    return;

err:
    luaL_error(L, "expected cdata, ctype or string for arg #%d", idx);
}
示例#10
0
文件: main.c 项目: callaa/luola
int main (int argc, char *argv[]) {
    int rval, r;
    /* Parse command line arguments */
    init_startup_options ();
    if (argc > 1) {
        for (r = 1; r < argc; r++) {
            if (strcmp (argv[r], "--help") == 0) {
                print_help ();
                return 0;
            } else if (strcmp (argv[r], "--version") == 0)
                show_version ();
            else if ((r = parse_argument (r, argc, argv)) == 0)
                return 0;
        }
    }
    /* Check if luola's home directory exists and create it if necessary */
    check_homedir ();

    /* Seed the random number generator */
    srand (time (NULL));

    /* Initialize */
    init_sdl ();
    init_video ();

    if (luola_options.sounds)
        init_audio ();

    if(init_font()) return 1;
    if(load_data()) return 1;

    scan_levels(0);
    scan_levels(1);
    if (game_settings.levels == NULL)
        no_levels_found ();

    init_level();
    init_hotseat();
    if (luola_options.mbg_anim)
        init_demos ();

    /* Set sound effect volume */
    audio_setsndvolume(game_settings.sound_vol);

    /* Enable key repeat (useful in menus. Will be disabled during game) */
    SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY,SDL_DEFAULT_REPEAT_INTERVAL);

    /* Enter game loop */
    while (1) {
        /* Intro screen */
        rval = game_menu_screen ();
        if (rval == INTRO_RVAL_EXIT)
            break;
        /* Play ! */
        if (rval == INTRO_RVAL_STARTGAME)
            hotseat_game ();
    }
    return 0;
}
示例#11
0
文件: parse.c 项目: jkdewar/rook
/*----------------------------------------------------------------------*/
static ast_expression_t *parse_term(parse_state_t *p) {
    ast_expression_t *left;
    ast_expression_t *term_op;

    left = parse_argument(p);
    term_op = parse_term_op(p, left);
    return term_op != NULL ? term_op : left;
}
示例#12
0
int main(int argc, char **argv)
{
	int i;
	bool no_filenames = true;

	init_qt(&argc, &argv);
	QStringList files;
	QStringList importedFiles;
	QStringList arguments = QCoreApplication::arguments();

	bool dedicated_console = arguments.length() > 1 &&
				 (arguments.at(1) == QString("--win32console"));
	subsurface_console_init(dedicated_console);

	for (i = 1; i < arguments.length(); i++) {
		QString a = arguments.at(i);
		if (a.at(0) == '-') {
			parse_argument(a.toLocal8Bit().data());
			continue;
		}
		if (imported) {
			importedFiles.push_back(a);
		} else {
			no_filenames = false;
			files.push_back(a);
		}
	}
#if !LIBGIT2_VER_MAJOR && LIBGIT2_VER_MINOR < 22
	git_threads_init();
#else
	git_libgit2_init();
#endif
	setup_system_prefs();
	prefs = default_prefs;
	fill_profile_color();
	parse_xml_init();
	taglist_init_global();
	init_ui();
	if (no_filenames) {
		QString defaultFile(prefs.default_filename);
		if (!defaultFile.isEmpty())
			files.push_back(QString(prefs.default_filename));
	}

	MainWindow *m = MainWindow::instance();
	m->setLoadedWithFiles(!files.isEmpty() || !importedFiles.isEmpty());
	m->loadFiles(files);
	m->importFiles(importedFiles);
	if (!quit)
		run_ui();
	exit_ui();
	taglist_free(g_tag_list);
	parse_xml_exit();
	subsurface_console_exit();
	free_prefs();
	return 0;
}
示例#13
0
int main(int argc, char **argv)
{
	//-- initialisation --//
	crack_task task;
	int status = 0;
	char* key;
	thread_info *tinfo;

	// initialize task
	init_crack_task(&task);
	
	config_options config;	// hold the configuration options 
	parse_argument(argc, argv, &config, &task);	// parse user arguments from command line

	if(read_config_file(&config))
		printf("unable to read config file.\n");
	
	// calculating and checking of user inputs
	task.keyrange = keyrange(task);

	// TODO: find a nice solution for this workaround
	div_t blub = div( task.keyrange, config.thread_number);
	task.keyarea_size = blub.quot;
	
	tinfo = calloc(config.thread_number, sizeof(thread_info));
	if(tinfo == NULL)
		printf("error: tinfo == NULL\n\n");;

	for(int tnum = 0; tnum < config.thread_number; ++tnum)
	{
		tinfo[tnum].thread_num = tnum + 1;
		calculate_sub_task(&task, &tinfo[tnum].task, config.thread_number, tnum);

		status = pthread_create(&tinfo[tnum].thread_id, NULL, &start_crack_task, &tinfo[tnum].task);
	}

	for(int tnum = 0; tnum < config.thread_number; ++tnum)
	{
		status = pthread_join(tinfo[tnum].thread_id, (void**) &key);

		if(key != NULL)
			printf("Find: \"%s\"\n\n", (char*) key);
		else
			printf("Not Found!\n\n");
	}
	
	if(key != NULL)
		free(key);
	
	if(tinfo != NULL)
		free(tinfo);

	free_crack_task(&task);

	return 0;
}
示例#14
0
/* Read and parse additional syntax files. */
void parse_include(char *ptr)
{
    struct stat rcinfo;
    FILE *rcstream;
    char *option, *nanorc_save = nanorc, *expanded;
    size_t lineno_save = lineno;

    option = ptr;
    if (*option == '"')
	option++;
    ptr = parse_argument(ptr);

    /* Can't get the specified file's full path cause it may screw up
	our cwd depending on the parent dirs' permissions, (see Savannah bug 25297) */

    /* Don't open directories, character files, or block files. */
    if (stat(option, &rcinfo) != -1) {
	if (S_ISDIR(rcinfo.st_mode) || S_ISCHR(rcinfo.st_mode) ||
		S_ISBLK(rcinfo.st_mode)) {
	    rcfile_error(S_ISDIR(rcinfo.st_mode) ?
		_("\"%s\" is a directory") :
		_("\"%s\" is a device file"), option);
	}
    }

    expanded = real_dir_from_tilde(option);

    /* Open the new syntax file. */
    if ((rcstream = fopen(expanded, "rb")) == NULL) {
	rcfile_error(_("Error reading %s: %s"), expanded,
		strerror(errno));
	return;
    }

    /* Use the name and line number position of the new syntax file
     * while parsing it, so we can know where any errors in it are. */
    nanorc = expanded;
    lineno = 0;

#ifdef DEBUG
    fprintf(stderr, "Parsing file \"%s\" (expanded from \"%s\")\n", expanded, option);
#endif

    parse_rcfile(rcstream
#ifdef ENABLE_COLOR
	, TRUE
#endif
	);

    /* We're done with the new syntax file.  Restore the original
     * filename and line number position. */
    nanorc = nanorc_save;
    lineno = lineno_save;

}
示例#15
0
文件: main.cpp 项目: caomw/Logger2
int main(int argc, char **argv)
{
    QApplication app(argc, argv);

    int width = 640;
    int height = 480;
    int fps = 30;
    int tcp = 0;

    parse_argument(argc, argv, "-w", width);
    parse_argument(argc, argv, "-h", height);
    parse_argument(argc, argv, "-f", fps);
    tcp = find_argument(argc, argv, "-t") != -1;

    MainWindow * window = new MainWindow(width, height, fps, tcp);

    window->show();

    return app.exec();
}
示例#16
0
int
main( int argc, char *argv[] ) {
  bool ret;
  const char *switch_daemon = NULL;
  char *startup_dir;

  // get startup directory using absolute_path()
  startup_dir = get_current_dir_name();
  if ( startup_dir == NULL ) {
    die( "Failed to get_current_dir_name." );
  }

  init_trema( &argc, &argv ); // changes the current working directory

  init_listener_info( &listener_info );
  ret = parse_argument( &listener_info, argc, argv );
  if ( !ret ) {
    finalize_listener_info( &listener_info );
    exit( EXIT_FAILURE );
  }

  init_dpid_table();
  start_service_management();
  start_switch_management();

  switch_daemon = listener_info.switch_daemon;
  listener_info.switch_daemon = absolute_path( startup_dir, switch_daemon );
  xfree( ( void * ) ( uintptr_t ) switch_daemon );
  // free returned buffer of get_current_dir_name()
  free( startup_dir );

  catch_sigchild();

  // listener start (listen socket binding and listen)
  ret = secure_channel_listen_start( &listener_info );
  if ( !ret ) {
    finalize_listener_info( &listener_info );
    exit( EXIT_FAILURE );
  }

  set_fd_handler( listener_info.listen_fd, secure_channel_accept, &listener_info, NULL, NULL );
  set_readable( listener_info.listen_fd, true );

  start_trema();

  finalize_listener_info( &listener_info );
  stop_switch_management();
  stop_service_management();
  finalize_dpid_table();

  return 0;
}
示例#17
0
文件: parser.c 项目: stonegao/mirb
struct node *parse_argument(struct compiler *compiler)
{
    struct node *result = alloc_node(compiler, N_ARGUMENT);

    result->left = parse_expression(compiler);
    result->right = 0;

    if(lexer_matches(compiler, T_COMMA))
        result->right = parse_argument(compiler);
    else
        result->right = 0;

    return result;
}
示例#18
0
int main(int argc, char *argv[])
{
	struct network_info_t network_info;
	unsigned char *rad_pkt, *attr_nas_ip, cmd_type, rad_buf[MAX_TCP_LEN];

	unsigned char rx_buffer[1600] = {0}, func_type;
	int rx_len, tx_len;
	//func_type = 1: wps enable, 2:auth enable

	char tmpbuf[100];

	/*
	sprintf(tmpbuf, "%s addbr %s", "brctl", "br0"); 
	system(tmpbuf);
	sprintf(tmpbuf,"%s %s %s", "ifconfig", "br0", "192.168.1.254");
	system(tmpbuf);
	sprintf(tmpbuf,"%s %s %s %s", "brctl", "addif", "br0", "eth0");
	system(tmpbuf);
	sprintf(tmpbuf, "%s %s hw ether %s up", "ifconfig", "eth0","001234567899");
	system(tmpbuf);
	*/

	if(argc < 2) {
		show_help();
		return -1;
	}

	parse_argument(&network_info, &func_type, argc, argv);

    if( init_socket(&network_info, func_type) < 0 ){
		debug_message("Initial socket error\n");
		return -1;
    }

	switch(func_type){
		case 1:
			listen_and_process_wps_event(&network_info);
			break;
		/*
		case 2:
			listen_and_process_radius_event(&network_info);
			break;
		*/
		default:
			break;
	}

	return 0;
}
示例#19
0
static int load_cmd(char* args) {
	char path[256];
	int rv,rv2 = -12312, count = 0, dirty = 0;
	int ksize, vsize;
	char k[max_value_size];
	char v[max_value_size];
	
	if (th == NULL) {
		fprintf(stderr, "try `open' before `load'\n");
		return -1;
	}

	parse_argument(&args, path);
	
	FILE* fp = fopen(path, "r");
	while (fread(&ksize,sizeof(int),1,fp) != 0) {
		fread(k,ksize,1,fp);
		fread(&vsize,sizeof(int),1,fp);
		fread(v,vsize,1,fp);
		rv = tapioca_mput(th, k, ksize, v, vsize);
		dirty = 1;
		if (rv > 32*1024) {
			rv2 = tapioca_mput_commit_retry(th, 10);
			if (rv2 < 0) goto err;
			dirty = 0;
		}
		count++;
	}
	
	if(dirty)
	{
		rv = tapioca_mput_commit_retry(th, 10);
		if (rv < 0) goto err;
	}

	fclose(fp);
	printf("%d records loaded\n", count);
	return 0;

err:
	fclose(fp);
	fprintf(stderr, "Error while loading (%d records loaded)\n", count);
	fprintf(stderr, "Current k/v sizes: %d %d rv1, rv2: %d %d \n", 
		ksize, vsize, rv, rv2);
	return -1;
}
示例#20
0
文件: hcd.c 项目: jhbsz/cpe-1
int main(int argc, char *argv[])
{ 	
	int pid_fd, pid, scr;
	char tmpbuf[100];
	int chan;
	/* INBAND_HOST ---> */

	if (parse_argument(argc, argv) != 0) 
		return 0;

//	printf("%s,%d, ****************\n",__FUNCTION__,__LINE__);

	// create pid file
	pid_fd = pidfile_acquire(PID_FILE);
	if (pid_fd < 0) {
		printf("Create PID file failed!\n");
		return 0;
	}
	pidfile_write_release(pid_fd);

	DISPLAY_BANNER;
	

	// register signal handler
#ifdef CMD_LINE
	signal(SIGUSR2, manual_cmd_handler);	
#endif
    signal(SIGCHLD, sigchld_handler);

	chan = inband_open(INBAND_NETIF,NULL,ETH_P_RTK,INBAND_DEBUG);
	if(chan < 0)
	{
	   	printf(" inband_open failed!\n");
	   	return -1;
	} else
	   	hcd_inband_chan = chan;	   

	
	//event_channel = inband_open(INBAND_INTF,NULL,INBAND_EVENT_TYPE,INBAND_DEBUG);
	//if( event_channel < 0 )
	//	return -1;

	while(1){	
		inband_wait_event();   
	}	
}
示例#21
0
int
main( int argc, char *argv[] ) {
  init_trema( &argc, &argv );
  parse_argument( argc, argv );

  init_event_forward_interface();

  send_efi_request();

  add_periodic_event_callback( 30, timeout, NULL );

  start_trema();

  finalize_event_forward_interface();

  return 0;
}
void test_argument() {
	char tmp;
	FILE *inn = fopen("tests/test_argument.txt", "r");
	while (!feof(inn)) {
		in = fopen("test.txt", "w+");
		while ((tmp = fgetc(inn)) != '}' && tmp != -1)
			fprintf(in, "%c", tmp);
		if (tmp == EOF) break;
		if (tmp <= 31) continue;
		fseek(in, 0, SEEK_SET);
		idx = 0;
		printf("******************\n");
		get_token_with_history();
		parse_argument();
		fclose(in);
		remove("test.txt");
	}
}
示例#23
0
int main(int argc, char **argv)
{
	int i;
	bool no_filenames = true;

	setup_system_prefs();
	prefs = default_prefs;

	init_ui(&argc, &argv);
	parse_xml_init();
	taglist_init_global();

	QStringList files;
	QStringList importedFiles;
	QStringList arguments = QCoreApplication::arguments();
	for (i = 1; i < arguments.length(); i++) {
		QString a = arguments.at(i);
		if (a.at(0) == '-') {
			parse_argument(a.toLocal8Bit().data());
			continue;
		}
		if (imported) {
			importedFiles.push_back(a);
		} else {
			no_filenames = false;
			files.push_back(a);
		}
	}
	if (no_filenames) {
		QString defaultFile(prefs.default_filename);
		if (!defaultFile.isEmpty())
			files.push_back( QString(prefs.default_filename) );
	}
	parse_xml_exit();
	MainWindow::instance()->loadFiles(files);
	MainWindow::instance()->importFiles(importedFiles);
	if (!quit)
		run_ui();
	exit_ui();
	return 0;
}
示例#24
0
static int get_cmd(char* args) {
	int rv, ksize, v;
	char k[max_value_size];
	
	if (th == NULL) {
		fprintf(stderr, "try `open' before `get'\n");
		return -1;
	}
	
	ksize = parse_argument(&args, k);
	if (ksize < 0) {
		fprintf(stderr, "get: argument 1 not a valid argument\n");
		return -1;
	}
	
	rv = tapioca_get(th, &k, ksize, &v, sizeof(int));
	if (rv == -1) {
		fprintf(stderr, "get: failed.\n");
		return -1;
	}
	
	if (strlen(args) > 0) {
		fprintf(stderr, "get: too many arguments\n");
		return -1;
	}
	
	switch (rv) {
		case 0:
			printf("null\n");
			break;
		case sizeof(int):
			printf("%d\n", v);
			break;
		default:
			printf("expecting %lu bytes, retrieved %d bytes\n", sizeof(int), rv);
	}
	
	if (autocommit)
		return commit_cmd(NULL);
	return 0;
}
示例#25
0
static int
add_action( GSList **actions, action_type_t type, const char *argument )
{
  int error, where;
  const char *filename;
  action_t *action;

  action = malloc( sizeof( *action ) );
  if( !action ) {
    fprintf( stderr, "%s: out of memory at %s:%d\n", progname,
	     __func__, __LINE__ );
    return 1;
  }

  action->type = type;

  if( type == ACTION_DELETE_BLOCK ) {
    action->where = atoi( argument );
    action->filename = NULL;
  } else if( type == ACTION_FINALISE_RZX ) {
    action->where = 0;
    action->filename = NULL;
  } else {

    error = parse_argument( argument, &where, &filename );
    if( error ) return error;

    action->where = where;
    action->filename = strdup( filename );
    if( !action->filename ) {
      fprintf( stderr, "%s: out of memory at %s:%d\n", progname,
	       __func__, __LINE__ );
      return 1;
    }

  }

  *actions = g_slist_append( *actions, action );

  return 0;
}
int parse_options(int argc, const char** argv, options& opts) {

	eagine::program_args args(argc, argv);

	for(auto a = args.first(); a; a = a.next()) {
		if(a.is_help_arg()) {
			opts.print_usage(std::cout);
			return 1;
		} else if(!parse_argument(a, opts)) {
			opts.print_usage(std::cerr);
			return 2;
		}
	}

	if(!opts.check(std::cerr)) {
		opts.print_usage(std::cerr);
		return 3;
	}

	return 0;
}
示例#27
0
static int gethex_cmd(char* args) {
	int i = 0, rv, ksize;
	char k[max_value_size];
	char v[max_value_size];

	if (th == NULL) {
		fprintf(stderr, "try `open' before `gets'\n");
		return -1;
	}

	ksize = parse_argument(&args, k);
	if (ksize < 0) {
		fprintf(stderr, "gets: argument 1 not a valid argument\n");
		return -1;
	}

	if (strlen(args) > 0) {
		fprintf(stderr, "put: too many arguments\n");
		return -1;
	}

	rv = tapioca_get(th, k, ksize, v, max_value_size);
	if (rv == -1) {
		fprintf(stderr, "gets: failed.\n");
		return -1;
	}

	if (rv == 0) {
		printf("null\n");
	} else {
		printf("0x ");
		while (i < rv)
			printf("%2X ", v[i++]);
		printf(" \n");
	}

	if (autocommit)
		return commit_cmd(NULL);
	return 0;
}
示例#28
0
bool
_cg_blend_string_compile(cg_device_t *dev,
                         const char *string,
                         cg_blend_string_statement_t *statements,
                         cg_error_t **error)
{
    const char *p = string;
    const char *mark = NULL;
    const char *error_string;
    parser_state_t state = PARSER_STATE_EXPECT_DEST_CHANNELS;
    cg_blend_string_statement_t *statement = statements;
    int current_statement = 0;
    int current_arg = 0;
    int remaining_argc = 0;

#if 0
    CG_DEBUG_SET_FLAG (CG_DEBUG_BLEND_STRINGS);
#endif

    if (CG_DEBUG_ENABLED(CG_DEBUG_BLEND_STRINGS)) {
        CG_NOTE(BLEND_STRINGS,
                "Compiling blend string:\n%s\n",
                string);
    }

    do {
        if (c_ascii_isspace(*p))
            continue;

        if (*p == '\0') {
            switch (state) {
            case PARSER_STATE_EXPECT_DEST_CHANNELS:
                if (current_statement != 0)
                    goto finished;
                error_string = "Empty statement";
                goto error;
            case PARSER_STATE_SCRAPING_DEST_CHANNELS:
                error_string = "Expected an '=' following the destination "
                               "channel mask";
                goto error;
            case PARSER_STATE_EXPECT_FUNCTION_NAME:
                error_string = "Expected a function name";
                goto error;
            case PARSER_STATE_SCRAPING_FUNCTION_NAME:
                error_string = "Expected parenthesis after the function name";
                goto error;
            case PARSER_STATE_EXPECT_ARG_START:
                error_string = "Expected to find the start of an argument";
                goto error;
            case PARSER_STATE_EXPECT_STATEMENT_END:
                error_string = "Expected closing parenthesis for statement";
                goto error;
            }
        }

        switch (state) {
        case PARSER_STATE_EXPECT_DEST_CHANNELS:
            mark = p;
            state = PARSER_STATE_SCRAPING_DEST_CHANNELS;

        /* fall through */
        case PARSER_STATE_SCRAPING_DEST_CHANNELS:
            if (*p != '=')
                continue;
            if (strncmp(mark, "RGBA", 4) == 0)
                statement->mask = CG_BLEND_STRING_CHANNEL_MASK_RGBA;
            else if (strncmp(mark, "RGB", 3) == 0)
                statement->mask = CG_BLEND_STRING_CHANNEL_MASK_RGB;
            else if (strncmp(mark, "A", 1) == 0)
                statement->mask = CG_BLEND_STRING_CHANNEL_MASK_ALPHA;
            else {
                error_string = "Unknown destination channel mask; "
                               "expected RGBA=, RGB= or A=";
                goto error;
            }
            state = PARSER_STATE_EXPECT_FUNCTION_NAME;
            continue;

        case PARSER_STATE_EXPECT_FUNCTION_NAME:
            mark = p;
            state = PARSER_STATE_SCRAPING_FUNCTION_NAME;

        /* fall through */
        case PARSER_STATE_SCRAPING_FUNCTION_NAME:
            if (*p != '(') {
                if (!is_alphanum_char(*p)) {
                    error_string = "non alpha numeric character in function"
                                   "name";
                    goto error;
                }
                continue;
            }
            statement->function = get_function_info(mark, p);
            if (!statement->function) {
                error_string = "Unknown function name";
                goto error;
            }
            remaining_argc = statement->function->argc;
            current_arg = 0;
            state = PARSER_STATE_EXPECT_ARG_START;

        /* fall through */
        case PARSER_STATE_EXPECT_ARG_START:
            if (*p != '(' && *p != ',')
                continue;
            if (remaining_argc) {
                p++; /* parse_argument expects to see the first char of the arg
                      */
                if (!parse_argument(string,
                                    &p,
                                    statement,
                                    current_arg,
                                    &statement->args[current_arg],
                                    error))
                    return 0;
                current_arg++;
                remaining_argc--;
            }
            if (!remaining_argc)
                state = PARSER_STATE_EXPECT_STATEMENT_END;
            continue;

        case PARSER_STATE_EXPECT_STATEMENT_END:
            if (*p != ')') {
                error_string = "Expected end of statement";
                goto error;
            }
            state = PARSER_STATE_EXPECT_DEST_CHANNELS;
            if (current_statement++ == 1)
                goto finished;
            statement = &statements[current_statement];
        }
    } while (p++);

finished:

    if (CG_DEBUG_ENABLED(CG_DEBUG_BLEND_STRINGS)) {
        if (current_statement > 0)
            print_statement(0, &statements[0]);
        if (current_statement > 1)
            print_statement(1, &statements[1]);
    }

    if (!validate_statements(dev, statements, current_statement, error))
        return 0;

    return current_statement;

error: {
        int offset = p - string;
        _cg_set_error(error,
                      CG_BLEND_STRING_ERROR,
                      CG_BLEND_STRING_ERROR_PARSE_ERROR,
                      "Syntax error for string \"%s\" at offset %d: %s",
                      string,
                      offset,
                      error_string);

        if (CG_DEBUG_ENABLED(CG_DEBUG_BLEND_STRINGS)) {
            c_debug("Syntax error at offset %d: %s", offset, error_string);
        }
        return 0;
    }
}
示例#29
0
int main(int argc, char **argv)
{
	int i;
	GtkWidget *win;
	GtkWidget *divelist;
	GtkWidget *table;
	GtkWidget *notebook;
	GtkWidget *frame;
	GtkWidget *menubar;
	GtkWidget *vbox;

	parse_xml_init();

	gtk_init(&argc, &argv);

	for (i = 1; i < argc; i++) {
		const char *a = argv[i];

		if (a[0] == '-') {
			parse_argument(a);
			continue;
		}
		parse_xml_file(a);
	}

	report_dives();

	win = gtk_window_new(GTK_WINDOW_TOPLEVEL);
	g_signal_connect(G_OBJECT(win), "destroy",      G_CALLBACK(on_destroy), NULL);
	main_window = win;

	vbox = gtk_vbox_new(FALSE, 0);
	gtk_container_add(GTK_CONTAINER(win), vbox);

	menubar = get_menubar_menu(win);
	gtk_box_pack_start(GTK_BOX(vbox), menubar, FALSE, FALSE, 0);

	/* Table for the list of dives, cairo window, and dive info */
	table = gtk_table_new(2, 2, FALSE);
	gtk_container_set_border_width(GTK_CONTAINER(table), 5);
	gtk_box_pack_end(GTK_BOX(vbox), table, TRUE, TRUE, 0);
	gtk_widget_show(table);

	/* Create the atual divelist */
	divelist = create_dive_list();
	gtk_table_attach(GTK_TABLE(table), divelist, 0, 1, 0, 2,
		0, GTK_FILL | GTK_SHRINK | GTK_EXPAND, 0, 0);

	/* Frame for minimal dive info */
	frame = dive_info_frame();
	gtk_table_attach(GTK_TABLE(table), frame, 1, 2, 0, 1,
		 GTK_FILL | GTK_SHRINK | GTK_EXPAND, 0, 0, 0);

	/* Notebook for dive info vs profile vs .. */
	notebook = gtk_notebook_new();
	gtk_table_attach_defaults(GTK_TABLE(table), notebook, 1, 2, 1, 2);

	/* Frame for dive profile */
	frame = dive_profile_frame();
	gtk_notebook_append_page(GTK_NOTEBOOK(notebook), frame, gtk_label_new("Dive Profile"));
	dive_profile = frame;

	/* Frame for extended dive info */
	frame = extended_dive_info_frame();
	gtk_notebook_append_page(GTK_NOTEBOOK(notebook), frame, gtk_label_new("Extended dive Info"));

	gtk_widget_set_app_paintable(win, TRUE);
	gtk_widget_show_all(win);

	gtk_main();
	return 0;
}
示例#30
0
//---------------------------------------------------------------------------
// mode&1 = testing
QString TSatScript::parse_argument(QString arg, bool *error, int mode)
{
    QString str, constant;
    int     index, start_pos, end_pos, pos, len;

    if(*error)
        return "";

    index = getconstant_index(arg);
    if(index < 0)
        return arg; // not in our scope

    constant  = constants->at(index);
    start_pos = arg.indexOf(constant);
    end_pos   = arg.indexOf('}', start_pos + 1);

    //qDebug("in arg: %s, line:%d", arg.toStdString().c_str(), __LINE__);

    if(start_pos < 0 || end_pos <= (start_pos + constant.length() - 2)) {
        *error = true;
        arg += "\nBogus argument!";

        return arg; // erroneous argument
    }

    switch(index)
    {
    // check first arguments that can not be embedded, ie {CONSTANT_NAME}
    case SS_INDEX_SATNAME:
    case SS_INDEX_SATFREQ:
    {
        switch(index)
        {
        case SS_INDEX_SATFREQ:
        {
            // frequency in Hz
            str.sprintf("%.0f", _frequency * 1.0e6);

            break;
        }
        case SS_INDEX_SATNAME:
        {
            str.sprintf("%s", _satname.toStdString().c_str());

            break;
        }

        default:
        {
            *error = true;

            return "Wrong index";
        }
        }

        arg = arg.remove(constant);
        arg = arg.insert(start_pos, str);

        //qDebug("out arg 1: %s, line:%d", arg.toStdString().c_str(), __LINE__);

        return parse_argument(arg, error, mode);
    }

    // check embedded arguments, ie {CONSTANT_NAME:arguments {CONSTANT_NAME} arguments...}
    case SS_INDEX_DATETIME:
    case SS_INDEX_DIR:
    {
        pos = start_pos + constant.length();
        len = end_pos - pos;

        if(len <= 1) {
            *error = true;
            arg += "\nBogus parameter, too short!";

            return arg;
        }

        str = substring(arg, pos, len);

        //qDebug("SS_INDEX_XX: %s, line:%d", str.toStdString().c_str(), __LINE__);

        switch(index)
        {
        case SS_INDEX_DATETIME:
        {
            str = now.toString(str);
            //qDebug("arg datetime 1: %s, line:%d", str.toStdString().c_str(), __LINE__);

            arg = arg.remove(start_pos, end_pos - start_pos + 1);
            //qDebug("arg datetime 2: %s, line:%d", arg.toStdString().c_str(), __LINE__);

            arg = arg.insert(start_pos, str);
            //qDebug("arg datetime 3: %s, line:%d\n", arg.toStdString().c_str(), __LINE__);

            break;
        }

        case SS_INDEX_DIR:
        {
            //qDebug("dir: %s, line:%d", str.toStdString().c_str(), __LINE__);

            // get the directory path
            if(!(mode & 1)) {
                if(!checkdirectory(str)) {
                    *error = true;
                    arg += "\nFailed to create directory: " + str;

                    return arg;
                }
            }

            // remove the constant and ending bracket {DIR: ... }
            arg = arg.remove(end_pos, 1);
            arg = arg.remove(constant);

            break;
        }

        default:
        {
            *error = true;

            return "Wrong index";
        }
        }

        // qDebug("arg: %s, line:%d", arg.toStdString().c_str(), __LINE__);

        return parse_argument(arg, error, mode);
    }

    default:
        return "";
    }

    return "";
}