Пример #1
0
//return value: number of parameters
//0 represents only command without any parameters
//-1 represents wrong input
int read_command(char **command,char **parameters,char *prompt)
{
#ifdef READLINE_ON
    char* tmpbuffer = buffer
    buffer  = readline(prompt);
    if(feof(stdin) == 0)
    {
        printf("\n");
        exit(0);
    }
#else
    printf("%s",prompt);
    char* Res_fgets = fgets(buffer,MAXLINE,stdin);
    if(Res_fgets == NULL)
    {
        printf("\n");
        exit(0);
    }		
#endif
    if(buffer[0] == '\0')
        return -1;
    char *pStart,*pEnd;
    int count = 0;
    int isFinished = 0;
    pStart = pEnd = buffer;
    while(isFinished == 0)
    {
        while((*pEnd == ' ' && *pStart == ' ') || (*pEnd == '\t' && *pStart == '\t'))
        {
            pStart++;
            pEnd++;
        }

        if(*pEnd == '\0' || *pEnd == '\n')
        {
            if(count == 0)
                return -1;
            break;
        }

        while(*pEnd != ' ' && *pEnd != '\0' && *pEnd != '\n')
            pEnd++;


        if(count == 0)
        {
            char *p = pEnd;
            *command = pStart;
            while(p!=pStart && *p !='/')
                p--;
            if(*p == '/')
                p++;
            //else //p==pStart
            parameters[0] = p;
            count += 2;
#ifdef DEBUG
            printf("\ncommand:  %s\n",*command);
#endif
        }
        else if(count <= MAXARG)
        {
            parameters[count-1] = pStart;
            count++;
        }
        else
        {
            break;
        }

        if(*pEnd == '\0' || *pEnd == '\n')
        {
            *pEnd = '\0';
            isFinished = 1;
        }
        else
        {
            *pEnd = '\0';
            pEnd++;
			pStart = pEnd;
        }
    }

    parameters[count-1] = NULL;

#ifdef DEBUG
    /*input analysis*/
    printf("input analysis:\n");
    printf("pathname:%s\ncommand:%s\nparameters:\n",*command,parameters[0]);
    int i;
    for(i=0;i<count-1;i++)
        printf("%s\n",parameters[i]);
#endif

//free the space of readline() ---error
/**
 * edit by reeves 
 * 2015/07/03
 * 下面这样写会有错误,导致readline情况下输入命令却不执行
#ifdef READLINE_ON
    free(buffer);
    buffer = tmpbuffer;
#endif
    return count;
}
*/
//free the space of readline()---correct
#ifdef READLINE_ON
    buffer=NULL;
    free(tmpbuffer);
#endif
    return count;
}
Пример #2
0
int gridread(char *file, void ***data, int datatype, int *nx, int *ny,
             float *dx, float *dy, double bndbox[4], double *csize, float *nodata, int *filetype)
{
  FILE *fp;
  int channel1,type,iesri;

  int i, j, hdrlines = 0;
  float value;
  char fline[MAXLN], keyword[21], utmetag, utmntag;
  float **farr;
  int **iarr;
  short **sarr;
  double adjbndbox[4],utme,utmn;
  CELLTYPE *rowbuf;
  float floatNull;


  if(iesri = GridIOSetup() >= 0)
    /*
    Open input cell layer with no evaluation        (5)
    */
    if ((channel1 =
           CellLayerOpen(file,READONLY,ROWIO,
                         &type,csize)) >= 0 )
    {
/*  The success of these means the file could be opened as an ESRI grid file  */
      *filetype=1;
/*  File types are
    0=ASCII
    1= ARCVIEW grid via the ESRI Application Programmers Interface  */
/*  here is the ESRI grid file read stuff - following copyrow example */
      *dx = *dy = (float) *csize;
      if(type == CELLINT && datatype == RPFLTDTYPE)
      {
        printf("%s File contains integer data but was read as float\n",file);
      }
      if(type == CELLFLOAT && datatype != RPFLTDTYPE)
      {
        printf("%s File contains Float data but was read as Integer\n",file);
      }
      /*
      Get the bounding box of the input cell layer            (7)
      */
      if (BndCellRead (file, bndbox) < 0)
      {
        printf ("could not read bounding box of input grid\n");
        CellLyrClose(channel1);
        GridIOExit();
        return(1);
      }
/*        printf("%f %f %f %f %g\n",bndbox[0],bndbox[1],bndbox[2],bndbox[3],*nodata) */;
/*  Bounding box is xllcorner, yllcorner, xurcorner, yurcorner   */

      /*
      Set the Window to the output bounding box and cellsize  (9)
      */
      if (AccessWindowSet (bndbox, *csize, adjbndbox) < 0)
      {
        printf ("Could not set Window\n");
        CellLyrClose(channel1);
        GridIOExit();
        return(2);
      }
      /*
      Get the number of rows and columns                      (10)
      in the window
      */
      *nx = WindowCols();
      *ny = WindowRows();

      /*  Allocate memory and set all type pointers  */
      *data = matalloc(*nx, *ny, datatype);
      farr = (float **) (*data);
      iarr = (int **) (*data);
      sarr = (short **) (*data);
      GetMissingFloat(&floatNull);

      *nodata = (datatype == RPFLTDTYPE) ? floatNull : -9999.;

      /*
      Allocate row buffer                                     (11)
      */
      if ((rowbuf = (CELLTYPE *)
                    CAllocate1 ( *nx, sizeof(CELLTYPE)))
          == NULL )
      {
        printf ("Could not allocate memory\n");
        CellLyrClose(channel1);
        GridIOExit();
        return(3);
      }
      /*
      Now copy row into array                 (12)
      */
      for (i=0; i < *ny; i++)
      {
        GetWindowRow (channel1, i, rowbuf);
        if(type == CELLINT)
        {
          register int *buf = (int *)rowbuf;
          if(datatype == RPSHRDTYPE)
          {
            for(j=0; j < *nx; j++)
            {
              sarr[j][i]=(buf[j] == MISSINGINT) ? (short) *nodata : (short) buf[j];
            }
          }
          else if(datatype == RPINTDTYPE)
          {
            for(j=0; j < *nx; j++)
            {
              iarr[j][i]=(buf[j] == MISSINGINT) ? (int) *nodata : buf[j];
            }
          }
          else
          {
            for(j=0; j < *nx; j++)
            {
              farr[j][i]=(buf[j] == MISSINGINT) ? *nodata : (float) buf[j];
            }
          }
        }
        else
        {
          register float *buf = (float *)rowbuf;

/*     This is all repeated to get right the typecasting of data from ESRI file into the format
       we want   */
          if(datatype == RPSHRDTYPE)
          {
            for(j=0; j < *nx; j++)
            {
              sarr[j][i]=(buf[j] == floatNull) ? (short) *nodata : (short) buf[j];
            }
          }
          else if(datatype == RPINTDTYPE)
          {
            for(j=0; j < *nx; j++)
            {
              iarr[j][i]=(buf[j] == floatNull) ? (int) *nodata : (int) buf[j];
            }
          }
          else
          {
            for(j=0; j < *nx; j++)
            {
              farr[j][i]= buf[j];
            }
          }
        }
      }

      /*
      Free row buffer                                         (13)
      */
      CFree1 ((char *)rowbuf);
      /*
      Close handles                                           (14)
      */
      CellLyrClose(channel1);
      /*
      Done with the library                                   (15)
      */
      GridIOExit();
      return(0);
    }

/*  Here assume file is ASCII  Close ESRI stuff. */
//    CellLyrClose(channel1);
  GridIOExit();

  *filetype=0;
  fp = fopen(file,"r");
  printf("%s\n",file);
  if(fp == NULL)
  {
    printf("\nERROR: Cannot open input file (%s).\n\n",file);
    return(1);
  }

  /* read ARC-Info header */
  while(1)
  {
    readline(fp, fline);
    if(!isalpha(*fline) || *fline == '-')
      break;

    hdrlines++;

    sscanf(fline,"%s %f",keyword,&value);

    if(strcmp(keyword,"ncols") == 0 || strcmp(keyword,"NCOLS") == 0)
      *nx = (int)value;
    else if(strcmp(keyword,"nrows") == 0 || strcmp(keyword,"NROWS") == 0)
      *ny = (int)value;
    else if(strcmp(keyword,"xllcenter") == 0 || strcmp(keyword,"XLLCENTER") == 0)
    {
      utmetag = 'c';
      utme = value;
    }
    else if(strcmp(keyword,"xllcorner") == 0 || strcmp(keyword,"XLLCORNER") == 0)
    {
      utmetag = 'e';
      utme = value;
    }
    else if(strcmp(keyword,"yllcenter") == 0 || strcmp(keyword,"YLLCENTER") == 0)
    {
      utmntag = 'c';
      utmn = value;
    }
    else if(strcmp(keyword,"yllcorner") == 0 || strcmp(keyword,"YLLCORNER") == 0)
    {
      utmntag = 'e';
      utmn = value;
    }
    else if(strcmp(keyword,"cellsize") == 0 || strcmp(keyword,"CELLSIZE") == 0)
    {
      *dx = *dy = value;
      *csize = (double) value;
    }
    else if(strcmp(keyword,"nodata_value") == 0 || strcmp(keyword,"NODATA_VALUE") == 0 ||
            strcmp(keyword,"NODATA_value") == 0)
      *nodata = value;
  }

  /* adjust utme and utmn if necessary (we store center of reference cell) */
  if(utmetag == 'e') utme = utme + *dx/2;
  if(utmntag == 'e') utmn = utmn + *dy/2;
  bndbox[0] = utme - *csize/2.;
  bndbox[1] = utmn - *csize/2.;
  bndbox[2] = bndbox[0] + *csize * (*nx);
  bndbox[3] = bndbox[1] + *csize * (*ny);
  /* position file pointer for ARC-Info file to beginning of image data */
  rewind(fp);
  for(i=0; i<hdrlines; i++) readline(fp, fline);

  /* convert depending on datatype */
  if(datatype == RPSHRDTYPE)
  {
    sarr = (short **) matalloc(*nx, *ny, datatype);

    /* read in the ARC-Info file */
    for(i=0; i< *ny; i++)
    {
      for(j=0; j< *nx; j++)
        fscanf(fp,"%hd",&sarr[j][i]);
    }
    *data = (void **) sarr;
  }
  else if(datatype == RPINTDTYPE)
  {
    iarr = (int **) matalloc(*nx, *ny, datatype);

    for(i=0; i< *ny; i++)
    {
      for(j=0; j< *nx; j++)
        fscanf(fp,"%d",&iarr[j][i]);
    }
    *data = (void **) iarr;
  }
  else if(datatype == RPFLTDTYPE)
  {
    farr = (float **) matalloc(*nx, *ny, datatype);

    /* read in the ARC-Info file */
    for(i=0; i< *ny; i++)
    {
      for(j=0; j< *nx; j++)
      {

        fscanf(fp,"%f",&farr[j][i]);
      }
    }
    *data = (void **) farr;
  }
  else
  {
    printf("\nERROR: unknown datatype (%s).\n\n",datatype);
  }
  fclose(fp);
  return(0);
}
Пример #3
0
int do_askenv ( cmd_tbl_t *cmdtp, int flag, int argc, char *argv[])
{
	extern char console_buffer[CFG_CBSIZE];
	char message[CFG_CBSIZE];
	int size = CFG_CBSIZE - 1;
	int len;
	char *local_args[4];

	local_args[0] = argv[0];
	local_args[1] = argv[1];
	local_args[2] = NULL;
	local_args[3] = NULL;

	if (argc < 2) {
		printf ("Usage:\n%s\n", cmdtp->usage);
		return 1;
	}
	/* Check the syntax */
	switch (argc) {
	case 1:
		printf ("Usage:\n%s\n", cmdtp->usage);
		return 1;

	case 2:		/* askenv envname */
		sprintf (message, "Please enter '%s':", argv[1]);
		break;

	case 3:		/* askenv envname size */
		sprintf (message, "Please enter '%s':", argv[1]);
		size = simple_strtoul (argv[2], NULL, 10);
		break;

	default:	/* askenv envname message1 ... messagen size */
	    {
		int i;
		int pos = 0;

		for (i = 2; i < argc - 1; i++) {
			if (pos) {
				message[pos++] = ' ';
			}
			strcpy (message+pos, argv[i]);
			pos += strlen(argv[i]);
		}
		message[pos] = '\0';
		size = simple_strtoul (argv[argc - 1], NULL, 10);
	    }
		break;
	}

	if (size >= CFG_CBSIZE)
		size = CFG_CBSIZE - 1;

	if (size <= 0)
		return 1;

	/* prompt for input */
	len = readline (message);

	if (size < len)
		console_buffer[size] = '\0';

	len = 2;
	if (console_buffer[0] != '\0') {
		local_args[2] = console_buffer;
		len = 3;
	}

	/* Continue calling setenv code */
	return _do_setenv (flag, len, local_args);
}
Пример #4
0
int
main(int argc, char **argv)
{
  char ruby_code[1024] = { 0 };
  char last_code_line[1024] = { 0 };
#ifndef ENABLE_READLINE
  int last_char;
  int char_index;
#else
  char *home = NULL;
#endif
  mrbc_context *cxt;
  struct mrb_parser_state *parser;
  mrb_state *mrb;
  mrb_value result;
  struct _args args;
  int n;
  int code_block_open = FALSE;
  int ai;

  /* new interpreter instance */
  mrb = mrb_open();
  if (mrb == NULL) {
    fputs("Invalid mrb interpreter, exiting mirb\n", stderr);
    return EXIT_FAILURE;
  }
  mrb_define_global_const(mrb, "ARGV", mrb_ary_new_capa(mrb, 0));

  n = parse_args(mrb, argc, argv, &args);
  if (n == EXIT_FAILURE) {
    cleanup(mrb, &args);
    usage(argv[0]);
    return n;
  }

  print_hint();

  cxt = mrbc_context_new(mrb);
  cxt->capture_errors = 1;
  cxt->lineno = 1;
  mrbc_filename(mrb, cxt, "(mirb)");
  if (args.verbose) cxt->dump_result = 1;

  ai = mrb_gc_arena_save(mrb);

#ifdef ENABLE_READLINE
  using_history();
  home = getenv("HOME");
#ifdef _WIN32
  if (!home)
    home = getenv("USERPROFILE");
#endif
  if (home) {
    strcpy(history_path, home);
    strcat(history_path, "/");
    strcat(history_path, history_file_name);
    read_history(history_path);
  }
#endif


  while (TRUE) {
#ifndef ENABLE_READLINE
    print_cmdline(code_block_open);

    char_index = 0;
    while ((last_char = getchar()) != '\n') {
      if (last_char == EOF) break;
      last_code_line[char_index++] = last_char;
    }
    if (last_char == EOF) {
      fputs("\n", stdout);
      break;
    }

    last_code_line[char_index] = '\0';
#else
    char* line = readline(code_block_open ? "* " : "> ");
    if (line == NULL) {
      printf("\n");
      break;
    }
    strncpy(last_code_line, line, sizeof(last_code_line)-1);
    add_history(line);
    free(line);
#endif

    if ((strcmp(last_code_line, "quit") == 0) || (strcmp(last_code_line, "exit") == 0)) {
      if (!code_block_open) {
        break;
      }
      else{
        /* count the quit/exit commands as strings if in a quote block */
        strcat(ruby_code, "\n");
        strcat(ruby_code, last_code_line);
      }
    }
    else {
      if (code_block_open) {
        strcat(ruby_code, "\n");
        strcat(ruby_code, last_code_line);
      }
      else {
        strcpy(ruby_code, last_code_line);
      }
    }

    /* parse code */
    parser = mrb_parser_new(mrb);
    parser->s = ruby_code;
    parser->send = ruby_code + strlen(ruby_code);
    parser->lineno = cxt->lineno;
    mrb_parser_parse(parser, cxt);
    code_block_open = is_code_block_open(parser);

    if (code_block_open) {
      /* no evaluation of code */
    }
    else {
      if (0 < parser->nerr) {
        /* syntax error */
        printf("line %d: %s\n", parser->error_buffer[0].lineno, parser->error_buffer[0].message);
      }
      else {
        /* generate bytecode */
        n = mrb_generate_code(mrb, parser);

        /* evaluate the bytecode */
        result = mrb_run(mrb,
            /* pass a proc for evaulation */
            mrb_proc_new(mrb, mrb->irep[n]),
            mrb_top_self(mrb));
        /* did an exception occur? */
        if (mrb->exc) {
          p(mrb, mrb_obj_value(mrb->exc), 0);
          mrb->exc = 0;
        }
        else {
          /* no */
          if (!mrb_respond_to(mrb, result, mrb_intern2(mrb, "inspect", 7))){
            result = mrb_any_to_s(mrb,result);
          }
          p(mrb, result, 1);
        }
      }
      ruby_code[0] = '\0';
      last_code_line[0] = '\0';
      mrb_gc_arena_restore(mrb, ai);
    }
    mrb_parser_free(parser);
    cxt->lineno++;
  }
  mrbc_context_free(mrb, cxt);
  mrb_close(mrb);

#ifdef ENABLE_READLINE
  write_history(history_path);
#endif

  return 0;
}
Пример #5
0
void filemenu(int mode)
{
	getstats(mode);
	if (button(100,100,170,120,"OPTIMIZE",9,13,base2,false,mode)==DDgui_LeftClick && mode!=DD_AfterCheck) { optimizeproject(); waitleftbutton=true; }
	if (button(100,121,170,141,"TextureO",9,13,base2,false,mode)==DDgui_LeftClick && mode!=DD_AfterCheck) { savetextureusefile(); waitleftbutton=true; }
	if (mode==DD_Draw)
	{
		glColor4f(buttontextlit);
		rectangle(661,120,775,264);
	}	  
	if (mode==DD_Check)
		if (leftclickinwindow(661,121,774,263) && mouseinwindow(661,121,774,260)) fscnselected=min(fscnbarpos+(my-121) / 10,filenum(prjlist)-1);
	if ((mode ==DD_Check) && mouseinwindow(661,121,774,263)) fscnbarpos-=wheel*4;
	scroller(775,120,790,264,15,15,filenum(prjlist),14,fscnbarpos,mode);
	if (mode==DD_Draw)
	{
		pf = prjlist;
		for (x=1;x<=fscnbarpos;x++) pf=pf->next;
		for (x=0;x<=13;x++)
		{
			if (pf!=NULL)
			{
				if (fscnbarpos+x==fscnselected) glColor4f(col4); else glColor4f(buttontextlit);
				glRasterPos2i(665,130+x*10);
				strcpy(st,pf->filedata.cFileName);
				glPrint(st,base2,18);
				pf=pf->next;
			}
		}

		glColor4f(buttontextlit);
		sprintf(s,"%d PROJECTS.",filenum(prjlist));
		glRasterPos2i(683,277);
		glPrint(s,base2);

	}
	glColor4f(1,1,1,1);
	if ((button(686,283,771,299,texbutton1,0,96.0/256.0,85.0/256.0,112.0/256.0,false,mode) == DDgui_LeftClick) && (mode!=DD_AfterCheck))
	{
		pf = prjlist;
		for (x=1;x<=fscnselected;x++) pf=pf->next;
		//sprintf(s,"%s%s",scenedir,pf->filedata.cFileName);
		memset(lastfilename,0,256);
		memcpy(lastfilename,pf->filedata.cFileName,strlen(pf->filedata.cFileName)-4);
		sprintf(s,"%s%s",projectdir,pf->filedata.cFileName);
		//loadaDDictscene(*actualscene,NULL,s,true,true,true,true,true);				
		LoadProject(s);
		modellviews[3].cam=actualscene->editview;
		modellviews[3].cam2=actualscene->editview;
		tTexture *tex=texturelist;
		while ((tex!=NULL) && (tex->number!=selectedtexture)) tex=tex->next;
		memcpy(generatedtexture.commands,tex->commands,sizeof(generatedtexture.commands));
		memcpy(generatedtexture.texts,tex->texts,sizeof(generatedtexture.texts));
		generatedtexture.commandnum=tex->commandnum;
		//memcpy(generatedtexture.layers,tex->layers,sizeof(generatedtexture.layers));
		for (y=0;y<=3;y++)
		{
			glBindTexture(GL_TEXTURE_2D, texlayers[y]);
			glTexImage2D(GL_TEXTURE_2D,0,3,256,256,0,GL_RGBA,GL_UNSIGNED_BYTE,generatedtexture.layers[y]);
		}				
		
		if (materiallist!=NULL)
		{
			matselected=0;
			material *mat=materiallist;
			for (x=1;x<=matselected;x++) mat=mat->next;
			mattexture=mat->handle;
		}				

		waitleftbutton=true;
	}

	if (button(685,300,770,316,texbutton1,0,144.0/256.0,85.0/256.0,160.0/256.0,false,mode) == DDgui_LeftClick) 
	{
		char *ss=readline("Enter Filename (.scn not needed)",210,0,base2,lastfilename);
		if (ss!="")
		{
			//sprintf(s,"%s%s.scn",scenedir,ss);
			//saveaDDictscene(*actualscene,NULL,s,scntexturesave, scncamerasave, scnselectionsave, scnlightsave, scnobjectsave);
			memset(lastfilename,0,256);
			memcpy(lastfilename,ss,strlen(ss));
			sprintf(s,"%s%s.64k",projectdir,ss);
			SaveProject(s);
		}
	}
	if (button(685,317,770,333,texbutton1,0,160.0/256.0,85.0/256.0,176.0/256.0,false,mode) == DDgui_LeftClick) 
	{
		char *ss=readline("Enter Filename (.scn not needed)",210,0,base2,"");
		if (ss!="")
		{
			sprintf(s,"%s%s.m64",minimaldir,ss);
			//SaveMinimalScene(*actualscene,NULL,s);
			saveminimalproject(s,2);
		}
	}
	/*RadioButton(681,341,scntexturesave,"TEXTURES",mode);
	RadioButton(681,355,scncamerasave,"CAMERAS",mode);
	RadioButton(681,369,scnselectionsave,"SELECTIONS",mode);
	RadioButton(681,383,scnlightsave,"LIGHTS",mode);
	RadioButton(681,397,scnobjectsave,"OBJECTS",mode);*/
}
void *CLInterface(void *data)
{
    printf(RED_BEGIN"#Ready to operation ('h' for help)#\n"COLOR_END);

    (void)data;
    OCStackResult ret;
    char query[MAX_LINE] = {0,};
    const char prompt[] = BOLD_BEGIN"IoTivity-DP#"COLOR_END" ";
    const char* helpmsg[6] = {
            GREEN_BEGIN"# h  (or help) : show help message"COLOR_END,
            GREEN_BEGIN"# dd (DP device discovery) : discover Direct-Pairing devices"COLOR_END,
            GREEN_BEGIN"# dp (start Direct-Pairing) : negotiate DP method & start Direct-Pairing"COLOR_END,
            GREEN_BEGIN"# sd (send data) : send data to device"COLOR_END,
            GREEN_BEGIN"# ll (list all device) : list all discovered/paired devices"COLOR_END,
            GREEN_BEGIN"# q  (quit) : quit test"COLOR_END,
        };

    for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)
    {
        fprintf(stderr, "%s\n", helpmsg[i]);
    }
    printf("\n");

    // cli
    for (;;)
    {
        const char *input = readline(prompt, NULL);
        if (!input) {
            continue;
        }

        strncpy(query, input, MAX_LINE);
        if (!strlen(query))
        {
            continue;
        }
        else if (!strcmp(query, "h") || !strcmp(query, "help"))
        {
            for (size_t i=0; i<(sizeof(helpmsg)/sizeof(char*)); i++)
            {
                fprintf(stderr, "%s\n", helpmsg[i]);
            }
            continue;
        }
        else
        {
            if (!strcmp(query, "dd"))
            {
                OIC_LOG(INFO, TAG, "- Direct-Pairing device discovery -");

                ret = DirectPairingDiscovery();
                if (OC_STACK_OK != ret)
                {
                    OIC_LOG(ERROR, TAG, "Error in DirectPairingDiscovery()");
                }
            }
            else if (!strcmp(query, "dp"))
            {
                OIC_LOG(INFO, TAG, "- Negotiate DP method & Start Direct-Pairing -");

                printf("\n   * List of  discovered device\n");
                printList(discoveredDevs);

                // target peer
                OCDPDev_t *peer = NULL;
                long peerIdx;
                input = readline("   > Enter Peer Device Number to initiate Direct-Pairing: ", NULL);
                if (!input || !strlen(input))
                {
                    continue;
                }
                char *ptr;
                peerIdx = strtol(input, &ptr, 10);

                peer = getDev(discoveredDevs, (uint32_t)peerIdx);
                if (NULL == peer)
                {
                    OIC_LOG(ERROR, TAG, "Not found the peer in discovered list");
                    continue;
                }

                // get pairing method
                long pmIdx;
                OCPrm_t pmSel = DP_NOT_ALLOWED;
                if (false == printPairingMethod(peer))
                {
                    OIC_LOG(ERROR, TAG, "Target does not support the Direct-Pairing");
                    continue;
                }
                input = readline("   > Enter pairing method: ", NULL);
                if (!input || !strlen(input))
                {
                    continue;
                }
                pmIdx = strtol(input, &ptr, 10);
                printf("\n");
                if (0 >= pmIdx || peer->prmLen+1 < (size_t)pmIdx)
                {
                    OIC_LOG(ERROR, TAG, "Invalid mode selection");
                    continue;
                }
                pmSel = peer->prm[pmIdx-1];

                // get PIN
                char pinNumber[DP_PIN_LENGTH+1];
                input = readline("   > Enter PIN Number for authentication (ex - '00000000' [8 digit] ): ", NULL);
                if (!input || DP_PIN_LENGTH != strlen(input))
                {
                    OIC_LOG(ERROR, TAG, "Invalid PIN");
                    continue;
                }
                sscanf(input, "%8s", pinNumber);
                printf("\n");

                ret = DoDirectPairing(peer, pmSel, pinNumber);
                if (OC_STACK_OK != ret)
                {
                    OIC_LOG(ERROR, TAG, "Error in DoDirectPairing()");
                }
            }
            else if (!strcmp(query, "sd"))
            {
                OIC_LOG(INFO, TAG, "- Send data(GET Request) to device(led server) -");

                //pairedDevs = OCGetDirectPairedDevices();
                //printList(pairedDevs);
                printList(discoveredDevs);

                // target peer
                OCDPDev_t *peer = NULL;
                long peerIdx;
                input = readline("   > Enter Peer Device Number to initiate Direct-Pairing: ", NULL);
                if (!input || !strlen(input))
                {
                    continue;
                }
                char *ptr;
                peerIdx = strtol(input, &ptr, 10);

                //peer = getDev(pairedDevs, peerIdx);
                peer = getDev(discoveredDevs, (uint32_t)peerIdx);
                if (NULL == peer)
                {
                    OIC_LOG(ERROR, TAG, "Not found the peer in discovered list");
                    continue;
                }

                // send Get Req
                ret = SendGetRequest(peer);
                if (OC_STACK_OK != ret)
                {
                    OIC_LOG(ERROR, TAG, "Error in SendGetRequest()");
                }
            }
            else if (!strcmp(query, "ll"))
            {
                OIC_LOG(INFO, TAG, "- List all discovered and paired devices) -");

                printf("  > List of discovered devices\n");
                printList(discoveredDevs);
                printf("\n");

                printf("  > List of paired devices\n");
                pairedDevs = OCGetDirectPairedDevices();
                printList(pairedDevs);
                printf("\n");
            }
            else if (!strcmp(query, "q"))
            {
                printf("QUIT\n");
                gQuitFlag = 1;
                break;
            }
        }
    }

    return 0;
}
Пример #7
0
void split(char *input_file, int l, int machines, int nr_query, struct Query_Machine *q_machine, int *query)
{
	int machine_id = 0;
	double y;
	int len = 0;
	FILE *fp = fopen(input_file,"r");
	char *idx, *val, *endptr;
	char *label;
	char **out_file = (char**)malloc(sizeof(char*)*machines);
	for(int i=0;i<machines;i++)
		out_file[i] = (char*)malloc(sizeof(char)*1024);
    FILE **f = (FILE**)malloc(sizeof(FILE*)*machines);
    
    if(mkdir("temp_dir",0777)==0)
    {
        printf("Directory was successfully created!\n");
    }
    else
    {
        printf("Directory has existed!!\n");
    }
    
    for(int i=0;i<machines;i++)
	{
		sprintf(out_file[i],"temp_dir/train.txt.%d",i);
		f[i] = fopen(out_file[i],"w");
	}

	char *copy_line = (char*)malloc(sizeof(char)*2048);
	for(int j=0;j<l;j++)
	{
		readline(fp);		
		len = (int)strlen(line);
		//printf("len=%d for line:%d\n",len,j+1);
		if(len > 2048)
		{
			copy_line = (char*)realloc(copy_line,len*sizeof(char));
		}
		sprintf(copy_line, "%s", line);
		//strcpy(copy_line,line);
		//printf("copy_line:%s",copy_line);
		//printf("line:%s",line);
		label = strtok(line, " \t\n");
		if(label == NULL)
			exit_input_error(j+1);
		y = strtod(label, &endptr);
		if(endptr == label || *endptr != '\0')
			exit_input_error(j+1);
		idx = strtok(NULL,":");
		val = strtok(NULL, " \t");
		if(val == NULL)
			exit_input_error(j+1);
		if(!strcmp(idx,"qid"))
		{
			errno = 0;
			query[j] = (int)strtol(val, &endptr, 10);
			if(endptr == val || errno !=0 || (*endptr != '\0' && !isspace(*endptr)))
				exit_input_error(j+1);
		}

		for(int i=0;i<nr_query;i++)
		{
			if(query[j] == q_machine[i].query)
			{
				machine_id = q_machine[i].machine_id;
				break;
			}
		}
		fprintf(f[machine_id],"%s",copy_line);

	}
	free(copy_line);
	for(int i=0;i<machines;i++)
		free(out_file[i]);
	free(out_file);
	for(int i=0;i<machines;i++)
		fclose(f[i]);
	rewind(fp);
	fclose(fp);
}
Пример #8
0
STATIC int do_repl(void) {
    mp_hal_stdout_tx_str("MicroPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; "
        MICROPY_PY_SYS_PLATFORM " version\nUse Ctrl-D to exit, Ctrl-E for paste mode\n");

    #if MICROPY_USE_READLINE == 1

    // use MicroPython supplied readline

    vstr_t line;
    vstr_init(&line, 16);
    for (;;) {
        mp_hal_stdio_mode_raw();

    input_restart:
        vstr_reset(&line);
        int ret = readline(&line, ">>> ");
        mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT;

        if (ret == CHAR_CTRL_D) {
            // EOF
            printf("\n");
            mp_hal_stdio_mode_orig();
            vstr_clear(&line);
            return 0;
        } else if (ret == CHAR_CTRL_E) {
            // paste mode
            mp_hal_stdout_tx_str("\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\n=== ");
            vstr_reset(&line);
            for (;;) {
                char c = mp_hal_stdin_rx_chr();
                if (c == CHAR_CTRL_C) {
                    // cancel everything
                    mp_hal_stdout_tx_str("\n");
                    goto input_restart;
                } else if (c == CHAR_CTRL_D) {
                    // end of input
                    mp_hal_stdout_tx_str("\n");
                    break;
                } else {
                    // add char to buffer and echo
                    vstr_add_byte(&line, c);
                    if (c == '\r') {
                        mp_hal_stdout_tx_str("\n=== ");
                    } else {
                        mp_hal_stdout_tx_strn(&c, 1);
                    }
                }
            }
            parse_input_kind = MP_PARSE_FILE_INPUT;
        } else if (line.len == 0) {
            if (ret != 0) {
                printf("\n");
            }
            goto input_restart;
        } else {
            // got a line with non-zero length, see if it needs continuing
            while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) {
                vstr_add_byte(&line, '\n');
                ret = readline(&line, "... ");
                if (ret == CHAR_CTRL_C) {
                    // cancel everything
                    printf("\n");
                    goto input_restart;
                } else if (ret == CHAR_CTRL_D) {
                    // stop entering compound statement
                    break;
                }
            }
        }

        mp_hal_stdio_mode_orig();

        mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line.buf, line.len, false);
        ret = execute_from_lexer(lex, parse_input_kind, true);
        if (ret & FORCED_EXIT) {
            return ret;
        }
    }

    #else

    // use GNU or simple readline

    for (;;) {
        char *line = prompt(">>> ");
        if (line == NULL) {
            // EOF
            return 0;
        }
        while (mp_repl_continue_with_input(line)) {
            char *line2 = prompt("... ");
            if (line2 == NULL) {
                break;
            }
            char *line3 = strjoin(line, '\n', line2);
            free(line);
            free(line2);
            line = line3;
        }

        mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line, strlen(line), false);
        int ret = execute_from_lexer(lex, MP_PARSE_SINGLE_INPUT, true);
        if (ret & FORCED_EXIT) {
            return ret;
        }
        free(line);
    }

    #endif
}
Пример #9
0
/// %Thread start
void CliRunnable::run() {
	///- Display the list of available CLI functions then beep
	//sLog->outString("");
#if PLATFORM != PLATFORM_WINDOWS
	rl_attempted_completion_function = cli_completion;
	rl_event_hook = cli_hook_func;
#endif
	if (sConfig->GetBoolDefault("BeepAtStart", true))
		printf("\a"); // \a = Alert

	// print this here the first time
	// later it will be printed after command queue updates
	printf("ArkCORE>");

	///- As long as the World is running (no World::m_stopEvent), get the command line and handle it
	while (!World::IsStopped()) {
		fflush(stdout);

		char *command_str; // = fgets(commandbuf, sizeof(commandbuf), stdin);

#if PLATFORM == PLATFORM_WINDOWS
		char commandbuf[256];
		command_str = fgets(commandbuf, sizeof(commandbuf), stdin);
#else
		command_str = readline("ArkCORE>");
		rl_bind_key('\t', rl_complete);
#endif
		if (command_str != NULL) {
			for (int x = 0; command_str[x]; x++)
				if (command_str[x] == '\r' || command_str[x] == '\n') {
					command_str[x] = 0;
					break;
				}

			if (!*command_str) {
#if PLATFORM == PLATFORM_WINDOWS
				printf("ArkCORE>");
#endif
				continue;
			}

			std::string command;
			if (!consoleToUtf8(command_str, command)) // convert from console encoding to utf8
					{
#if PLATFORM == PLATFORM_WINDOWS
				printf("ArkCORE>");
#endif
				continue;
			}
			fflush(stdout);
			sWorld->QueueCliCommand(
					new CliCommandHolder(NULL, command.c_str(), &utf8print,
							&commandFinished));
#if PLATFORM != PLATFORM_WINDOWS
			add_history(command.c_str());
#endif
		} else if (feof(stdin)) {
			World::StopNow(SHUTDOWN_EXIT_CODE);
		}
	}
}
Пример #10
0
// read in a problem (in libsvm format)
void read_problem(const char *filename)
{
	int max_index, inst_max_index, i, max_index_=0;
	long int elements, j;
	FILE *fp = fopen(filename,"r");
	char *endptr;
	char *idx, *val, *label;

	if(fp == NULL)
	{
		fprintf(stderr,"can't open input file %s\n",filename);
		exit(1);
	}

	prob.l = 0;
	elements = 0;
	max_line_len = 1024;
	line = Malloc(char,max_line_len);
	while(readline(fp, 0)!=NULL) 
	{
		char *p = strtok(line," \t"); // label

		// features
		while(1)
		{
			idx = strtok(NULL,":"); 
			p = strtok(NULL," \t");
			if(p == NULL || *p == '\n') // check '\n' as ' ' may be after the last feature
				break;
			if((int) strtol(idx,&endptr,10)>max_index_) 
				max_index_ = (int) strtol(idx,&endptr,10); 
			elements++;
		}
		elements++; // for bias term
		prob.l++;
	}
	param.real_dim = max_index_; 
	rewind(fp);

	prob.bias=bias;

	prob.y = Malloc(double,prob.l);
	prob.x = Malloc(struct feature_node *,prob.l);
	x_space = Malloc(struct feature_node,elements+prob.l);

	max_index = 0;
	j=0;
	for(i=0;i<prob.l;i++)
	{
		inst_max_index = 0; // strtol gives 0 if wrong format
		readline(fp, param.real_dim); //sym
		prob.x[i] = &x_space[j];
		label = strtok(line," \t\n");
		if(label == NULL) // empty line
			exit_input_error(i+1);

		prob.y[i] = strtod(label,&endptr);
		if(endptr == label || *endptr != '\0')
			exit_input_error(i+1);

		while(1)
		{
			idx = strtok(NULL,":");
			val = strtok(NULL," \t");

			if(val == NULL)
				break;

			errno = 0;
			x_space[j].index = (int) strtol(idx,&endptr,10);
			if(endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index)
				exit_input_error(i+1);
			else
				inst_max_index = x_space[j].index;

			errno = 0;
			x_space[j].value = strtod(val,&endptr);
			if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
				exit_input_error(i+1);

			++j;
		}

		if(inst_max_index > max_index)
			max_index = inst_max_index;

		if(prob.bias >= 0)
			x_space[j++].value = prob.bias;

		x_space[j++].index = -1;
	}

	if(prob.bias >= 0)
	{
		prob.n=max_index+1;
		for(i=1;i<prob.l;i++)
			(prob.x[i]-2)->index = prob.n; 
		x_space[j-2].index = prob.n;
	}
	else
		prob.n=max_index;

	fclose(fp);
}
Пример #11
0
void do_predict(FILE *input, FILE *output)
{
    int total = 0;

    int nr_class=get_nr_class(model_);
    double *prob_estimates=NULL;
    int n;
    int nr_feature=get_nr_feature(model_);
    if(model_->bias>=0)
        n=nr_feature+1;
    else
        n=nr_feature;

    if(!check_probability_model(model_))
    {
        fprintf(stderr, "probability output is only supported for logistic regression\n");
        exit(1);
    }

    prob_estimates = (double *) malloc(nr_class*sizeof(double));

    max_line_len = 1024;
    line = (char *)malloc(max_line_len*sizeof(char));
    int clicks = 0;
    int shows = 0;
    while(readline(input) != NULL)
    {
        int i = 0;
        double target_ctr, predict_ctr;
        char *idx, *val, *endptr;

        int inst_max_index = 0; // strtol gives 0 if wrong format

        char *p = strtok(line," \t\n"); //clicks
        if(p == NULL) // empty line
            exit_input_error(total+1);

        clicks = atoi(p);
        p = strtok(NULL," \t"); // shows
        shows = atoi(p);
        p = strtok(NULL," \t"); // qid:1

        if (shows <=0 || clicks > shows) {
            continue;
        }

        target_ctr = (double)clicks / shows;

        while(1)
        {
            if(i>=max_nr_attr-2)	// need one more for index = -1
            {
                max_nr_attr *= 2;
                x = (struct feature_node *) realloc(x,max_nr_attr*sizeof(struct feature_node));
            }

            idx = strtok(NULL,":");
            val = strtok(NULL," \t");

            if(val == NULL)
                break;
            errno = 0;
            x[i].index = (int) strtol(idx,&endptr,10);
            if(endptr == idx || errno != 0 || *endptr != '\0' || x[i].index <= inst_max_index)
                exit_input_error(total+1);
            else
                inst_max_index = x[i].index;

            errno = 0;
            x[i].value = strtod(val,&endptr);
            if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
                exit_input_error(total+1);

            // feature indices larger than those in training are not used
            if(x[i].index <= nr_feature)
                ++i;
        }

        if(model_->bias>=0)
        {
            x[i].index = n;
            x[i].value = model_->bias;
            i++;
        }
        x[i].index = -1;

        predict_probability(model_,x,prob_estimates);
        fprintf(output,"%d %d ", clicks, shows);
        predict_ctr = prob_estimates[0];
        fprintf(output," %g\n", predict_ctr);
    }

    info("total:%d\n",total);

    free(prob_estimates);
}
Пример #12
0
/*
 * load config file
 */
void on_load_config(GtkButton *button, gpointer user_data)
{
	FILE *config = fopen(current_path, "r");
	if (!config)
		dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Error reading config file"));

	/* target */
	gchar target[FILENAME_MAX];
	readline(config, target, FILENAME_MAX - 1);
	gtk_entry_set_text(GTK_ENTRY(targetname), target);
	
	/* debugger */
	gchar debugger[FILENAME_MAX];
	readline(config, debugger, FILENAME_MAX - 1);
	int index = debug_get_module_index(debugger);
	if (-1 == index)
	{
		dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Configuration error: debugger module \'%s\' is not found"), debugger);
		gtk_combo_box_set_active(GTK_COMBO_BOX(cmb_debugger), 0);
	}
	else
		gtk_combo_box_set_active(GTK_COMBO_BOX(cmb_debugger), index);

	/* arguments */
	gchar arguments[FILENAME_MAX];
	readline(config, arguments, FILENAME_MAX - 1);
	GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(textview));
	gtk_text_buffer_set_text(buffer, arguments, -1);
	
	/* breakpoints and environment variables */
	breaks_iterate(removebreak);
	wtree_remove_all();
	
	gboolean wrongbreaks = FALSE;
	gchar line[MAXLINE];
	gtk_list_store_clear(store);
	while (readline(config, line, MAXLINE))
	{
		if (!strcmp(line, BREAKPOINTS_MARKER))
		{
			/* file */
			gchar file[FILENAME_MAX];
			readline(config, file, MAXLINE);
			
			/* line */
			int nline;
			readline(config, line, MAXLINE);
			sscanf(line, "%d", &nline);
			
			/* hitscount */
			int hitscount;
			readline(config, line, MAXLINE);
			sscanf(line, "%d", &hitscount);

			/* condition */
			gchar condition[MAXLINE];
			readline(config, condition, MAXLINE);

			/* enabled */
			gboolean enabled;
			readline(config, line, MAXLINE);
			sscanf(line, "%d", &enabled);
			
			/* check whether file is available */
			struct stat st;
			if(!stat(file, &st))
				breaks_add(file, nline, condition, enabled, hitscount);
			else
				wrongbreaks = TRUE;
		}
		else if (!strcmp(line, ENVIRONMENT_MARKER))
		{
			gchar name[MAXLINE], value[1000];
			readline(config, name, MAXLINE);
			readline(config, value, MAXLINE);
			
			GtkTreeIter iter;
			gtk_list_store_append(store, &iter);
			
			gtk_list_store_set(store, &iter, NAME, name, VALUE, value, -1);
		}
		else if (!strcmp(line, WATCH_MARKER))
		{
			gchar watch[MAXLINE];
			readline(config, watch, MAXLINE);
			wtree_add_watch(watch);
		}
		else
		{
			dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Error reading config file"));
			break;
		}
	}
	if (wrongbreaks)
		dialogs_show_msgbox(GTK_MESSAGE_ERROR, _("Some breakpoints can't be set as the files are missed"));
	
	add_empty_row();
	
	fclose(config);
	
	if (user_data)
		dialogs_show_msgbox(GTK_MESSAGE_INFO, _("Config loaded successfully"));
}
Пример #13
0
#endif

DEFUN("readline", Freadline, Sreadline,
      (repv prompt_, repv completer), rep_Subr2)
{
    char *prompt = rep_STRINGP(prompt_) ? ((char *) rep_STR(prompt_)) : "> ";
#ifdef HAVE_LIBREADLINE
    char *input;
    repv ret = Qnil, saved;
    rep_GC_root gc_saved;

    saved = completion_fun;
    completion_fun = completer;
    rep_PUSHGC (gc_saved, saved);
    input = readline (prompt);
    rep_POPGC;
    completion_fun = saved;

    if (input)
    {
	int len = strlen (input);
	if (len > 0)
	    add_history (input);
	ret = rep_make_string (len + 2);
	memcpy (rep_STR(ret), input, len);
	rep_STR(ret)[len] = '\n';
	rep_STR(ret)[len+1] = 0;
	free (input);
    }
    completions = Qnil;
Пример #14
0
int lvm_shell(struct cmd_context *cmd, struct cmdline_context *cmdline)
{
	int argc, ret;
	char *input = NULL, *args[MAX_ARGS], **argv;

	rl_readline_name = "lvm";
	rl_attempted_completion_function = (CPPFunction *) _completion;

	_read_history(cmd);

	_cmdline = cmdline;

	_cmdline->interactive = 1;
	while (1) {
		free(input);
		input = readline("lvm> ");

		/* EOF */
		if (!input) {
			printf("\n");
			break;
		}

		/* empty line */
		if (!*input)
			continue;

		add_history(input);

		argv = args;

		if (lvm_split(input, &argc, argv, MAX_ARGS) == MAX_ARGS) {
			log_error("Too many arguments, sorry.");
			continue;
		}

		if (!strcmp(argv[0], "lvm")) {
			argv++;
			argc--;
		}

		if (!argc)
			continue;

		if (!strcmp(argv[0], "quit") || !strcmp(argv[0], "exit")) {
			remove_history(history_length - 1);
			log_error("Exiting.");
			break;
		}

		ret = lvm_run_command(cmd, argc, argv);
		if (ret == ENO_SUCH_CMD)
			log_error("No such command '%s'.  Try 'help'.",
				  argv[0]);

                if ((ret != ECMD_PROCESSED) && !error_message_produced()) {
			log_debug(INTERNAL_ERROR "Failed command did not use log_error");
			log_error("Command failed with status code %d.", ret);
		}
		_write_history();
	}

	free(input);
	return 0;
}
Пример #15
0
int main() {
        printf("Variante %d: %s\n", VARIANTE, VARIANTE_STRING);

#ifdef USE_GUILE
        scm_init_guile();
        /* register "executer" function in scheme */
        scm_c_define_gsubr("executer", 1, 0, 0, executer_wrapper);
#endif

		pidTable = create_pid_list();

		struct sigaction act;
		memset(&act, '\0', sizeof(act));
		act.sa_sigaction = &terminationHandler;
		act.sa_flags = SA_SIGINFO | SA_NOCLDSTOP;
		if(sigaction(SIGCHLD, &act, NULL) == -1){
			perror("sigaction");
		}

	while (1) {
		char *line=0;
		char *prompt = "ensishell>";

		/* Readline use some internal memory structure that
		   can not be cleaned at the end of the program. Thus
		   one memory leak per command seems unavoidable yet */
		line = readline(prompt);
		if (line == 0 || ! strncmp(line,"exit", 4)) {
			terminate(line);
		}
		else if(!strncmp(line, "jobs", 4)){
			clean_pid_list(&pidTable);
			print_pid_list(pidTable);
#ifdef USE_GNU_READLINE
		add_history(line);
#endif
			continue;
		}

#ifdef USE_GNU_READLINE
		add_history(line);
#endif


#ifdef USE_GUILE
		/* The line is a scheme command */
		if (line[0] == '(') {
			char catchligne[strlen(line) + 256];
			sprintf(catchligne, "(catch #t (lambda () %s) (lambda (key . parameters) (display \"mauvaise expression/bug en scheme\n\")))", line);
			scm_eval_string(scm_from_locale_string(catchligne));
			free(line);
                        continue;
                }
#endif

		executer(line);
//		struct cmdline *l;
//		int i, j;
//		/* parsecmd free line and set it up to 0 */
//		l = parsecmd( & line);
//
//		/* If input stream closed, normal termination */
//		if (!l) {
//		  
//			terminate(0);
//		}
//		
//
//		
//		if (l->err) {
//			/* Syntax error, read another command */
//			printf("error: %s\n", l->err);
//			continue;
//		}
//
//		if (l->in) printf("in: %s\n", l->in);
//		if (l->out) printf("out: %s\n", l->out);
//		if (l->bg) printf("background (&)\n");
//
//		/* Display each command of the pipe */
//		for (i=0; l->seq[i]!=0; i++) {
//			char **cmd = l->seq[i];
//			printf("seq[%d]: ", i);
//                        for (j=0; cmd[j]!=0; j++) {
//                                printf("'%s' ", cmd[j]);
//                        }
//			printf("\n");
//		}
	}

}
Пример #16
0
int main(int argc, char **argv)
{
    int    ch, sock, port, count;

    char   line      [MAXLEN];
    char   request   [MAXLEN];
    char   base      [MAXLEN];
    char   constraint[MAXLEN];
    char   server    [MAXLEN];
    char   outfile   [MAXLEN];
    char   bandStr   [MAXLEN];
    char   band2MASS [MAXLEN];

    char  *locstr;
    char  *widthstr;

    char   heightstr [MAXLEN];
    char   sysstr    [MAXLEN];
    char   equistr   [MAXLEN];
    char   resstr    [MAXLEN];
    char   rotstr    [MAXLEN];

    FILE  *fout;


    /* Construct service request using location/size */

    opterr = 0;

    strcpy(heightstr, "");
    strcpy(sysstr,    "");
    strcpy(equistr,   "");
    strcpy(resstr,    "");
    strcpy(rotstr,    "");

    strcpy(band2MASS, "");

    while ((ch = getopt(argc, argv, "s:e:h:p:r:t:")) != EOF)
    {
        switch (ch)
        {
        case 's':
            strcpy(sysstr, optarg);
            break;

        case 'e':
            strcpy(equistr, optarg);
            break;

        case 'h':
            strcpy(heightstr, optarg);
            break;

        case 'p':
            strcpy(resstr, optarg);
            break;

        case 'r':
            strcpy(rotstr, optarg);
            break;

        case 't':
            strcpy(bandStr, optarg);

            if(bandStr[0] == 'j') strcpy(band2MASS, "j");
            else if(bandStr[0] == 'h') strcpy(band2MASS, "h");
            else if(bandStr[0] == 'k') strcpy(band2MASS, "k");
            else if(bandStr[0] == 'J') strcpy(band2MASS, "j");
            else if(bandStr[0] == 'H') strcpy(band2MASS, "h");
            else if(bandStr[0] == 'K') strcpy(band2MASS, "k");

            else
            {
                printf("[struct stat=\"ERROR\", msg=\"If 2MASS band is given, it must be 'J', 'H', or 'K'\"]\n");
                exit(0);
            }

            break;

        default:
            break;
        }
    }

    if(argc < 4)
    {
        printf("[struct stat=\"ERROR\", msg=\"Usage: %s [-s system] [-e equinox] [-h height(deg)] [-p pixsize(arcsec)] [-r rotation] [-t 2mass-band] object|location width(deg) outfile (object/location must be a single argument string)\"]\n", argv[0]);
        exit(0);
    }

    strcpy(server, "irsa.ipac.caltech.edu");

    port = 80;

    strcpy(base, "/cgi-bin/HdrTemplate/nph-hdr?");

    locstr    = url_encode(argv[optind]);
    widthstr  = url_encode(argv[optind+1]);

    strcpy(outfile, argv[optind+2]);

    sprintf(constraint, "location=%s&width=%s",
            locstr, widthstr);

    if(strlen(heightstr) > 0)
    {
        strcat(constraint, "&height=");
        strcat(constraint, url_encode(heightstr));
    }

    if(strlen(sysstr) > 0)
    {
        strcat(constraint, "&system=");
        strcat(constraint, url_encode(sysstr));
    }

    if(strlen(equistr) > 0)
    {
        strcat(constraint, "&equinox=");
        strcat(constraint, url_encode(equistr));
    }

    if(strlen(resstr) > 0)
    {
        strcat(constraint, "&resolution=");
        strcat(constraint, url_encode(resstr));
    }

    if(strlen(rotstr) > 0)
    {
        strcat(constraint, "&rotation=");
        strcat(constraint, url_encode(rotstr));
    }

    if(strlen(band2MASS) > 0)
    {
        strcat(constraint, "&band=");
        strcat(constraint, band2MASS);
    }

    fout = fopen(outfile, "w+");

    if(fout == (FILE *)NULL)
    {
        printf("[struct stat=\"ERROR\", msg=\"Can't open output file %s\"]\n",
               outfile);
        exit(0);
    }


    /* Connect to the port on the host we want */

    sock = tcp_connect(server, port);


    /* Send a request for the file we want */

    sprintf(request, "GET %s%s HTTP/1.0\r\nHOST: %s:%d\r\n\r\n",
            base, constraint, server, port);

    if(debug)
    {
        printf("DEBUG> request = [%s]\n", request);
        fflush(stdout);
    }

    send(sock, request, strlen(request), 0);


    /* And read all the lines coming back */

    count = 0;

    while(1)
    {
        /* Read lines returning from service */

        if(readline (sock, line) == 0)
            break;

        if(debug)
        {
            printf("DEBUG> return; [%s]\n", line);
            fflush(stdout);
        }

        if(strncmp(line, "ERROR: ", 7) == 0)
        {
            if(line[strlen(line)-1] == '\n')
                line[strlen(line)-1]  = '\0';

            printf("[struct stat=\"ERROR\", msg=\"%s\"]\n", line+7);
            exit(0);
        }
        else
        {
            fprintf(fout, "%s", line);
            fflush(fout);

            if(line[0] != '|'
                    && line[0] != '\\')
                ++count;
        }
    }

    fclose(fout);

    printf("[struct stat=\"OK\", count=\"%d\"]\n", count);
    fflush(stdout);

    exit(0);
}
Пример #17
0
int Application::run()
{
    std::cout << "***********************************************************" << std::endl <<
                 "* ON  Server  v" << MACRO_STR(DETECTED_ON_VERSION) <<
                            "    (built on " << MACRO_STR(BUILD_DATE) << ")" << std::endl <<
                 "* (c) Copyright 2009 - " << MACRO_STR(BUILD_YEAR) << " IWStudio" << std::endl <<
                 "* Released under GNU General Public License, vesion 2" << std::endl <<
                 "*" << std::endl <<
                 std::endl;


    _INFO(_logModule, "ON Server Starting Up...");
    setApplicationName("ONCoreServer");
    setApplicationVersion(MACRO_STR(DETECTED_ON_VERSION));
    setOrganizationName("IWStudio");
    setOrganizationDomain("iwstudio.hu");

    _INFO(_logModule, "Installing signal handlers");
    connect(new Common::UnixSignalHandler(SIGHUP, this),
            SIGNAL(CoughtSignal()), SLOT(quit()));
    connect(new Common::UnixSignalHandler(SIGINT, this),
            SIGNAL(CoughtSignal()), SLOT(quit()));
    connect(new Common::UnixSignalHandler(SIGQUIT, this),
            SIGNAL(CoughtSignal()), SLOT(quit()));
    connect(new Common::UnixSignalHandler(SIGTERM, this),
            SIGNAL(CoughtSignal()), SLOT(quit()));

    _INFO(_logModule, "Parsing commandline arguments");

    _INFO(_logModule, "Loading config file");

    _INFO(_logModule, "Setting up logger");
    Common::Logger::Instance()->SetLogToStdout(true);
    Common::Logger::Instance()->SetStdoutLogLevel(Common::Logger::Level::Trace);
    Common::Logger::Instance()->SetFileLogLevel(Common::Logger::Level::Trace);
    Common::Logger::Instance()->SetLogFormat(Common::Logger::Format::Csv);
    Common::Logger::Instance()->SetLogFile(QString(getenv("HOME")).append("/ONServerCore.log"));
    Common::Logger::Instance()->FlushStartupBuffer();

    _INFO(_logModule, "Setting up command interface");
    ServerCore::CommandInterface commander;
    connect(&commander, SIGNAL(Quit()), SLOT(quit()));

    _INFO(_logModule, "Starting Readline");
    ServerCore::Readline readline("on> ");
    readline.connect(Common::Logger::Instance().data(), SIGNAL(BeforeLogLine()), SLOT(Disable()),
                     Qt::DirectConnection);
    readline.connect(Common::Logger::Instance().data(), SIGNAL(AfterLogLine()), SLOT(Enable()),
                     Qt::DirectConnection);
    connect(&readline, SIGNAL(EndSignal()), SLOT(quit()));
    commander.connect(&readline, SIGNAL(LineRead(QString)), SLOT(ProcessCommand(QString)));

    _INFO(_logModule, "Start listening");
    ServerCore::Listener listener;
    listener.listen(3214);

    _INFO(_logModule, "ON Server Startup Complete");
    int exitCode = QCoreApplication::exec();
    _INFO(_logModule, "ON Server Shutting Down...");

    Common::Logger::Instance()->disconnect(&readline);
    readline.Disable();

    return exitCode;
}
Пример #18
0
void build(char *filename) {
  FILE *database = fopen(filename, "r");
  while (!(feof(database))){
    if (first) {
      Node newNode = malloc(sizeof(struct node)); // allocate memory for newNode
      readline(buffer, 128, database); // reads up to 128 characters and stores it in buffer
      newNode->key = malloc(strlen(buffer) + 1); // allocate memory for key
      strcpy(newNode->key, buffer); // copy string from buffer to key
    
      readline(buffer, 128, database); // reads up to 128 characters and stores it in buffer
      newNode->value = malloc(strlen(buffer) + 1); // allocate memory for value 
      strcpy(newNode->value, buffer); // copy string from buffer to value
    
      newNode->left = NULL;
      newNode->right = NULL;
      root = newNode;
      printf("%s and %s placed in root\n",newNode->key, newNode->value);
      first = 0;
    }
    
    done = 0;
    temp = root;
    Node newNode = malloc(sizeof(struct node)); // allocate memory for newNode
    readline(buffer, 128, database); // reads up to 128 characters and stores it in buffer
    if (!count){
      newNode->key = malloc(strlen(buffer) + 1); // allocate memory for key
      strcpy(newNode->key, buffer); // copy string from buffer to key

      readline(buffer, 128, database); // reads up to 128 characters and stores it in buffer
      newNode->value = malloc(strlen(buffer) + 1); // allocate memory for value 
      strcpy(newNode->value, buffer); // copy string from buffer to value

      newNode->left = NULL;
      newNode->right = NULL;

      while(!done) {
        if (strcmp(temp->key, newNode->key) < 0) {
          if (temp->right == NULL){
            temp->right = newNode;
            printf("%s and %s was placed to the right\n", newNode->key, newNode->value);
            done = 1;
          }
          else {
            temp = temp->right;
            printf("Continue to the right\n");
          }
        }
 
        else {
          if (temp->left == NULL){
            temp->left = newNode;
            printf("%s and %s was placed to the left\n", newNode->key, newNode->value);
            done = 1;
          }
          else{
            temp = temp->left;
            printf("Continue to the left\n");
          }
        }
      }
    } else break;

  }

}
Пример #19
0
int main(int argc, char **argv)
{
	char *input_file = NULL;
	input_file = (char*)malloc(sizeof(char)*1024);
	int machines = 1;
	double epsilon = 0.001;
	if(argc != 6) exit_main();
	for(int i=1;i<argc-1;i++)
	{
		if(argv[i][0]!='-')
		{
			exit_main();
		}
		i++;
		switch(argv[i-1][1])
		{
		case 'p':
			machines = atoi(argv[i]);
			break;
		case 'e':
			epsilon = atof(argv[i]);
			break;
		default:
			fprintf(stderr,"unknow options:-%s\n",argv[i-1]);
			exit_main();
			break;
		}
	}
	strcpy(input_file, argv[argc-1]);
	FILE *fp = fopen(input_file,"r");
    printf("Split the data......\n");
	int *query = NULL;
	int k = 0;
	int nr_query = 1;
	int l = 0;
	struct Query_Info *q_info = NULL;
	int *nr_in_machine = NULL;
	struct Query_Machine *query_machine = NULL;
	nr_in_machine = (int*)malloc(sizeof(int)*machines);
	for(int i=0;i<machines;i++)
		nr_in_machine[i] = 0;
	if(fp==NULL)
	{
		fprintf(stderr, "can't open input file %s\n",input_file);
		exit(1);
	}
	max_line_len = 1024;
	line = Malloc(char,max_line_len);
	while(readline(fp)!=NULL)
	{
		l++;
	}
	rewind(fp);
	fclose(fp);
	//printf("l=%d\n",l);
	//exit(1);
	query = (int*)malloc(sizeof(int)*l);
	statistic_queries(input_file, query, l);
	qsort(query, l, sizeof(int), compare_query);// in decending order
	//for(int i=0;i<l;i++)
		//printf("query:%d\n",query[i]);
	//exit(1);
	for(int j=1;j<l;j++)
	{
		if(query[j] != query[j-1])
			nr_query++;
	}
	//printf("nr_query=%d",nr_query);
	//exit(1);
    //
	q_info = (struct Query_Info *)malloc(sizeof(Query_Info)*nr_query);
	q_info[0].query = query[0];
	for(int j=0;j<nr_query;j++)
	{
		q_info[j].num = 0;
		q_info[j].selected = false;
		q_info[j].machine_id = INF;
	}
	// calculate the number of instances for each query.
	for(int j=0;j<l;j++)
	{
		if(query[j]==q_info[k].query)
		{
			q_info[k].num++;
		}
		else
		{
			k++;
			q_info[k].query = query[j];
			q_info[k].num++;
		}
	}
	//address the imbalance issue. i.e., different computing nodes will get almost
    //the same number of instances.
	//solve_imbalance_issue(q_info, nr_query, machines, l, epsilon, nr_in_machine);
    printf("Slove the imbalance issue.\n");
	query_machine = (Query_Machine*)malloc(sizeof(Query_Machine)*nr_query);
	address_imbalance_doublelist(q_info, nr_query, machines, l, epsilon, nr_in_machine, query_machine);
	//for(int i=0;i<machines;i++)
		//printf("nr_in_machine[%d]=%d\n",i,nr_in_machine[i]);
	//exit(1);
	//for(int i=0;i<nr_query;i++)
		//printf("query:%d->machined_id:%d\n",q_info[i].query,q_info[i].machine_id);
    //exit(1);

	double average = (double) l/machines;	 
	 for(int i=0;i<machines;i++)
	 {
		 printf("Instance Count: %d in Machine %d* ",nr_in_machine[i], i);
		 printf("Difference:%d* ", nr_in_machine[i]-(int)average);
         printf("Difference Rate:%f%\n",((double)nr_in_machine[i]-average)/average*100);
     }


	//split the input file
	split(input_file, l, machines, nr_query, query_machine, query);
	printf("The splited data have been completed!!\n");
    //free the assigned memory
	//system("cd temp_dir/");
    //system("ls");
    //system("cd ..");
    //system("rm -r temp_dir");
    free(q_info);
    free(nr_in_machine);
    free(query_machine);
	free(query);
	free(line);
	free(input_file);
	return 0;
}
Пример #20
0
static void configure_host(int host_num, int hasdefault)
{
	char *input;
	char password[128];
	int i;

	struct {
		char *parameter_name;
		char **variable;
		char *message;
	} question_table[] = {
		{ "HostName",     config.host_name,
		  _("Enter remote host name or IP address. (e.g., ftp.myhost.org, 192.168.0.1)\n") },
		{ "LoginName",    config.login_name,
		  _("Enter login name of the account.\n"), },
		{ "Password",     config.password,
		  _("Enter password granting access to the account.\n"), },
		{ "LocalTopDir",  config.local_top_dir,
		  _("Enter local top directory. It must be specified as absolute path.\n(e.g., /home/foo/www)\n"), },
		{ "RemoteTopDir", config.remote_top_dir,
		  _("Enter remote top directory. It must be specified as absolute path.\n(e.g., /public_html)\n"), },
	};

	for (i = 0; i < sizeof(question_table) / sizeof(question_table[0]); i++) {
		printf(question_table[i].message);

		if (strcmp(question_table[i].parameter_name, "Password") == 0) {
			for (;;) {
				if (hasdefault == DEFAULT_EXIST) {
					printf(_("Just press enter to leave default. (default is: ********)\n"));
				}
				input = getpass(">");
				if (input[0] == '\0') {
					if (hasdefault == DEFAULT_EXIST) {
						printf(_("Not changed.\n"));
						break;
					}
					continue;
				}
				strcpy(password, input);
				printf(_("\nRetype password for confirmation.\n"));
				input = getpass(">");
				if (strcmp(password, input) != 0) {
					printf(_("\nPasswords do not match.\n\n"));
					printf(question_table[i].message);
					continue;
				}
				cfgStoreValue(config_table, question_table[i].parameter_name, input, CFG_INI, host_num);
				break;
			}
		} else {
			if (hasdefault == DEFAULT_EXIST) {
				printf(_("Just press enter to leave default. (default is: %s)\n"), question_table[i].variable[host_num]);
			}
			for (;;) {
#ifdef HAVE_LIBREADLINE
				input = readline(">");
#else
				printf(">");
				input = str_fgets(stdin);
#endif
				if (input[0] != '\0') {
					cfgStoreValue(config_table, question_table[i].parameter_name, input, CFG_INI, host_num);
					break;
				} else {
					free(input);
					if (hasdefault == DEFAULT_EXIST) {
						printf(_("Not changed.\n"));
						break;
					}
				}
			}
		}
		printf("\n");
	}
}
Пример #21
0
int main(int argc, char **argv)
{
    const char *lua_init = "init.lua";
    std::vector< std::pair< exec_type, std::string > > startup_cmds;
    // parse command line
    while(1)
    {
        static struct option long_options[] =
        {
            {"help", no_argument, 0, '?'},
            {"quiet", no_argument, 0, 'q'},
            {0, 0, 0, 0}
        };

        int c = getopt_long(argc, argv, "?qi:e:f:", long_options, NULL);
        if(c == -1)
            break;
        switch(c)
        {
            case -1:
                break;
            case 'q':
                g_quiet = true;
                break;
            case '?':
                usage();
                break;
            case 'i':
                lua_init = optarg;
                break;
            case 'e':
                startup_cmds.push_back(std::make_pair(exec_cmd, std::string(optarg)));
                break;
            case 'f':
                startup_cmds.push_back(std::make_pair(exec_file, std::string(optarg)));
                break;
            default:
                abort();
        }
    }

    // load register descriptions
    std::vector< soc_t > socs;
    for(int i = optind; i < argc; i++)
    {
        socs.push_back(soc_t());
        if(!soc_desc_parse_xml(argv[i], socs[socs.size() - 1]))
        {
            printf("Cannot load description '%s'\n", argv[i]);
            return 2;
        }
    }

    // create usb context
    libusb_context *ctx;
    libusb_init(&ctx);
    libusb_set_debug(ctx, 3);

    // look for device
    if(!g_quiet)
        printf("Looking for hwstub device ...\n");
    // open first device
    libusb_device **list;
    ssize_t cnt = hwstub_get_device_list(ctx, &list);
    if(cnt <= 0)
    {
        printf("No device found\n");
        return 1;
    }
    libusb_device_handle *handle;
    if(libusb_open(list[0], &handle) != 0)
    {
        printf("Cannot open device\n");
        return 1;
    }
    libusb_free_device_list(list, 1);

    // admin stuff
    libusb_device *mydev = libusb_get_device(handle);
    if(!g_quiet)
    {
        printf("device found at %d:%d\n",
            libusb_get_bus_number(mydev),
            libusb_get_device_address(mydev));
    }
    g_hwdev = hwstub_open(handle);
    if(g_hwdev == NULL)
    {
        printf("Cannot open device!\n");
        return 1;
    }

    // get hwstub information
    int ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_VERSION, &g_hwdev_ver, sizeof(g_hwdev_ver));
    if(ret != sizeof(g_hwdev_ver))
    {
        printf("Cannot get version!\n");
        goto Lerr;
    }
    if(g_hwdev_ver.bMajor != HWSTUB_VERSION_MAJOR || g_hwdev_ver.bMinor < HWSTUB_VERSION_MINOR)
    {
        printf("Warning: this tool is possibly incompatible with your device:\n");
        printf("Device version: %d.%d.%d\n", g_hwdev_ver.bMajor, g_hwdev_ver.bMinor, g_hwdev_ver.bRevision);
        printf("Host version: %d.%d\n", HWSTUB_VERSION_MAJOR, HWSTUB_VERSION_MINOR);
    }

    // get memory layout information
    ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_LAYOUT, &g_hwdev_layout, sizeof(g_hwdev_layout));
    if(ret != sizeof(g_hwdev_layout))
    {
        printf("Cannot get layout: %d\n", ret);
        goto Lerr;
    }

    // get target
    ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_TARGET, &g_hwdev_target, sizeof(g_hwdev_target));
    if(ret != sizeof(g_hwdev_target))
    {
        printf("Cannot get target: %d\n", ret);
        goto Lerr;
    }

    // get STMP specific information
    if(g_hwdev_target.dID == HWSTUB_TARGET_STMP)
    {
        ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_STMP, &g_hwdev_stmp, sizeof(g_hwdev_stmp));
        if(ret != sizeof(g_hwdev_stmp))
        {
            printf("Cannot get stmp: %d\n", ret);
            goto Lerr;
        }
    }

    // get PP specific information
    if(g_hwdev_target.dID == HWSTUB_TARGET_PP)
    {
        ret = hwstub_get_desc(g_hwdev, HWSTUB_DT_PP, &g_hwdev_pp, sizeof(g_hwdev_pp));
        if(ret != sizeof(g_hwdev_pp))
        {
            printf("Cannot get pp: %d\n", ret);
            goto Lerr;
        }
    }
    /** Init lua */

    // create lua state
    g_lua = luaL_newstate();
    if(g_lua == NULL)
    {
        printf("Cannot create lua state\n");
        return 1;
    }
    // import hwstub
    if(!my_lua_import_hwstub())
        printf("Cannot import hwstub description into Lua context\n");
    // open all standard libraires
    luaL_openlibs(g_lua);
    // import socs
    if(!my_lua_import_soc(socs))
        printf("Cannot import SoC descriptions into Lua context\n");

    if(luaL_dofile(g_lua, lua_init))
        printf("error in init: %s\n", lua_tostring(g_lua, -1));
    lua_pop(g_lua, lua_gettop(g_lua));

    /** start interactive mode */
    if(!g_quiet)
        printf("Starting interactive lua session. Type 'help()' to get some help\n");

    /** run startup commands */
    for(size_t i = 0; i < startup_cmds.size(); i++)
    {
        bool ret = false;
        if(!g_quiet)
            printf("Running '%s'...\n", startup_cmds[i].second.c_str());
        if(startup_cmds[i].first == exec_file)
            ret = luaL_dofile(g_lua, startup_cmds[i].second.c_str());
        else if(startup_cmds[i].first == exec_cmd)
            ret = luaL_dostring(g_lua, startup_cmds[i].second.c_str());
        if(ret)
            printf("error: %s\n", lua_tostring(g_lua, -1));
    }

    // use readline to provide some history and completion
    rl_bind_key('\t', rl_complete);
    while(!g_exit)
    {
        char *input = readline("> ");
        if(!input)
            break;
        add_history(input);
        // evaluate string
        if(luaL_dostring(g_lua, input))
            printf("error: %s\n", lua_tostring(g_lua, -1));
        // pop everything to start from a clean stack
        lua_pop(g_lua, lua_gettop(g_lua));
        free(input);
    }

    Lerr:
    // display log if handled
    if(!g_quiet)
        printf("Device log:\n");
    print_log(g_hwdev);
    hwstub_release(g_hwdev);
    return 1;
}
Пример #22
0
void read_problem(const char *filename)
{
	int elements, max_index, inst_max_index, i, j;
	FILE *fp = fopen(filename,"r");
	char *endptr;
	char *idx, *val, *label;

	if(fp == NULL)
	{
		fprintf(stderr,"can't open input file %s\n",filename);
		exit(1);
	}

	prob.l = 0;
	elements = 0;

	max_line_len = 1024;
	line = Malloc(char,max_line_len);
	while(readline(fp)!=NULL)
	{
		char *p = strtok(line," \t"); // label

		// features
		while(1)
		{
			p = strtok(NULL," \t");
			if(p == NULL || *p == '\n') // check '\n' as ' ' may be after the last feature
				break;
			++elements;
		}
		++elements;
		++prob.l;
	}
	rewind(fp);

	prob.y = Malloc(double,prob.l);
	prob.x = Malloc(struct svm_node *,prob.l);
	x_space = Malloc(struct svm_node,elements);

	max_index = 0;
	j=0;
	for(i=0;i<prob.l;i++)
	{
		inst_max_index = -1; // strtol gives 0 if wrong format, and precomputed kernel has <index> start from 0
		readline(fp);
		prob.x[i] = &x_space[j];
		label = strtok(line," \t\n");
		if(label == NULL) // empty line
			exit_input_error(i+1);

		prob.y[i] = strtod(label,&endptr);
		if(endptr == label || *endptr != '\0')
			exit_input_error(i+1);

		while(1)
		{
			idx = strtok(NULL,":");
			val = strtok(NULL," \t");

			if(val == NULL)
				break;

			errno = 0;
			x_space[j].index = (int) strtol(idx,&endptr,10);
			if(endptr == idx || errno != 0 || *endptr != '\0' || x_space[j].index <= inst_max_index)
				exit_input_error(i+1);
			else
				inst_max_index = x_space[j].index;

			errno = 0;
			x_space[j].value = strtod(val,&endptr);
			if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr)))
				exit_input_error(i+1);

			++j;
		}

		if(inst_max_index > max_index)
			max_index = inst_max_index;
		x_space[j++].index = -1;
	}

	if(param.gamma == 0 && max_index > 0)
		param.gamma = 1.0/max_index;
	if(param.C == 0)
	{
		if (param.svm_type == SVDD && prob.l > 0)
			param.C = 2.0/prob.l;
		else
			param.C = 1;
	}

	if(param.kernel_type == PRECOMPUTED)
		for(i=0;i<prob.l;i++)
		{
			if (prob.x[i][0].index != 0)
			{
				fprintf(stderr,"Wrong input format: first column must be 0:sample_serial_number\n");
				exit(1);
			}
			if ((int)prob.x[i][0].value <= 0 || (int)prob.x[i][0].value > max_index)
			{
				fprintf(stderr,"Wrong input format: sample_serial_number out of range\n");
				exit(1);
			}
		}

	fclose(fp);
}
Пример #23
0
void tloop(int history)
{
	using_history();
	stifle_history(history);

	lookf(self.next);

	while(1){
		int fail = 0;
		struct tobj *prev = NULL;
		struct tobj *noun = NULL;
		char *input = readline(">> ");
		char *verbstr = input;
		char *nounstr = verbstr;
		add_history(verbstr);

		/* Blank out spaces and punctuation and set the noun as the last word */
		while(*input){
			if(!isalpha(*input)){
				*input = '\0';
				if(isalpha(*(input + 1))){
					nounstr = input + 1;
				}
			}
			++input;
		}
		input = verbstr; /* Restore input back to where it was */

		/* Do basic substition for shortcut commands */
		if(tstrequals(verbstr, 2, "n", "north")){
			verbstr = "go";
			nounstr = "north";
		}
		else if(tstrequals(verbstr, 2, "ne", "northeast")){
			verbstr = "go";
			nounstr = "northeast";
		}
		else if(tstrequals(verbstr, 2, "e", "east")){
			verbstr = "go";
			nounstr = "east";
		}
		else if(tstrequals(verbstr, 2, "se", "southeast")){
			verbstr = "go";
			nounstr = "southeast";
		}
		else if(tstrequals(verbstr, 2, "s", "south")){
			verbstr = "go";
			nounstr = "south";
		}
		else if(tstrequals(verbstr, 2, "sw", "southwest")){
			verbstr = "go";
			nounstr = "southwest";
		}
		else if(tstrequals(verbstr, 2, "w", "west")){
			verbstr = "go";
			nounstr = "west";
		}
		else if(tstrequals(verbstr, 2, "nw", "northwest")){
			verbstr = "go";
			nounstr = "northwest";
		}
		else if(tstrequals(verbstr, 1, "out")){
			verbstr = "go";
			nounstr = "out";
		}

		noun = tfind(&self, &prev, nounstr);
		if(noun == NULL){
			if(verbstr != nounstr){
				if(tstrequals(verbstr, 2, "go", "travel")){
					printf("You can't go ``%s'' here.\n", nounstr);
				}
				else{
					printf("You don't see ``%s'' here.\n", nounstr);
				}
				fail = 1;
			}
			else{
				prev = NULL;
				noun = self.next;
			}
		}
		if(!fail){
			if(tstrcmp(verbstr, "look") == 0){
				lookf(noun);
			}
			else if(tstrequals(verbstr, 2, "i", "inventory")){
				lookf(&self);
			}
			else if(tstrequals(verbstr, 3, "eat", "consume", "ingest")){
				eatf(prev, noun);
			}
			else if(tstrequals(verbstr, 2, "go", "travel")){
				gof(noun);
			}
			else if(tstrequals(verbstr, 3, "drop", "leave", "abandon")){
				dropf(prev, noun);
			}
			else if(tstrequals(verbstr, 3, "talk", "say", "speak")){
				talkf(noun);
			}
			else if(tstrequals(verbstr, 6, "break", "smash", "kick", "punch", "headbutt", "kill")){
				breakf(noun);
			}
			else if(tstrcmp(verbstr, "unlock") == 0){
				unlockf(noun);
			}
			else if(tstrequals(verbstr, 2, "lock", "bar")){
				lockf(noun);
			}
			else if(tstrequals(verbstr, 5, "pick", "get", "take", "steal", "pack")){
				pickf(prev, noun);
			}
			else{
				printf("Don't know how to ``%s.''\n", verbstr);
				fail = 1;
			}
		}
		free(input);
	}
}
Пример #24
0
int srec2bin(int argc,char *argv[],int verbose)
{
    int i,rlen,sts;
    FILE *fp;
    char ac;
    char buff[256];
    bit32u TAG_BIG     = 0xDEADBE42;
    bit32u TAG_LITTLE  = 0xFEEDFA42;

    bit32u Tag;

  
    if(argc < 3)
    {
      printf("\nError: <srec2bin <srec input file> <bin output file>\n\n");
      return(0);
    }
  
    if (argc > 3) BigEndian=TRUE; else BigEndian=FALSE;

    if (BigEndian)
        Tag = TAG_BIG;
    else
        Tag = TAG_LITTLE;

    if (verbose)
       printf("\nEndian: %s, Tag is 0x%8X\n",(BigEndian)?"BIG":"LITTLE", Tag);

    fp = fopen(argv[1],"rt");

    if (fp==NULL)
    {
      printf("\nError: Opening input file, %s.", argv[1]);
      return(0);
    }
  
    fOut = fopen( argv[2], "wb");
    
    if (fOut==NULL)
    {
      printf("\nError: Opening Output file, %s.", argv[2]);
      if(fp) fclose(fp);
      return(0);
    }
 
    RecStart = FALSE;

    AddressCurrent = 0xFFFFFFFFL;

    // Setup Tag 
  
    dumpfTell("Tag", Tag);

    binOut32(Tag);

  
    inputline=0;
    sts=TRUE;

    rlen = readline(fp,buff,sizeof buff);

    while( (sts) && (rlen != -1))
    {
        if (strlen(buff))
        {
            sts &= srecLine(buff);
            WaitDisplay();
        }
       rlen = readline(fp,buff,sizeof buff);
    }

  
  //  printf("PC: 0x%08X, Length 0x%08X, Tag 0x%08X\n", ProgramStart, RecLength, TAG_LITTLE);
  
    binRecEnd();

    if(fp) fclose(fp);
    if(fOut) fclose(fOut);

    return(1);
}
Пример #25
0
 virtual int readline(char* buf, int maxlen, IMultiException *me)
 { return readline(buf, maxlen, false, me); }
Пример #26
0
int main(int argc, char* argv[])
{

    int i , maxi , maxfd , listenfd , connfd , sockfd ;
    int nready , client[ FD_SETSIZE ] ;
    ssize_t n ;
    fd_set rset , allset ;
    char buf [ MAXLINE ];
    socklen_t clilen ;
    struct sockaddr_in cliaddr , servaddr ;

		//creat socket
    listenfd = socket( AF_INET , SOCK_STREAM , 0 );
		//set socket
    bzero(&servaddr , sizeof( servaddr ));
    servaddr.sin_family = AF_INET ;
    servaddr.sin_addr.s_addr = htonl( INADDR_ANY );
    servaddr.sin_port = htons( SERV_PORT ) ;
		//bind port
    bind(listenfd , (SA*) &servaddr ,sizeof(servaddr) );
		//listen port listenfd
    listen(listenfd , 10 );  // max client is 10
		//consider maxfd 
    maxfd = listenfd ;
    //initial maxi which is num of fd
		maxi = -1;
		//all client port is closed now
    for(i = 0; i < FD_SETSIZE ; i++) client[i] = -1 ;
    
		//initial select set
		FD_ZERO(&allset);
		//wait listenfd which is in allset when select
    FD_SET(listenfd , &allset );

    printf("ready to wait \n listenfd=%d",listenfd);

    for(;;)
    {
        rset = allset ;
				//nready is the fd ready to ready
        nready = select( maxfd + 1 , &rset , NULL , NULL , NULL );

        if(FD_ISSET(listenfd , &rset) ){
						//connect to ready client
            clilen = sizeof( cliaddr ) ;
            connfd = accept( listenfd , (SA* )&cliaddr , &clilen );

            printf("start to read: \n");
						//sav fd to client[i]
            for(i = 0 ; i<FD_SETSIZE; i++){
                if(client[i]<0) {
                    client[i] = connfd;
                    break;
                }
						}
            //if full, exit
						if(i == FD_SETSIZE){
                printf("too many client\n");
                exit(0);
            }
						//wait connfd when select
            FD_SET(connfd, &allset);
            if(connfd > maxfd )maxfd = connfd;
            if(i > maxi )maxi = i;
            if(--nready <= 0)continue;
        }
				//seek connected socket
				for(i=0;i<=maxi;i++){
            if( (sockfd = client[i]) < 0 )continue;
            if(FD_ISSET(sockfd,&rset)){
                if((n = readline(sockfd , buf , MAXLINE )) == 0 )
                {
                    close(sockfd);
                    FD_CLR(sockfd , &allset );
                    client[i] = -1;
                }
                else if(n>0){
									int k;
									//write messege to all client
									printf("%s",buf);
									for(k=0;k<=maxi;k++){
										if(client[k]!=-1){
											printf("write in k=%d\n",k);
											if((write(client[k] , buf , n))!=n)printf("write error!\n");
										}
									}
                }
								else if (n<0)printf("error!\n");	
								if(--nready <= 0) break;
            }

        }

    }


}
Пример #27
0
int
kswitch(struct kswitch_options *opt, int argc, char **argv)
{
    krb5_error_code ret;
    krb5_ccache id = NULL;

    if (opt->cache_string && opt->principal_string)
	krb5_errx(kcc_context, 1,
		  N_("Both --cache and --principal given, choose one", ""));

    if (opt->interactive_flag) {
	krb5_cc_cache_cursor cursor;
	krb5_ccache *ids = NULL;
	size_t i, len = 0;
	char *name;
	rtbl_t ct;

	ct = rtbl_create();

	rtbl_add_column_by_id(ct, 0, "#", 0);
	rtbl_add_column_by_id(ct, 1, "Principal", 0);
	rtbl_set_column_affix_by_id(ct, 1, "    ", "");
        rtbl_add_column_by_id(ct, 2, "Type", 0);
        rtbl_set_column_affix_by_id(ct, 2, "  ", "");

	ret = krb5_cc_cache_get_first(kcc_context, NULL, &cursor);
	if (ret)
	    krb5_err(kcc_context, 1, ret, "krb5_cc_cache_get_first");

	while (krb5_cc_cache_next(kcc_context, cursor, &id) == 0) {
	    krb5_principal p;
	    char num[10];

	    ret = krb5_cc_get_principal(kcc_context, id, &p);
	    if (ret)
		continue;

	    ret = krb5_unparse_name(kcc_context, p, &name);
	    krb5_free_principal(kcc_context, p);

	    snprintf(num, sizeof(num), "%d", (int)(len + 1));
	    rtbl_add_column_entry_by_id(ct, 0, num);
	    rtbl_add_column_entry_by_id(ct, 1, name);
            rtbl_add_column_entry_by_id(ct, 2, krb5_cc_get_type(kcc_context, id));
	    free(name);

	    ids = erealloc(ids, (len + 1) * sizeof(ids[0]));
	    ids[len] = id;
	    len++;
	}
	krb5_cc_cache_end_seq_get(kcc_context, cursor);

	rtbl_format(ct, stdout);
	rtbl_destroy(ct);

	name = readline("Select number: ");
	if (name) {
	    i = atoi(name);
	    if (i == 0)
		krb5_errx(kcc_context, 1, "Cache number '%s' is invalid", name);
	    if (i > len)
		krb5_errx(kcc_context, 1, "Cache number '%s' is too large", name);

	    id = ids[i - 1];
	    ids[i - 1] = NULL;
	} else
	    krb5_errx(kcc_context, 1, "No cache selected");
	for (i = 0; i < len; i++)
	    if (ids[i])
		krb5_cc_close(kcc_context, ids[i]);

    } else if (opt->principal_string) {
	krb5_principal p;

	ret = krb5_parse_name(kcc_context, opt->principal_string, &p);
	if (ret)
	    krb5_err(kcc_context, 1, ret, "krb5_parse_name: %s",
		     opt->principal_string);

	ret = krb5_cc_cache_match(kcc_context, p, &id);
	if (ret)
	    krb5_err(kcc_context, 1, ret,
		     N_("Did not find principal: %s", ""),
		     opt->principal_string);

	krb5_free_principal(kcc_context, p);

    } else if (opt->cache_string) {
	const krb5_cc_ops *ops;
	char *str;

	ops = krb5_cc_get_prefix_ops(kcc_context, opt->type_string);
	if (ops == NULL)
	    krb5_err(kcc_context, 1, 0, "krb5_cc_get_prefix_ops");

	asprintf(&str, "%s:%s", ops->prefix, opt->cache_string);
	if (str == NULL)
	    krb5_errx(kcc_context, 1, N_("out of memory", ""));

	ret = krb5_cc_resolve(kcc_context, str, &id);
	if (ret)
	    krb5_err(kcc_context, 1, ret, "krb5_cc_resolve: %s", str);

	free(str);
    } else {
	krb5_errx(kcc_context, 1, "missing option for kswitch");
    }

    ret = krb5_cc_switch(kcc_context, id);
    if (ret)
	krb5_err(kcc_context, 1, ret, "krb5_cc_switch");

    return 0;
}
Пример #28
0
int
main (int argc, char **argv)
{
  logical labels_saved, printing, header, first, last_was_blank_line;
  time_t ltoday;
  struct tm *tm;
  char *labels, *p, *today;
  struct linebuffer data;

#ifdef MSDOS
  _fmode = O_BINARY;		/* all of files are treated as binary files */
#if __DJGPP__ > 1
  if (!isatty (fileno (stdout)))
    setmode (fileno (stdout), O_BINARY);
  if (!isatty (fileno (stdin)))
    setmode (fileno (stdin), O_BINARY);
#else /* not __DJGPP__ > 1 */
  (stdout)->_flag &= ~_IOTEXT;
  (stdin)->_flag &= ~_IOTEXT;
#endif /* not __DJGPP__ > 1 */
#endif
  progname = argv[0];

  while (1)
    {
      int opt = getopt_long (argc, argv, "hV", longopts, 0);
      if (opt == EOF)
	break;

      switch (opt)
	{
	case 'V':
	  printf ("%s (GNU Emacs %s)\n", "b2m", VERSION);
	  puts ("b2m is in the public domain.");
	  exit (EXIT_SUCCESS);

	case 'h':
	  fprintf (stderr, "Usage: %s <babylmailbox >unixmailbox\n", progname);
	  exit (EXIT_SUCCESS);
	}
    }

  if (optind != argc)
    {
      fprintf (stderr, "Usage: %s <babylmailbox >unixmailbox\n", progname);
      exit (EXIT_SUCCESS);
    }

  labels_saved = printing = header = last_was_blank_line = FALSE;
  first = TRUE;
  ltoday = time (0);
  /* Convert to a string, checking for out-of-range time stamps.
     Don't use 'ctime', as that might dump core if the hardware clock
     is set to a bizarre value.  */
  tm = localtime (&ltoday);
  if (! (tm && TM_YEAR_IN_ASCTIME_RANGE (tm->tm_year)
	 && (today = asctime (tm))))
    fatal ("current time is out of range");
  data.size = 200;
  data.buffer = xnew (200, char);

  if (readline (&data, stdin) == 0
      || !strneq (data.buffer, "BABYL OPTIONS:", 14))
    fatal ("standard input is not a Babyl mailfile.");

  while (readline (&data, stdin) > 0)
    {
      if (streq (data.buffer, "*** EOOH ***") && !printing)
	{
	  printing = header = TRUE;
	  printf ("From \"Babyl to mail by %s\" %s", progname, today);
	  continue;
	}

      if (data.buffer[0] == '\037')
	{
	  if (data.buffer[1] == '\0')
	    continue;
	  else if (data.buffer[1] == '\f')
	    {
	      if (first)
		first = FALSE;
	      else if (! last_was_blank_line)
		puts("");
	      /* Save labels. */
	      readline (&data, stdin);
	      p = strtok (data.buffer, " ,\r\n\t");
	      labels = "X-Babyl-Labels: ";

	      while ((p = strtok (NULL, " ,\r\n\t")))
		labels = concat (labels, p, ", ");

	      p = &labels[strlen (labels) - 2];
	      if (*p == ',')
		*p = '\0';
	      printing = header = FALSE;
	      labels_saved = TRUE;
	      continue;
	    }
	}

      if ((data.buffer[0] == '\0') && header)
	{
	  header = FALSE;
	  if (labels_saved)
	    puts (labels);
	}

      if (printing)
	{
	  puts (data.buffer);
	  if (data.buffer[0] == '\0')
	    last_was_blank_line = TRUE;
	  else
	    last_was_blank_line = FALSE;
	}
    }

  return EXIT_SUCCESS;
}
Пример #29
0
static void set_input_device_filter_array(void )
{
    struct file *fp;
    mm_segment_t fs;
    loff_t pos;
    int read_num = 0;
    int i = 0;
    int j = 0;

    fp = filp_open(HWATE_CONF_FILE, O_RDONLY , 0644);
    if (IS_ERR(fp)) {
        printk(KERN_ERR "%s: open file %s failed\n", __func__, HWATE_CONF_FILE);
        default_set_input_device_filter_array();
        printk(KERN_WARNING "%s: set default value.\n", __func__);
        goto set_input_device_arrary;
    } else {
        fs = get_fs();
        set_fs(KERNEL_DS);
        pos = 0;
        /* Read out the input dev name */
        while (1) {
            read_num = readline(fp, ate_dt->idf.dev_name[ate_dt->idf.filer_total], &pos);
            if (read_num <= 0 || read_num > MAX_SIZE_OF_DEV_NAME ||
                ate_dt->idf.filer_total > MAX_INPUT_DEV) {
                printk(KERN_ERR "%s: read name from %s error\n", __func__, HWATE_CONF_FILE);
                break;
            } else {
                ate_dt->idf.filer_total++;
            }
        }
        /* Close the file */
        filp_close(fp, NULL);
        set_fs(fs);

        for(i = 0; i < ate_dt->idf.filer_total; i++) {
            for(j = 0; j< sizeof(ate_dt->idf.dev_name[i]) - 1; j++) {
                if(' ' == ate_dt->idf.dev_name[i][j]) {
                    ate_dt->idf.dev_name[i][j] = '\0';
                    ate_dt->idf.input_event_type[i] = ( unsigned int ) (ate_dt->idf.dev_name[i][j+1] - '0');
                    if(ate_dt->idf.input_event_type[i] >= MAX_EVENT_TYPE) {
                        printk(KERN_ERR "%s: read error data from %s error\n", __func__, HWATE_CONF_FILE);
                        clean_input_device_filter_array();
                        return ;
                    }
                    break ;
                }
            }
        }

set_input_device_arrary:
        for (i = 0; i < ate_dt->idf.filer_total; i++) {
            for (j = 0; j < ate_dt->ate_dev.input_dev_sum; j++) {
                if (0 == strcmp(ate_dt->idf.dev_name[i], ate_dt->ate_dev.input_dev_table[j]->name)) {
#ifdef ATE_DEBUG
                    printk(KERN_DEBUG "%s: name=%s\n", __func__, ate_dt->idf.dev_name[i]);
                    printk(KERN_DEBUG "%s: i=%d j=%d\n", __func__, i, j);
#endif
                    ate_dt->ate_dev.valid[j] = true;
                    ate_dt->ate_dev.input_event_type[j] = ate_dt->idf.input_event_type[i];
                }
            }
        }
    }

}
Пример #30
0
//------------------------------------------------------------------------------
static char* call_readline_impl(const char* prompt)
{
    static int initialised = 0;
    int expand_result;
    char* text;
    char* expanded;
    char* prepared_prompt;
    char cwd_cache[MAX_PATH];

    // Initialisation
    if (!initialised)
    {
        initialise_clink_settings();
        initialise_lua();
        load_history();

        rl_catch_signals = 0;
        rl_startup_hook = initialise_hook;
        initialised = 1;
    }

    // If no prompt was provided assume the line is prompted already and
    // extract it. If a prompt was provided filter it through Lua.
    prepared_prompt = NULL;
    if (prompt == NULL)
    {
        prepared_prompt = extract_prompt(1);

        // Even though we're not going to display filtered result the extracted
        // prompt is run through Lua. This is a little bit of a hack, but helps
        // to keep behaviour consistent.
        if (prepared_prompt != NULL)
        {
            char buffer[1024];

            str_cpy(buffer, prepared_prompt, sizeof(buffer));
            lua_filter_prompt(buffer, sizeof_array(buffer));
        }
    }
    else
    {
        prepared_prompt = filter_prompt(prompt);
    }

    GetCurrentDirectory(sizeof_array(cwd_cache), cwd_cache);

    // Call readline
    do
    {
        rl_already_prompted = (prompt == NULL);
        text = readline(prepared_prompt ? prepared_prompt : "");
        if (!text)
        {
            goto call_readline_epilogue;
        }

        // Expand history designators in returned buffer.
        expanded = NULL;
        expand_result = expand_from_history(text, &expanded);
        if (expand_result > 0 && expanded != NULL)
        {
            free(text);
            text = expanded;

            // If there was some expansion then display the expanded result.
            if (expand_result > 0)
            {
                hooked_fprintf(NULL, "History expansion: %s\n", text);
            }
        }

        add_to_history(text);
    }
    while (!text || expand_result == 2);

call_readline_epilogue:
    free_prompt(prepared_prompt);
    SetCurrentDirectory(cwd_cache);
    return text;
}