Exemple #1
0
void
fv_gl_init(void)
{
        int sample_buffers = 0;
        int max_vertex_attribs;
        int i;

        memset(&fv_gl, 0, sizeof fv_gl);

        fv_gl.glGetString = SDL_GL_GetProcAddress("glGetString");

        get_gl_version();

        for (i = 0; i < FV_N_ELEMENTS(gl_groups); i++)
                init_group(gl_groups + i);

        fv_gl.have_map_buffer_range = fv_gl.glMapBufferRange != NULL;
        fv_gl.have_vertex_array_objects = fv_gl.glGenVertexArrays != NULL;

        /* On GLES2 (and thus WebGL) non-power-of-two textures are
         * only supported if no mipmaps are used and the repeat mode
         * is CLAMP_TO_EDGE.
         */
#ifdef EMSCRIPTEN
        fv_gl.have_npot_mipmaps = false;
#else
        fv_gl.have_npot_mipmaps = true;
#endif

        fv_gl.have_texture_2d_array =
                SDL_GL_ExtensionSupported("GL_EXT_texture_array");

        fv_gl.glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &max_vertex_attribs);

        fv_gl.have_instanced_arrays =
                fv_gl.glVertexAttribDivisor != NULL &&
                fv_gl.glDrawElementsInstanced != NULL &&
                max_vertex_attribs >= 11;

#ifndef EMSCRIPTEN
        fv_gl.glGetIntegerv(GL_SAMPLE_BUFFERS_ARB, &sample_buffers);
#endif

        fv_gl.have_multisampling = sample_buffers != 0;
}
Exemple #2
0
int
folder_menu(char *path, int mode)
{
    FILE           *folder;
    register article_header *ah;
    news_header_buffer dgbuf;
    char            buffer[256];
    int             more, length, re, menu_cmd, was_raw;
    memory_marker   mem_marker;
    group_header    fake_group;
    int             cc_save;
    char            folder_name[FILENAME], folder_file[FILENAME];
    int             orig_layout;
    char           *orig_hdr_lines;

    orig_layout = fmt_linenum;
    orig_hdr_lines = header_lines;

    strcpy(folder_name, path);
    fake_group.group_name = folder_name;
    fake_group.kill_list = NULL;
    if (!expand_file_name(folder_file, folder_name, 1))
	return ME_NO_REDRAW;
    fake_group.archive_file = path = folder_file;
    fake_group.next_group = fake_group.prev_group = NULL;
    fake_group.group_flag = G_FOLDER | G_FAKED;
    fake_group.master_flag = 0;
    fake_group.save_file = NULL;
    current_group = NULL;
    init_group(&fake_group);

    folder = open_file(path, OPEN_READ);
    if (folder == NULL) {
	msg("%s not found", path);
	return ME_NO_REDRAW;
    }
    switch (get_folder_type(folder)) {
	case 0:
	    msg("Reading: %-.65s", path);
	    break;
	case 1:
	case 2:
	    msg("Reading %s folder: %-.50s",
		current_folder_type == 1 ? "mail" : "mmdf", path);
	    break;
	default:
	    msg("Folder is empty");
	    fclose(folder);
	    return ME_NO_REDRAW;
    }
    rewind(folder);

    was_raw = no_raw();
    s_keyboard = 0;

    current_group = &fake_group;

    mark_memory(&mem_marker);

    ah = alloc_art();

    more = 1;
    while (more && (more = get_digest_article(folder, dgbuf)) >= 0) {
	if (s_keyboard)
	    break;

	ah->a_number = 0;
	ah->flag = A_FOLDER;
	ah->attr = 0;

	ah->lines = digest.dg_lines;

	ah->hpos = digest.dg_hpos;
	ah->fpos = digest.dg_fpos;
	ah->lpos = digest.dg_lpos;

	if (digest.dg_from) {
	    length = pack_name(buffer, digest.dg_from, Name_Length);
	    ah->sender = alloc_str(length);
	    strcpy(ah->sender, buffer);
	    ah->name_length = length;
	    if (mode == 1)
		fold_string(ah->sender);
	} else {
	    ah->sender = "";
	    ah->name_length = 0;
	}

	if (digest.dg_subj) {
	    length = pack_subject(buffer, digest.dg_subj, &re, 255);
	    ah->replies = re;
	    ah->subject = alloc_str(length);
	    strcpy(ah->subject, buffer);
	    ah->subj_length = length;
	    if (mode == 1 && length > 1)
		fold_string(ah->subject + 1);
	} else {
	    ah->replies = 0;
	    ah->subject = "";
	    ah->subj_length = 0;
	}

	ah->t_stamp = digest.dg_date ? pack_date(digest.dg_date) : 0;

	add_article(ah);
	ah = alloc_art();
    }

    fclose(folder);

    if (s_keyboard) {
	menu_cmd = ME_NO_REDRAW;
    } else if (n_articles == 0) {
	msg("Not a folder (no article header)");
	menu_cmd = ME_NO_REDRAW;
    } else {
	if (n_articles > 1) {
	    clrdisp();
	    prompt_line = 2;
	    if (mode == 0 && !dont_sort_folders)
		sort_articles(-1);
	    else if (mode == 1) {
		article_number  n;
		for (n = 0; n < n_articles; n++) {
		    ah = articles[n];
		    if (n == 0)
			ah->flag |= A_ROOT_ART;
		    else if (strcmp(ah->sender, articles[n - 1]->sender) == 0)
			articles[n - 1]->flag |= A_NEXT_SAME;
		    else
			ah->flag |= A_ROOT_ART;
		}
		bypass_consolidation = consolidated_manual ? 2 : 1;
	    } else
		no_sort_articles();
	} else
	    no_sort_articles();

	cc_save = cancel_count;
	cancel_count = 0;
	if (mode == 1) {
	    fmt_linenum = -1;
	    header_lines = "*";
	}
reenter_menu:
	ignore_fancy_select = 1;
	menu_cmd = menu(folder_header);
	ignore_fancy_select = 0;

	if (mode == 0 && cancel_count) {
	    register article_number cur;

	    cancel_count = 0;
	    for (cur = 0; cur < n_articles; cur++) {
		if (articles[cur]->attr == A_CANCEL)
		    cancel_count++;
	    }
	}
	if (mode == 0 && cancel_count) {
	    clrdisp();
	    tprintf("\rFolder: %s\n\rFile:   %s\n\n\r", folder_name, folder_file);
	    if (cancel_count == n_articles)
		tprintf("Cancel all articles and remove folder? ");
	    else
		tprintf("Remove %d article%s from folder? ",
			cancel_count, plural((long) cancel_count));
	    fl;

	    switch (yes(1)) {
		case 1:
		    tprintf("\n\n");
		    if (cancel_count == n_articles) {
			if (unlink(group_path_name) < 0 &&
			    nn_truncate(group_path_name, (off_t) 0) < 0) {
			    tprintf("\rCould not unlink %s\n\r", group_path_name);
			    any_key(0);
			}
		    } else
			rewrite_folder();
		    break;
		case 0:
		    break;
		default:
		    goto reenter_menu;
	    }
	}
	cancel_count = cc_save;
    }

    release_memory(&mem_marker);
    if (fmt_linenum == -1) {
	fmt_linenum = orig_layout;
	header_lines = orig_hdr_lines;
    }
    if (was_raw)
	nn_raw();

    return menu_cmd;
}
Exemple #3
0
/*
 * interface, not static 
 */
void init_filter_tree(int argc) {
  char * exp;
  int exp_num = 0;
  
  init_op_stack(argc);


  filter_list_size = argc;
  filter_list_len = 0;
  filter_list = (Filter **)(malloc(sizeof(Filter) * argc));

  while((exp = get_exp()) != NULL) {
    exp_num++;
    char * optarg;
    //all the exps
    if (IS_EQUAL(exp, "-name")) {
      optarg = _get_arg("-name");
      init_fnmatch(optarg, true);
    } else if (IS_EQUAL(exp, "-iname")) {
      optarg = _get_arg("-iname");
      init_fnmatch(optarg, false);
    } else if (IS_EQUAL(exp, "-user")) {
      optarg = _get_arg("-user");
      init_user(optarg);
    } else if (IS_EQUAL(exp, "-group")) {
      optarg = _get_arg("-group");
      init_group(optarg);
    } else if (IS_EQUAL(exp, "-perm")) {
      optarg = _get_arg("-perm");
      init_perm(optarg);
    } else if (IS_EQUAL(exp, "-regex")) {
      optarg = _get_arg("-regex");
      init_reg(optarg);
    } else if (IS_EQUAL(exp, "-amin")) {
      optarg = _get_arg("-amin");
      init_time(AMIN, optarg);
    } else if (IS_EQUAL(exp, "-atime")) {
      optarg = _get_arg("-atime");
      init_time(ATIME, optarg);
    } else if (IS_EQUAL(exp, "-anewer")) {
      optarg = _get_arg("-anewer");
      init_time(ANEWER, optarg);
    } else if (IS_EQUAL(exp, "-cnewer")) {
      optarg = _get_arg("-cnewer");
      init_time(CNEWER, optarg);
    } else if (IS_EQUAL(exp, "-cmin")) {
      optarg = _get_arg("-cmin");
      init_time(CMIN, optarg);
    } else if (IS_EQUAL(exp, "-ctime")) {
      optarg = _get_arg("-ctime");
      init_time(CTIME, optarg);
    } else if (IS_EQUAL(exp, "-mtime")) {
      optarg = _get_arg("-mtime");
      init_time(MMIN, optarg);
    } else if (IS_EQUAL(exp, "-mnewer")) {
      optarg = _get_arg("-mnewer");
      init_time(MNEWER, optarg);
    } else if (IS_EQUAL(exp, "-type")) {
      optarg = _get_arg("-type");
      init_filetype(optarg);
    } else if (IS_EQUAL(exp, "-size")) {
      optarg = _get_arg("-size");
      init_filesize(optarg);
    } else if (IS_EQUAL(exp, "-not")) {
#ifdef DEBUG
      fprintf(stderr, "filter not adapter\n");
#endif
      filter_not();
    } else if (IS_EQUAL(exp, "-and")) {
#ifdef DEBUG
      fprintf(stderr, "filter and\n");
#endif
      filter_and();
    } else if (IS_EQUAL(exp, "-or")) {
#ifdef DEBUG
      fprintf(stderr, "filter or\n");
#endif
      filter_or();
    } else {
      //TODO
    }
  }
  if (exp_num == 0) {
    init_true(); 
  }
  filter_tree.passed = op_stack[0];
  free_op_stack();
}
int main(int argc, char* argv[])
{
	srand((unsigned)time(NULL));

	int i, rank, size;
	int job_id;
	int num_slaves;             // # of slaves
	int num_gen = 100;          // # of generations
	int num_genes = 2;          // # of gene segments
	int num_chrs = 8;           // # of chromosomes
	double cross_rate = 0.95;   // crossover rate
	double mutate_rate = 0.001; // mutation rate
	double fitness;
	unsigned char* genes = (unsigned char*)malloc(num_genes * sizeof(unsigned char));
	Group* grp = init_group(num_genes, num_chrs, cross_rate, mutate_rate);
	MPI_Status stat;

	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &size);

	/* master is here */
	if (0 == rank)
	{
		num_slaves = size - 1;
		job_id = 0;

		for (i = 1; i < size; i++)
		{
			// send next job i, send grp->chrs[i]->genes
			MPI_Send(grp->chrs[job_id]->genes, num_genes, MPI_UNSIGNED_CHAR, i, 0, MPI_COMM_WORLD);
			job_id++;
		}

		while (job_id < num_chrs)
		{
			i = job_id % num_slaves + 1;

			// get result s, recv grp->chrs[s]->genes
			MPI_Recv(&(grp->chrs[job_id-num_slaves]->fitness), 1, MPI_DOUBLE, i, 0, MPI_COMM_WORLD, &stat);

			// send next job s, send grp->chrs[s]->genes
			MPI_Send(grp->chrs[job_id]->genes, num_genes, MPI_UNSIGNED_CHAR, i, 0, MPI_COMM_WORLD);
			job_id++;
		}

		int job_left = num_chrs % num_slaves;
		for (i = 0; i < num_genes; i++)
		{
			genes[i] = 0;
		}

		for (i = 1; i < size; i++)
		{
			int pid = (i + job_left - 1) % num_slaves + 1;

			// get result s, recv grp->chrs[s]->fitness
			MPI_Recv(&(grp->chrs[job_id-num_slaves]->fitness), 1, MPI_DOUBLE, pid, 0, MPI_COMM_WORLD, &stat);
			job_id++;

			// no more jobs s, send genes with all 0 values to represent no job
			MPI_Send(genes, num_genes, MPI_UNSIGNED_CHAR, i, 0, MPI_COMM_WORLD);
		}
	}
	else
	{
		/* slaves are here */
		while (1)
		{
			// get next job s, recv grp->chrs[s]->genes
			MPI_Recv(genes, num_genes, MPI_UNSIGNED_CHAR, 0, 0, MPI_COMM_WORLD, &stat);

			// stop process if no job
			unsigned char sum = 0;
			for (i = 0; i < num_genes; i++)
			{
			sum += genes[i];
			}

			// if sum of values of all gene segments is 0,
			// it means no job and should stop
			if (0 == sum)
			break;

			// do work
			fitness = update_fitness(num_genes, genes);

			// send result s, send fitness
			MPI_Send(&fitness, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD);
		}
	}

	/* Genetic Algorithm Process done by master */
	if (0 == rank)
	{
		for (i = 0; i < num_gen; i++)
		{
			update_fit_rate(grp);
			evolve(grp);
		}
	}

	free(genes);
	free_group(grp);

	MPI_Finalize();



	return 0;
}
Exemple #5
0
int main(int argc,const char *argv[])
{
  Net *net;
  Group *input,*hidden,*output,*bias;
  ExampleSet *examples, *test;
  Example *ex;
  Connections *c1,*c2,*c3,*c4;
  char * fileName = "input";
  int i,count,j, dataCount =0, testCount = 0;
  int dataCountArray[6] = {0};
  char * testFileArray[6] = {NULL};
  int inputCount = 0,outputCount = 0, hiddenCount = 200;
  int batchFlag = 0;
  Real error, correct;
  Real epsilon,range, hiddenRatio = 0;
  unsigned long seed = 0;
  /* don't buffer output */
  setbuf(stdout,NULL);

  /* set seed to unique number */
  mikenet_set_seed(seed);

  /* a default learning rate */
  epsilon=0.1;

  /* default weight range */
  range=0.5;

  default_errorRadius=0.0;
  const char *usage = "mike_childes [options]\n"
    "-seed\t\tRandom seed (default to 0)\n"
    "-i\t\tNumer of input units (default to 0)\n"
    "-h\t\tNumer of hidden units (default to 200)\n"
    "-o\t\tNumer of output units (default to 0)\n"
    "-r\t\tRatio of input units / hidden units.(default to 200)\n"
    "-b\t\tEnables batch learning (default online learning)\n"
    "-epsilon\tBack probagation epsilon (Default 0.1)\n"
    "-help\t\tprints this help\n";
  /* what are the command line arguments? */
  if (argc == 1) {
    fprintf(stderr, "%s", usage);
    exit(1);
  }
  for(i=1;i<argc;i++) {
    if (strcmp(argv[i],"-seed")==0) {
      seed = atol(argv[i+1]);
      mikenet_set_seed(seed);
      i++;
    } else if (strncmp(argv[i],"-epsilon",5)==0) {
      epsilon=atof(argv[i+1]);
      i++;
    } else if (strcmp(argv[i],"-range")==0) {
      range=atof(argv[i+1]);
      i++;
    } else if (strcmp(argv[i],"-errorRadius")==0) {
      default_errorRadius=atof(argv[i+1]);
      i++;
    } else if (strcmp(argv[i],"-t")==0){
      testFileArray[testCount] = (char *)argv[i+1];
      testCount++;
      i++;
    } else if (strcmp(argv[i],"-d")==0){
      dataCountArray[dataCount]= atoi(argv[i+1]);
      dataCount++;
      i++;
    } else if (strcmp(argv[i], "-iter")==0) {
      ITER = atoi(argv[i+1]);
      i++;
    } else if (strcmp(argv[i], "-f") == 0) {
      fileName = (char*)argv[i+1];
      i++;
    } else if (strcmp(argv[i], "-v") == 0) {
      VERBOSE = 1;
    } else if (strcmp(argv[i], "-i") == 0) {
      inputCount = atoi(argv[i+1]);
      i++;
    } else if (strcmp(argv[i], "-o") == 0) {
      outputCount = atoi(argv[i+1]);
      i++;
    } else if (strcmp(argv[i], "-h") == 0) {
      hiddenCount = atoi(argv[i+1]);
      i++;
    } else if (strcmp(argv[i], "-r") == 0) {
      hiddenRatio = atof(argv[i+1]);
      i++;
    } else if (strcmp(argv[i], "-b") == 0) {
      batchFlag = 1;
    } else {
      fprintf(stderr,"unknown argument: %s\n%s\n",argv[i],usage);
      exit(-1);
    }
  }

  /* build a network, with TIME number of time ticks */
  net=create_net(TIME);

  /* learning rate */
  default_epsilon=epsilon;

  /* hidden ratio */
  if (hiddenRatio > 0 && hiddenRatio <= 1) {
    hiddenCount = (int)inputCount * hiddenRatio;
    if(VERBOSE) fprintf(stderr, "number of hidden units is set to %d\n",hiddenCount);
  } else if(hiddenRatio > 1) {
    fprintf(stderr, "%s", usage);
    exit(1);
  }
  /* First stdout of this code is nummber of hidden units*/
  printf("%d\t",hiddenCount);
  /* create our groups.  
     format is: name, num of units, ticks */

  input=init_group("Input",inputCount,TIME);
  hidden=init_group("hidden",hiddenCount,TIME);
  output=init_group("Output",outputCount,TIME);

  /* bias is special.  format is: value, ticks */
  bias=init_bias(1.0,TIME);   

  /* now add our groups to the network object */
  bind_group_to_net(net,input);
  bind_group_to_net(net,hidden);
  bind_group_to_net(net,output);
  bind_group_to_net(net,bias);

  /* now connect our groups, instantiating */
  /* connection objects c1 through c4 */
  c1=connect_groups(input,hidden);
  c2=connect_groups(hidden,output);
  c3=connect_groups(bias,hidden);
  c4=connect_groups(bias,output);

  /* add connections to our network */
  bind_connection_to_net(net,c1);
  bind_connection_to_net(net,c2);
  bind_connection_to_net(net,c3);
  bind_connection_to_net(net,c4);

  /* randomize the weights in the connection objects.
     2nd argument is weight range. */
  randomize_connections(c1,range);
  randomize_connections(c2,range);
  randomize_connections(c3,range);
  randomize_connections(c4,range);

  /* how to load and save weights */
  /*  load_weights(net,"init.weights");   */

  /* erase old initial weight file */
  /*  system("rm -f init.weights.Z");      */

  /* save out our weights to file 'init.weights' */

  /* load in our example set */
  if (VERBOSE){
    fprintf(stderr, "Reading %s Iter:%d ",fileName, ITER);
    for(i=0; i < 6; i++){
      if (testFileArray[i] == NULL) break;
      fprintf(stderr, "TestSet:%s\n", testFileArray[i]);               
    }
  }
  examples=load_examples(fileName,TIME);
  if (VERBOSE){
    fprintf(stderr, "size:%d\n", examples->numExamples);     
    for(i=0; i < dataCount; i++){
      if (i == 0){
        fprintf(stderr, "DataCounts[%d] start:0 end:%d size:%d\n", \
            i,dataCountArray[i],dataCountArray[i]);
      }else{
        fprintf(stderr, "DataCounts[%d] start:%d end:%d size:%d\n", \
            i,dataCountArray[i - 1], dataCountArray[i], dataCountArray[i] - dataCountArray[i - 1]);
      }
    }
  }
  error=0.0;
  count=0;
  /* loop for ITER number of times */
  /* Reset the seed to get same training set*/
  fprintf(stderr, "Training: %s size:%d\n", fileName, examples->numExamples);     
  mikenet_set_seed(seed);     
  for(i=0;i<ITER;i++) {
    /* get j'th example from exampleset */
    int ridx = (int) (mikenet_random() * (Real)examples->numExamples);
    ex = &examples->examples[ridx];
    /*Original one*/
    // ex = get_random_example(examples);
    
    /* do forward propagation */
    bptt_forward(net,ex);

    /* backward pass: compute gradients */
    bptt_compute_gradients(net,ex);

    /* sum up error for this example */
    error+=compute_error(net,ex);

    /* online learning: apply the deltas 
       from previous call to compute_gradients */
    if(batchFlag == 0)  
      bptt_apply_deltas(net);

    /* is it time to write status? */
    if (count==REP) {
      /* average error over last 'count' iterations */
      error = error/(float)count;
      count=0;

      /* print a message about average error so far */
      if (VERBOSE) fprintf(stderr, "%d\t%f\n",i,error);
      if (error < 0.1) {
        break;
      }
      /* zero error; start counting again */
      error=0.0;
    }
    count++;
  }
  if(batchFlag == 1) 
      bptt_apply_deltas(net);
  /* done training.  write out results for each example */
  if (testCount == 0){
    correct = 0;
    dataCount = 0;
    for(i=0;i<examples->numExamples;i++)
    {
      if (VERBOSE && i % 1000 == 0) fprintf(stderr,".");
      if (dataCount && i == dataCountArray[dataCount]){
        if (dataCount ==0){
          printf("%f\t", correct / dataCountArray[dataCount]);
        }else{
          printf("%f\t", correct / (dataCountArray[dataCount] - dataCountArray[dataCount - 1]));

        }
        correct = 0;
        dataCount++;
      }
      ex=&examples->examples[i];
      bptt_forward(net,ex);
      int maxj = -1;
      Real  maxx = 0;
      for(j=0 ; j < outputCount; j++){
        if (output->outputs[TIME-1][j] > maxx){
          maxj = j;
          maxx = output->outputs[TIME-1][j];
        }
        /* printf("%d:%f ",j,output->outputs[TIME-1][j]); */
      }
      if (get_value(ex->targets,output->index,TIME-1,maxj) == 1)
        correct += 1;
    }
    printf("%f\n", correct / (dataCountArray[dataCount] - dataCountArray[dataCount - 1]));
  }
  else{
    int tt = 0, dc = 0;
    correct = 0;
    for(tt = 0; tt < testCount; tt++){
      test = load_examples(testFileArray[tt],TIME);
      if (VERBOSE)
        fprintf(stderr,"Testing:%s size:%d\n",testFileArray[tt],test->numExamples);
      correct = 0;
      for(i=0;i<test->numExamples;i++){
        if (dataCount && i == dataCountArray[dc]){
          if (dc == 0)
            printf("%f\t", correct / dataCountArray[dc]);
          else
            printf("%f\t", correct / (dataCountArray[dc] - dataCountArray[dc - 1]));                         
          correct = 0;
          dc++;
        }
        if (VERBOSE && i % 1000 == 0) fprintf(stderr,".");
        ex=&test->examples[i];
        bptt_forward(net,ex);
        int maxj = -1;
        Real  maxx = 0;
        int goldIdx = -1; 
        for(j=0 ; j < outputCount; j++){
          if (output->outputs[TIME-1][j] > maxx){
            maxj = j;
            maxx = output->outputs[TIME-1][j];
          } 
          if (get_value(ex->targets,output->index,TIME-1,j) == 1) {
            if(goldIdx != -1) {
              fprintf(stderr,\
                  "Multiple active output unit: Instance:%d unit:%d in test set!"\
                  ,i,j);
            }
            goldIdx = j; 
          }
          /* printf("%d:%f ",j,output->outputs[TIME-1][j]); */
        }
        if (goldIdx != -1 || maxj != -1) {
          // prints the goldtag and answer tag
          fprintf(stderr, "%d %d\n", goldIdx, maxj);
        } else{
          fprintf(stderr, "No active output units in test set");
          exit(-1);
        }
        if (get_value(ex->targets,output->index,TIME-1,maxj) == 1) {
          correct += 1;
        }
      }
      if (dataCount == 0)
        printf("%f %d %d\t", correct / test->numExamples, (int)correct, test->numExamples);
      else
        printf("%f\n", correct / (dataCountArray[dc] - dataCountArray[dc - 1]));
    }
  }
  return 0;
}
Exemple #6
0
xymongen_page_t *load_layout(char *pgset)
{
	char	pagetag[100], subpagetag[100], subparenttag[100], 
		vpagetag[100], vsubpagetag[100], vsubparenttag[100], 
		grouptag[100], summarytag[100], titletag[100], hosttag[100];
	char 	*name, *link, *onlycols, *exceptcols;
	char 	hostname[MAX_LINE_LEN];
	xymongen_page_t 	*toppage, *curpage, *cursubpage, *cursubparent;
	group_t *curgroup;
	host_t	*curhost;
	char	*curtitle;
	int	ip1, ip2, ip3, ip4;
	char	*p;
	int	fqdn = get_fqdn();
	char	*cfgdata, *inbol, *ineol, insavchar = '\0';

	if (loadhostsfromxymond) {
		if (load_hostnames("@", NULL, fqdn) != 0) {
			errprintf("Cannot load host configuration from xymond\n");
			return NULL;
		}
	}
	else {
		if (load_hostnames(xgetenv("HOSTSCFG"), "dispinclude", fqdn) != 0) {
			errprintf("Cannot load host configuration from %s\n", xgetenv("HOSTSCFG"));
			return NULL;
		}
	}

	if (first_host() == NULL) {
		errprintf("Empty configuration from %s\n", (loadhostsfromxymond ? "xymond" : xgetenv("HOSTSCFG")));
		return NULL;
	}

	dbgprintf("load_layout(pgset=%s)\n", textornull(pgset));

	/*
	 * load_hostnames() picks up the hostname definitions, but not the page
	 * layout. So we will scan the file again, this time doing the layout.
	 */

	if (pgset == NULL) pgset = "";
	sprintf(pagetag, "%spage", pgset);
	sprintf(subpagetag, "%ssubpage", pgset);
	sprintf(subparenttag, "%ssubparent", pgset);
	sprintf(vpagetag, "v%spage", pgset);
	sprintf(vsubpagetag, "v%ssubpage", pgset);
	sprintf(vsubparenttag, "v%ssubparent", pgset);
	sprintf(grouptag, "%sgroup", pgset);
	sprintf(summarytag, "%ssummary", pgset);
	sprintf(titletag, "%stitle", pgset);
	sprintf(hosttag, "%s:", pgset); for (p=hosttag; (*p); p++) *p = toupper((int)*p);

	toppage = init_page("", "", 0);
	addtopagelist(toppage);
	curpage = NULL;
	cursubpage = NULL;
	curgroup = NULL;
	curhost = NULL;
	cursubparent = NULL;
	curtitle = NULL;

	inbol = cfgdata = hostscfg_content();
	while (inbol && *inbol) {
		inbol += strspn(inbol, " \t");
		ineol = strchr(inbol, '\n');
		if (ineol) {
			while ((ineol > inbol) && (isspace(*ineol) || (*ineol == '\n'))) ineol--;
			if (*ineol != '\n') ineol++;

			insavchar = *ineol;
			*ineol = '\0';
		}

		dbgprintf("load_layout: -- got line '%s'\n", inbol);

		if ((strncmp(inbol, pagetag, strlen(pagetag)) == 0) || (strncmp(inbol, vpagetag, strlen(vpagetag)) == 0)) {
			getnamelink(inbol, &name, &link);
			if (curpage == NULL) {
				/* First page - hook it on toppage as a subpage from there */
				curpage = toppage->subpages = init_page(name, link, (strncmp(inbol, vpagetag, strlen(vpagetag)) == 0));
			}
			else {
				curpage = curpage->next = init_page(name, link, (strncmp(inbol, vpagetag, strlen(vpagetag)) == 0));
			}

			curpage->parent = toppage;
			if (curtitle) { 
				curpage->pretitle = curtitle; 
				curtitle = NULL; 
			}
			cursubpage = NULL;
			cursubparent = NULL;
			curgroup = NULL;
			curhost = NULL;
			addtopagelist(curpage);
		}
		else if ( (strncmp(inbol, subpagetag, strlen(subpagetag)) == 0) || (strncmp(inbol, vsubpagetag, strlen(vsubpagetag)) == 0) ) {
			if (curpage == NULL) {
				errprintf("'subpage' ignored, no preceding 'page' tag : %s\n", inbol);
				goto nextline;
			}

			getnamelink(inbol, &name, &link);
			if (cursubpage == NULL) {
				cursubpage = curpage->subpages = init_page(name, link, (strncmp(inbol, vsubpagetag, strlen(vsubpagetag)) == 0));
			}
			else {
				cursubpage = cursubpage->next = init_page(name, link, (strncmp(inbol, vsubpagetag, strlen(vsubpagetag)) == 0));
			}
			cursubpage->parent = curpage;
			if (curtitle) { 
				cursubpage->pretitle = curtitle; 
				curtitle = NULL;
			}
			cursubparent = NULL;
			curgroup = NULL;
			curhost = NULL;
			addtopagelist(cursubpage);
		}
		else if ( (strncmp(inbol, subparenttag, strlen(subparenttag)) == 0) || (strncmp(inbol, vsubparenttag, strlen(vsubparenttag)) == 0) ) {
			xymongen_page_t *parentpage, *walk;

			getparentnamelink(inbol, toppage, &parentpage, &name, &link);
			if (parentpage == NULL) {
				errprintf("'subparent' ignored, unknown parent page: %s\n", inbol);
				goto nextline;
			}

			cursubparent = init_page(name, link, (strncmp(inbol, vsubparenttag, strlen(vsubparenttag)) == 0));
			if (parentpage->subpages == NULL) {
				parentpage->subpages = cursubparent;
			} 
			else {
				for (walk = parentpage->subpages; (walk->next); (walk = walk->next)) ;
				walk->next = cursubparent;
			}
			if (curtitle) { 
				cursubparent->pretitle = curtitle; 
				curtitle = NULL;
			}
			cursubparent->parent = parentpage;
			curgroup = NULL;
			curhost = NULL;
			addtopagelist(cursubparent);
		}
		else if (strncmp(inbol, grouptag, strlen(grouptag)) == 0) {
			int sorthosts = (strstr(inbol, "group-sorted") != NULL);

			getgrouptitle(inbol, pgset, &link, &onlycols, &exceptcols);
			if (curgroup == NULL) {
				curgroup = init_group(link, onlycols, exceptcols, sorthosts);
				if (cursubparent != NULL) {
					cursubparent->groups = curgroup;
				}
				else if (cursubpage != NULL) {
					/* We're in a subpage */
					cursubpage->groups = curgroup;
				}
				else if (curpage != NULL) {
					/* We're on a main page */
					curpage->groups = curgroup;
				}
				else {
					/* We're on the top page */
					toppage->groups = curgroup;
				}
			}
			else {
				curgroup->next = init_group(link, onlycols, exceptcols, sorthosts);
				curgroup = curgroup->next;
			}
			if (curtitle) { curgroup->pretitle = curtitle; curtitle = NULL; }
			curhost = NULL;
		}
		else if (sscanf(inbol, "%3d.%3d.%3d.%3d %s", &ip1, &ip2, &ip3, &ip4, hostname) == 5) {
			void *xymonhost = NULL;
			int dialup, nonongreen, crittime = 1;
			double warnpct = reportwarnlevel;
			int warnstops = reportwarnstops;
			char *displayname, *clientalias, *comment, *description;
			char *alertlist, *onwaplist, *reporttime;
			char *nopropyellowlist, *nopropredlist, *noproppurplelist, *nopropacklist;
			char *targetpagelist[MAX_TARGETPAGES_PER_HOST];
			int targetpagecount;
			char *hval;

			/* Check for ".default." hosts - they are ignored. */
			if (*hostname == '.') goto nextline;

			if (!fqdn) {
				/* Strip any domain from the hostname */
				char *p = strchr(hostname, '.');
				if (p) *p = '\0';
			}

			/* Get the info */
			xymonhost = hostinfo(hostname);
			if (xymonhost == NULL) {
				errprintf("Confused - hostname '%s' cannot be found. Ignored\n", hostname);
				goto nextline;
			}

			/* Check for no-display hosts - they are ignored. */
			/* But only when we're building the default pageset */
			if ((strlen(pgset) == 0) && (xmh_item(xymonhost, XMH_FLAG_NODISP) != NULL)) goto nextline;

			for (targetpagecount=0; (targetpagecount < MAX_TARGETPAGES_PER_HOST); targetpagecount++) 
				targetpagelist[targetpagecount] = NULL;
			targetpagecount = 0;

			dialup = (xmh_item(xymonhost, XMH_FLAG_DIALUP) != NULL);
			nonongreen = (xmh_item(xymonhost, XMH_FLAG_NONONGREEN) != NULL);

			alertlist = xmh_item(xymonhost, XMH_NK);
			hval = xmh_item(xymonhost, XMH_NKTIME); if (hval) crittime = within_sla(xmh_item(xymonhost, XMH_HOLIDAYS), hval, 0);

			onwaplist = xmh_item(xymonhost, XMH_WML);
			nopropyellowlist = xmh_item(xymonhost, XMH_NOPROPYELLOW);
			if (nopropyellowlist == NULL) nopropyellowlist = xmh_item(xymonhost, XMH_NOPROP);
			nopropredlist = xmh_item(xymonhost, XMH_NOPROPRED);
			noproppurplelist = xmh_item(xymonhost, XMH_NOPROPPURPLE);
			nopropacklist = xmh_item(xymonhost, XMH_NOPROPACK);
			displayname = xmh_item(xymonhost, XMH_DISPLAYNAME);
			comment = xmh_item(xymonhost, XMH_COMMENT);
			description = xmh_item(xymonhost, XMH_DESCRIPTION);
			hval = xmh_item(xymonhost, XMH_WARNPCT); if (hval) warnpct = atof(hval);
			hval = xmh_item(xymonhost, XMH_WARNSTOPS); if (hval) warnstops = atof(hval);
			reporttime = xmh_item(xymonhost, XMH_REPORTTIME);

			clientalias = xmh_item(xymonhost, XMH_CLIENTALIAS);
			if (xymonhost && (strcmp(xmh_item(xymonhost, XMH_HOSTNAME), clientalias) == 0)) clientalias = NULL;

			if (xymonhost && (strlen(pgset) > 0)) {
				/* Walk the clone-list and pick up the target pages for this host */
				void *cwalk = xymonhost;
				do {
					hval = xmh_item_walk(cwalk);
					while (hval) {
						if (strncasecmp(hval, hosttag, strlen(hosttag)) == 0)
							targetpagelist[targetpagecount++] = strdup(hval+strlen(hosttag));
						hval = xmh_item_walk(NULL);
					}

					cwalk = next_host(cwalk, 1);
				} while (cwalk && 
					 (strcmp(xmh_item(cwalk, XMH_HOSTNAME), xmh_item(xymonhost, XMH_HOSTNAME)) == 0) &&
					 (targetpagecount < MAX_TARGETPAGES_PER_HOST) );

				/*
				 * HACK: Check if the pageset tag is present at all in the host
				 * entry. If it isn't, then drop this incarnation of the host.
				 *
				 * Without this, the following hosts.cfg file will have the
				 * www.hswn.dk host listed twice on the alternate pageset:
				 *
				 * adminpage nyc NYC
				 *
				 * 127.0.0.1   localhost      # bbd http://localhost/ CLIENT:osiris
				 * 172.16.10.2 www.xymon.com  # http://www.xymon.com/ ADMIN:nyc ssh noinfo
				 *
				 * page superdome Superdome
				 * 172.16.10.2 www.xymon.com # noconn
				 *
				 */
				if (strstr(inbol, hosttag) == NULL) targetpagecount = 0;
			}

			if (strlen(pgset) == 0) {
				/*
				 * Default pageset generated. Put the host into
				 * whatever group or page is current.
				 */
				if (curhost == NULL) {
					curhost = init_host(hostname, 0, displayname, clientalias,
							    comment, description,
							    ip1, ip2, ip3, ip4, dialup, 
							    warnpct, warnstops, reporttime,
							    alertlist, crittime, onwaplist,
							    nopropyellowlist, nopropredlist, noproppurplelist, nopropacklist);
					if (curgroup != NULL) {
						curgroup->hosts = curhost;
					}
					else if (cursubparent != NULL) {
						cursubparent->hosts = curhost;
					}
					else if (cursubpage != NULL) {
						cursubpage->hosts = curhost;
					}
					else if (curpage != NULL) {
						curpage->hosts = curhost;
					}
					else {
						toppage->hosts = curhost;
					}
				}
				else {
					curhost = curhost->next = init_host(hostname, 0, displayname, clientalias,
									    comment, description,
									    ip1, ip2, ip3, ip4, dialup,
									    warnpct, warnstops, reporttime,
									    alertlist, crittime, onwaplist,
									    nopropyellowlist,nopropredlist, 
									    noproppurplelist, nopropacklist);
				}
				curhost->parent = (cursubparent ? cursubparent : (cursubpage ? cursubpage : curpage));
				if (curtitle) { curhost->pretitle = curtitle; curtitle = NULL; }
				curhost->nonongreen = nonongreen;
			}
			else if (targetpagecount) {

				int pgnum;

				for (pgnum=0; (pgnum < targetpagecount); pgnum++) {
					char *targetpagename = targetpagelist[pgnum];

					char savechar;
					int wantedgroup = 0;
					xymonpagelist_t *targetpage = NULL;

					/* Put the host into the page specified by the PGSET: tag */
					p = strchr(targetpagename, ',');
					if (p) {
						savechar = *p;
						*p = '\0';
						wantedgroup = atoi(p+1);
					}
					else {
						savechar = '\0';
						p = targetpagename + strlen(targetpagename);
					}

					/* Find the page */
					if (strcmp(targetpagename, "*") == 0) {
						*targetpagename = '\0';
					}
					for (targetpage = pagelisthead; (targetpage && (strcmp(targetpagename, targetpage->pageentry->name) != 0)); targetpage = targetpage->next) ;

					*p = savechar;
					if (targetpage == NULL) {
						errprintf("Warning: Cannot find any target page named '%s' in set '%s' - dropping host '%s'\n", 
							targetpagename, pgset, hostname);
					}
					else {
						host_t *newhost = init_host(hostname, 0, displayname, clientalias,
									    comment, description,
									    ip1, ip2, ip3, ip4, dialup,
									    warnpct, warnstops, reporttime,
									    alertlist, crittime, onwaplist,
									    nopropyellowlist,nopropredlist, 
									    noproppurplelist, nopropacklist);

						if (wantedgroup > 0) {
							group_t *gwalk;
							host_t  *hwalk;
							int i;

							for (gwalk = targetpage->pageentry->groups, i=1; (gwalk && (i < wantedgroup)); i++,gwalk=gwalk->next) ;
							if (gwalk) {
								if (gwalk->hosts == NULL)
									gwalk->hosts = newhost;
								else {
									for (hwalk = gwalk->hosts; (hwalk->next); hwalk = hwalk->next) ;
									hwalk->next = newhost;
								}
							}
							else {
								errprintf("Warning: Cannot find group %d for host %s - dropping host\n",
									wantedgroup, hostname);
							}
						}
						else {
							/* Just put in on the page's hostlist */
							host_t *walk;
	
							if (targetpage->pageentry->hosts == NULL)
								targetpage->pageentry->hosts = newhost;
							else {
								for (walk = targetpage->pageentry->hosts; (walk->next); walk = walk->next) ;
								walk->next = newhost;
							}
						}

						newhost->parent = targetpage->pageentry;
						if (curtitle) newhost->pretitle = curtitle;
					}

					curtitle = NULL;
				}
			}
		}
		else if (strncmp(inbol, summarytag, strlen(summarytag)) == 0) {
			/* summary row.column      IP-ADDRESS-OF-PARENT    http://xymon.com/ */
			char sumname[MAX_LINE_LEN];
			char receiver[MAX_LINE_LEN];
			char url[MAX_LINE_LEN];
			summary_t *newsum;

			if (sscanf(inbol, "summary %s %s %s", sumname, receiver, url) == 3) {
				newsum = init_summary(sumname, receiver, url);
				newsum->next = sumhead;
				sumhead = newsum;
			}
		}
		else if (strncmp(inbol, titletag, strlen(titletag)) == 0) {
			/* Save the title for the next entry */
			curtitle = strdup(skipwhitespace(skipword(inbol)));
		}

nextline:
		if (ineol) {
			*ineol = insavchar;
			if (*ineol != '\n') ineol = strchr(ineol, '\n');

			inbol = (ineol ? ineol+1 : NULL);
		}
		else
			inbol = NULL;
	}

	xfree(cfgdata);
	return toppage;
}
Exemple #7
0
int main(int argc,char *argv[])
{
  int j;
  float e;
  int dbd=0;
  Net *net;
  float momentum=0.0;
  Group *input,*hidden,*output,*bias;
  ExampleSet *examples;
  Example *ex;
  Connections *c1,*c2,*c3,*c4;
  int i,count;
  Real error;
  int seed=666;
  Real epsilon,range,tolerance;

  /* don't buffer output */
  setbuf(stdout,NULL);
  announce_version();
  seed=getpid();

  /* how low must error get before we quit? */
  tolerance=0.01;

  /* set random number seed to process id
     (only unix machines have getpid call) */

  default_temperature=1.0;
  default_temporg=50;
  default_tempmult=0.9;
  /* a default learning rate */
  epsilon=0.1;
  
  /* default weight range */
  range=0.5;

  default_errorRadius=0.1;

  /* what are the command line arguments? */
  for(i=1;i<argc;i++)
    {
      if (strncmp(argv[i],"-epsilon",5)==0)
	{
	  epsilon=atof(argv[i+1]);
	  i++;
	}
      else if (strncmp(argv[i],"-momentum",5)==0)
	{
	  momentum=atof(argv[i+1]);
	  i++;
	}
      else if (strncmp(argv[i],"-seed",5)==0)
	{
	  seed=atoi(argv[i+1]);
	  i++;
	}
      else if (strcmp(argv[i],"-dbd")==0)
	{
	  dbd=1;
	}
      else if (strcmp(argv[i],"-range")==0)
	{
	  range=atof(argv[i+1]);
	  i++;
	}
      else if (strcmp(argv[i],"-errorRadius")==0)
	{
	  default_errorRadius=atof(argv[i+1]);
	  i++;
	}
      else if (strncmp(argv[i],"-tolerance",4)==0)
	{
	  tolerance=atof(argv[i+1]);
	  i++;
	}
      else
	{
	  fprintf(stderr,"unknown option: %s\n",argv[i]);
	  exit(-1);
	}
    }

  mikenet_set_seed(seed);
  default_momentum=0.0;
  
  if ((sizeof(Real)==4 && tolerance < 0.001) ||
      (sizeof(Real)==8 && tolerance < 0.00001))
    {
      fprintf(stderr,"careful; your tolerance is probably ");
      fprintf(stderr,"too tight for this machines precision\n");
    }
  
  /* build a network, with TIME number of time ticks */
  net=create_net(TIME);
  net->integrationConstant=0.5;
  
  /* learning rate */
  default_epsilon=epsilon;

  /* create our groups.  
     format is: name, num of units, ticks */
  input=init_group("Input",2,TIME);
  hidden=init_group("hidden",10,TIME);
  output=init_group("Output",21,TIME);

  /* bias is special.  format is: value, ticks */
  bias=init_bias(1.0,TIME);   

  /* now add our groups to the network object */
  bind_group_to_net(net,input);
  bind_group_to_net(net,hidden);
  bind_group_to_net(net,output); 
  bind_group_to_net(net,bias); 

  /* now connect our groups, instantiating */
  /* connection objects c1 through c4 */
  c1=connect_groups(input,hidden);
  c2=connect_groups(hidden,output);
  c3=connect_groups(bias,hidden);
  c4=connect_groups(bias,output);

  /* add connections to our network */
  bind_connection_to_net(net,c1);
  bind_connection_to_net(net,c2);
  bind_connection_to_net(net,c3);
  bind_connection_to_net(net,c4);

  /* randomize the weights in the connection objects.
     2nd argument is weight range. */
  randomize_connections(c1,range);
  randomize_connections(c2,range);
  randomize_connections(c3,range);
  randomize_connections(c4,range);

  /* load in our example set */
  examples=load_examples("xor.ex",TIME);

  error=0.0;
  count=0;
  /* loop for ITER number of times */
  for(i=0;i<ITER;i++)
    {

      for(j=0;j<examples->numExamples;j++)
	{
	  ex=&examples->examples[j];
	  dbm_positive(net,ex);
	  dbm_negative(net,ex);
	  dbm_update(net);
	}

      e = output->outputs[TIME-1][0] - 
	get_value(ex->targets,output->index,0,0);
      error += e * e;

      dbm_apply_deltas(net);

      
      if (count==REP)
	{
	  /* average error over last 'count' iterations */
	  error = error/(float)count;
	  count=0;

	  /* print a message about average error so far */
	  printf("%d\t%f\n",i,error);
	  /* are we done? */
	  if (error < tolerance)
	    {
	      printf("quitting... error low enough\n");
	      /* pop out of loop */
	      break;
	    }
	  /* zero error; start counting again */
	  error=0.0;
	}
      count++;
    }


  system("rm out.weights*");
  save_weights(net,"out.weights");
  return 0;
}
/*============== main() =================*/
int main(int argc, char* argv[])
{
	srand((unsigned)time(NULL));

	/* check arguments length */
	int numArgv = 13;

	if (numArgv != argc)
	{
		print_usage();  // print usage and help info
		exit (1);
	}

	/* get values from command line */
	int num_genes;				// # of gene segments
	int num_players;			// # of chromosomes/prisoners
	int num_gen;					// # of generations
	int num_iters;				// # of game iterations
	double cross_rate;		// crossover rate
	double mutate_rate;		// mutation rate

	// the order of arguments is arbitrary
	int i, j;
	for (i = 1; i < numArgv; i+=2)
	{
		if (0 == strcmp("-s",argv[i]))
			num_genes = atoi(argv[i+1]);
		else if (0 == strcmp("-p",argv[i]))
			num_players = atoi(argv[i+1]);
		else if (0 == strcmp("-g",argv[i]))
			num_gen = atoi(argv[i+1]);
		else if (0 == strcmp("-i",argv[i]))
			num_iters = atoi(argv[i+1]);
		else if (0 == strcmp("-c",argv[i]))
			cross_rate = atof(argv[i+1]);
		else if (0 == strcmp("-m",argv[i]))
			mutate_rate = atof(argv[i+1]);
		else
		{
			print_usage();  // print usage and help info
			exit (2);
		}
	}

	/* Prisoner's Dilemma Game */
	Group* players = init_group(num_genes, num_players, cross_rate, mutate_rate);

	// run for num_gen generations
	for (i = 0; i < num_gen; i++)
	{
		// play PD game for num_iters times
		for (j = 0; j < num_iters; j++)
		{
			play_game(players);
		}

		update_fit_rate(players);
		evolve(players);
	}

	free_group(players);

	return 0;
}
Exemple #9
0
int
do_collect(void)
{
    register group_header *gh;
    long            col_article_count, temp;
    int             col_group_count;
    time_t          start_time;

    start_time = cur_time();
    col_article_count = col_group_count = 0;
    current_group = NULL;	/* for init_group */
    temp = 0;

    Loop_Groups_Header(gh) {
	if (s_hangup) {
	    temp = -1;
	    break;
	}
	if (gh->master_flag & M_IGNORE_GROUP)
	    continue;

	if (gh->master_flag & M_MUST_CLEAN)
	    clean_group(gh);

	if (gh->last_db_article == gh->last_a_article) {
	    if (gh->master_flag & M_BLOCKED)
		goto unblock_group;
	    continue;
	}
	if (!init_group(gh)) {
	    if ((gh->master_flag & M_NO_DIRECTORY) == 0) {
		log_entry('R', "%s: no directory", gh->group_name);
		gh->master_flag |= M_NO_DIRECTORY;
	    }
	    gh->last_db_article = gh->last_a_article;
	    gh->first_db_article = gh->last_a_article;	/* OBS: not first */
	    gh->master_flag &= ~(M_EXPIRE | M_BLOCKED);
	    db_write_group(gh);
	    continue;
	}
	if (gh->master_flag & M_NO_DIRECTORY) {
	    /* The directory has been created now */
	    gh->master_flag &= ~M_NO_DIRECTORY;
	    clean_group(gh);
	}
	temp = collect_group(gh);

#ifdef NNTP
	if (temp < 0) {
	    /* connection broken */
	    gh->master_flag &= ~M_EXPIRE;	/* remains blocked */
	    db_write_group(gh);
	    break;
	}
#endif

	if (temp > 0) {
	    col_article_count += temp;
	    col_group_count++;
	}
unblock_group:
	gh->master_flag &= ~(M_EXPIRE | M_BLOCKED);
	db_write_group(gh);
    }

    if (col_article_count > 0)
	log_entry('C', "Collect: %ld art, %d gr, %ld s",
		  col_article_count, col_group_count,
		  cur_time() - start_time);

    return temp > 0;		/* return true IF we got articles */
}
Exemple #10
0
static SDL_bool load_config(session *s, game_state *gs, json_t *game, char const *root)
{
	json_t *entities, *fnt, *level;
	char const *file, *path;

	/* load config */
	fnt = json_object_get(game, "font");
	path = set_path("%s/%s/%s", root, ASSET_DIR, json_string_value(json_object_get(fnt, "resource")));
	int fnt_siz = json_integer_value(json_object_get(fnt, "size"));
	TTF_Font *font = TTF_OpenFont(path, fnt_siz);
	if (!font) {
		fprintf(stderr, "error: could not load font %s: %s\n", path, TTF_GetError());
		return SDL_FALSE;
	}

	if (!gs->debug.font) {
		gs->debug.font = TTF_OpenFont("debug_font.ttf", 14);
	}

	SDL_bool ok;
	ok = load_finish(s, game, font, fnt_siz);
	if (!ok) { return SDL_FALSE; }

	ok = load_messages(s, game, font, fnt_siz, root);
	if (!ok) { return SDL_FALSE; }
	TTF_CloseFont(font);

	level = json_object_get(game, "level");
	if (!ok) { return SDL_FALSE; }
	path = set_path("%s/%s/%s", root, CONF_DIR, json_string_value(level));
	json_error_t e;
	level = json_load_file(path, 0, &e);
	if (*e.text != 0) {
		fprintf(stderr, "Error at %s:%d: %s\n", path, e.line, e.text);
		return SDL_FALSE;
	}

	s->level.background = load_asset_tex(level, root, s->r, "resource");
	if (!s->level.background) { return SDL_FALSE; }

	load_collisions(&s->level, level);
	json_decref(level);

	entity_rule *e_rules;
	SDL_Texture **e_texs;
	entities = json_object_get(game, "entities");
	if (!entities) {
		fprintf(stderr, "Error: No entities defined, need player\n");
		return SDL_FALSE;
	}

	file = json_string_value(json_object_get(entities, "resource"));
	path = set_path("%s/%s/%s", root, CONF_DIR, file);
	entities = load_entities(root, path, s->r, &e_texs, &e_rules);
	if (!entities) {
		fprintf(stderr, "Error: Could not load entities\n");
		return SDL_FALSE;
	}

	init_group(&gs->entities[GROUP_PLAYER ], game, entities, "players", e_texs, e_rules, ST_IDLE);
	init_group(&gs->entities[GROUP_OBJECTS], game, entities, "objects", e_texs, e_rules, ST_IDLE);
	init_group(&gs->entities[GROUP_ENEMIES], game, entities, "enemies", e_texs, e_rules, ST_WALK);

	load_intro(&gs->logo, s, entities, "logo", e_rules, e_texs);
	load_intro(&gs->intro, s, entities, "intro", e_rules, e_texs);

	/* all texture pointers are copied by value, no need to hold onto the
	 * e_texs buffer */
	free(e_texs);

	json_decref(entities);
	json_decref(game);

	return SDL_TRUE;
}
Exemple #11
0
void
showtime_init(void)
{
  int r;

  hts_mutex_init(&gconf.state_mutex);
  hts_cond_init(&gconf.state_cond, &gconf.state_mutex);

  gconf.exit_code = 1;

  unicode_init();

  /* Initialize property tree */
  prop_init();
  init_global_info();

  /* Initiailize logging */
  trace_init();

  /* Callout framework */
  callout_init();

  /* Initialize htsmsg_store() */
  htsmsg_store_init();

  /* Notification framework */
  notifications_init();

  /* Initialize settings */
  settings_init();

  TRACE(TRACE_DEBUG, "core", "Loading resources from %s", showtime_dataroot());

  /* Try to create cache path */
  if(gconf.cache_path != NULL &&
     (r = makedirs(gconf.cache_path)) != 0) {
    TRACE(TRACE_ERROR, "cache", "Unable to create cache path %s -- %s",
	  gconf.cache_path, strerror(r));
    gconf.cache_path = NULL;
  }

  /* Initialize sqlite3 */
  db_init();

  /* Initializte blob cache */
  blobcache_init();

  /* Try to create settings path */
  if(gconf.persistent_path != NULL &&
     (r = makedirs(gconf.persistent_path)) != 0) {
    TRACE(TRACE_ERROR, "settings",
	  "Unable to create path for persistent storage %s -- %s",
	  gconf.persistent_path, strerror(r));
    gconf.persistent_path = NULL;
  }

  /* Metadata init */
  metadata_init();
  metadb_init();
  kvstore_init();

  /* Metadata decoration init */
  decoration_init();

  /* Initialize keyring */
  keyring_init();

#if ENABLE_LIBAV
  /* Initialize libavcodec & libavformat */
  av_lockmgr_register(fflockmgr);
  av_log_set_callback(fflog);
  av_register_all();

  TRACE(TRACE_INFO, "libav", LIBAVFORMAT_IDENT", "LIBAVCODEC_IDENT", "LIBAVUTIL_IDENT);
#endif

  /* Freetype */
#if ENABLE_LIBFREETYPE
  freetype_init();
  rasterizer_ft_init();
#endif

#if ENABLE_GLW
  glw_settings_init();
#endif

  fontstash_init();

  /* Global keymapper */
  keymapper_init();

  /* Initialize media subsystem */
  media_init();

  /* Service handling */
  service_init();

  /* Initialize backend content handlers */
  backend_init();

  /* Initialize navigator */
  nav_init();

  /* Initialize audio subsystem */
  audio_init();

  /* Initialize plugin manager */
  plugins_init(gconf.devplugin);

  /* Start software installer thread (plugins, upgrade, etc) */
  hts_thread_create_detached("swinst", swthread, NULL, THREAD_PRIO_LOW);

  /* Internationalization */
  i18n_init();

  /* Video settings */
  video_settings_init();

  if(gconf.load_jsfile)
    js_load(gconf.load_jsfile);

  /* Various interprocess communication stuff (D-Bus on Linux, etc) */
  init_group(INIT_GROUP_IPC);

  /* Service discovery. Must be after ipc_init() (d-bus and threads, etc) */
  if(!gconf.disable_sd)
    sd_init();

  /* Initialize various external APIs */
  init_group(INIT_GROUP_API);

  /* HTTP server and UPNP */
#if ENABLE_HTTPSERVER
  http_server_init();
  if(!gconf.disable_upnp)
    upnp_init();
#endif

  runcontrol_init();
}
Exemple #12
0
void
main_init(void)
{
  char errbuf[512];

  hts_mutex_init(&gconf.state_mutex);
  hts_cond_init(&gconf.state_cond, &gconf.state_mutex);

  gconf.exit_code = 1;

  asyncio_init_early();
  init_group(INIT_GROUP_NET);

  unicode_init();


  /* Initialize property tree */
  prop_init();
  init_global_info();

  /* Initiailize logging */
  trace_init();

  /* Callout framework */
  callout_init();
  prop_init_late();

  /* Initialize htsmsg_store() */
  htsmsg_store_init();

  /* Notification framework */
  notifications_init();

  /* Initialize settings */
  settings_init();

  TRACE(TRACE_DEBUG, "core", "Loading resources from %s", app_dataroot());

  TRACE(TRACE_DEBUG, "core", "Cache path: %s", gconf.cache_path);

  /* Try to create cache path */
  if(gconf.cache_path != NULL &&
     fa_makedirs(gconf.cache_path, errbuf, sizeof(errbuf))) {
    TRACE(TRACE_ERROR, "core", "Unable to create cache path %s -- %s",
	  gconf.cache_path, errbuf);
    gconf.cache_path = NULL;
  }

  /* Initialize sqlite3 */
#if ENABLE_SQLITE
  db_init();
#endif

  /* Initializte blob cache */
  blobcache_init();


  TRACE(TRACE_DEBUG, "core", "Persistent path: %s", gconf.persistent_path);

  /* Try to create settings path */
  if(gconf.persistent_path != NULL &&
     fa_makedirs(gconf.persistent_path, errbuf, sizeof(errbuf))) {
    TRACE(TRACE_ERROR, "core",
	  "Unable to create path for persistent storage %s -- %s",
	  gconf.persistent_path, errbuf);
    gconf.persistent_path = NULL;
  }

  /* Per-item key/value store */
  kvstore_init();

  /* Metadata init */
#if ENABLE_METADATA
  metadata_init();
  metadb_init();
  decoration_init();
#endif

  subtitles_init();

  /* Initialize keyring */
  keyring_init();

#if ENABLE_LIBAV
  /* Initialize libavcodec & libavformat */
  av_lockmgr_register(fflockmgr);
  av_log_set_callback(fflog);
  av_register_all();

  TRACE(TRACE_INFO, "libav", LIBAVFORMAT_IDENT", "LIBAVCODEC_IDENT", "LIBAVUTIL_IDENT" cpuflags:0x%x", av_get_cpu_flags());
#endif

  init_group(INIT_GROUP_GRAPHICS);

#if ENABLE_GLW
  glw_settings_init();
#endif

  /* Global keymapper */
  keymapper_init();

  /* Initialize media subsystem */
  media_init();

  /* Service handling */
  service_init();

  /* Initialize backend content handlers */
  backend_init();

  /* Initialize navigator */
  nav_init();

  /* Initialize audio subsystem */
  audio_init();

  /* Initialize plugin manager */
  plugins_init(gconf.devplugins);

  /* Start software installer thread (plugins, upgrade, etc) */
  hts_thread_create_detached("swinst", swthread, NULL, THREAD_PRIO_BGTASK);

  /* Internationalization */
  i18n_init();

  /* Video settings */
  video_settings_init();

  /* Various interprocess communication stuff (D-Bus on Linux, etc) */
  init_group(INIT_GROUP_IPC);

  /* Service discovery. Must be after ipc_init() (d-bus and threads, etc) */
  if(!gconf.disable_sd)
    sd_init();

  /* Initialize various external APIs */
  init_group(INIT_GROUP_API);

  /* Asynchronous IO (Used by HTTP server, etc) */
  asyncio_start();

  runcontrol_init();

  TRACE(TRACE_DEBUG, "SYSTEM", "Hashed device ID: %s", gconf.device_id);
  if(gconf.device_type[0])
    TRACE(TRACE_DEBUG, "SYSTEM", "Device type: %s", gconf.device_type);
}
Exemple #13
0
int main(int argc,const char *argv[])
{
     Net *net;
     Group *input,*hidden,*output,*bias;
     ExampleSet *examples;
     Example *ex;
     Connections *c1,*c2,*c3,*c4;
     char * fileName = "input";
     int i,count,j;
     int inputCount = 0,outputCount = 0, hiddenCount = 200;
     Real error, correct;
     Real epsilon,range;
     /* don't buffer output */
     setbuf(stdout,NULL);

     /* set seed to unique number */
     mikenet_set_seed(0);

     /* a default learning rate */
     epsilon=0.1;
  
     /* default weight range */
     range=0.5;

     default_errorRadius=0.0;

     /* what are the command line arguments? */
     for(i=1;i<argc;i++)
     {
          if (strcmp(argv[i],"-seed")==0)
          {
               mikenet_set_seed(atol(argv[i+1]));
               i++;
          }
          else if (strncmp(argv[i],"-epsilon",5)==0)
          {
               epsilon=atof(argv[i+1]);
               i++;
          }
          else if (strcmp(argv[i],"-range")==0)
          {
               range=atof(argv[i+1]);
               i++;
          }
          else if (strcmp(argv[i],"-errorRadius")==0)
          {
               default_errorRadius=atof(argv[i+1]);
               i++;
          }
          else if (strcmp(argv[i], "-f") == 0)
          {
               fileName = (char*)argv[i+1];
               i++;
          }
          else if (strcmp(argv[i], "-i") == 0)
          {
               inputCount = atoi(argv[i+1]);
               i++;
          }
          else if (strcmp(argv[i], "-o") == 0)
          {
               outputCount = atoi(argv[i+1]);
               i++;
          }
          else if (strcmp(argv[i], "-h") == 0)
          {
               hiddenCount = atoi(argv[i+1]);
               i++;
          }
          else
          {
               fprintf(stderr,"unknown argument: %s\n",argv[i]);
               exit(-1);
          }

     }
  
     /* build a network, with TIME number of time ticks */
     net=create_net(TIME);
  
     /* learning rate */
     default_epsilon=epsilon;

     /* create our groups.  
        format is: name, num of units, ticks */

     input=init_group("Input",inputCount,TIME);
     hidden=init_group("hidden",hiddenCount,TIME);
     output=init_group("Output",outputCount,TIME);

     /* bias is special.  format is: value, ticks */
     bias=init_bias(1.0,TIME);   

     /* now add our groups to the network object */
     bind_group_to_net(net,input);
     bind_group_to_net(net,hidden);
     bind_group_to_net(net,output);
     bind_group_to_net(net,bias);

     /* now connect our groups, instantiating */
     /* connection objects c1 through c4 */
     c1=connect_groups(input,hidden);
     c2=connect_groups(hidden,output);
     c3=connect_groups(bias,hidden);
     c4=connect_groups(bias,output);

     /* add connections to our network */
     bind_connection_to_net(net,c1);
     bind_connection_to_net(net,c2);
     bind_connection_to_net(net,c3);
     bind_connection_to_net(net,c4);

     /* randomize the weights in the connection objects.
        2nd argument is weight range. */
     randomize_connections(c1,range);
     randomize_connections(c2,range);
     randomize_connections(c3,range);
     randomize_connections(c4,range);

     /* how to load and save weights */
     /*  load_weights(net,"init.weights");   */
  
     /* erase old initial weight file */
     /*  system("rm -f init.weights.Z");      */

     /* save out our weights to file 'init.weights' */
     /*  save_weights(net,"init.weights");     */

     /* load in our example set */
     fprintf(stderr, "Reading %s\n",fileName);
     examples=load_examples(fileName,TIME);
     fprint(stderr, "Input: %d, Output: %d",);
     error=0.0;
     count=0;
     /* loop for ITER number of times */
     for(i=0;i<ITER;i++)
     {
          /* get j'th example from exampleset */
          ex=get_random_example(examples);
          /* do forward propagation */
          bptt_forward(net,ex);

          /* backward pass: compute gradients */
          bptt_compute_gradients(net,ex);
      
          /* sum up error for this example */
          error+=compute_error(net,ex);

          /* online learning: apply the deltas 
             from previous call to compute_gradients */
          bptt_apply_deltas(net);

          /* is it time to write status? */
          if (count==REP)
          {
               /* average error over last 'count' iterations */
               error = error/(float)count;
               count=0;

               /* print a message about average error so far */
               fprintf(stderr, "%d\t%f\n",i,error);

               if (error < 0.01)
               {
                    break;
               }

               /* zero error; start counting again */
               error=0.0;
          }
          count++;
     }
     /* done training.  write out results for each example */
     correct = 0;
     for(i=0;i<examples->numExamples;i++)
     {
          ex=&examples->examples[i];
          bptt_forward(net,ex);
          int maxj = -1;
          Real  maxx = 0;
          for(j=0 ; j < outputCount; j++){
               if (output->outputs[TIME-1][j] > maxx){
                    maxj = j;
                    maxx = output->outputs[TIME-1][j];
               }
               /* printf("%d:%f ",j,output->outputs[TIME-1][j]); */
          }
          /* printf("max:%d\n",maxj); */
          if (get_value(ex->targets,output->index,TIME-1,maxj) == 1)
               correct += 1;
          printf("i:%d g:%f cor:%f\n",i, get_value(ex->targets,output->index,TIME-1,maxj),correct / (i+1));
          /* printf("example %d\tinputs %f\t%f\toutput %f\ttarget %f\n", */
          /*     i, */
          /*        get_value(ex->inputs,input->index,TIME-1,0), */
          /*        get_value(ex->inputs,input->index,TIME-1,1), */
          /*        output->outputs[TIME-1][0], */
          /*        get_value(ex->targets,output->index,TIME-1,0)); */
      
     }
     fprintf(stderr,"Acc:%f\n", correct / examples->numExamples);
     return 0;
}