コード例 #1
0
ファイル: solver.c プロジェクト: frostburn/tinytsumego
void repair(int argc, char *argv[]) {
    if (argc != 2) {
        printf("Please enter a filename.\n");
        return;
    }
    char capture_filename[128];
    char japanese_filename[128];
    char temp_filename[128];
    sprintf(capture_filename, "%s_capture.dat", argv[1]);
    sprintf(japanese_filename, "%s_japanese.dat", argv[1]);
    sprintf(temp_filename, "%s_temp.dat", argv[1]);


    solution sol_;
    solution *sol = &sol_;
    char *buffer = file_to_buffer(capture_filename);
    buffer = load_solution(sol, buffer, 1);
    print_state(sol->base_state);
    calculate_leaves(sol);

    solution solj_;
    solution *solj = &solj_;
    buffer = file_to_buffer(japanese_filename);
    buffer = load_solution(solj, buffer, 1);
    print_state(solj->base_state);
    solj->leaf_nodes = sol->leaf_nodes;

    FILE *f = fopen(temp_filename, "wb");
    save_solution(solj, f);
    fclose(f);
    printf("Done!\n");
}
コード例 #2
0
ファイル: loadavg.c プロジェクト: GNOME/libgtop
void
glibtop_get_loadavg_s (glibtop *server, glibtop_loadavg *buf)
{
	char buffer [BUFSIZ], *p, *old;

	memset (buf, 0, sizeof (glibtop_loadavg));

	file_to_buffer(server, buffer, sizeof buffer, FILENAME);

	buf->loadavg [0] = g_ascii_strtod (buffer, &p);
	buf->loadavg [1] = g_ascii_strtod (p, &p);
	buf->loadavg [2] = g_ascii_strtod (p, &p);

	buf->flags = _glibtop_sysdeps_loadavg;

	p = next_token(p);

	/* Older Linux versions don't have the nr_running/nr_tasks fields. */

	old = p;
	while (*p) {
		if (*p == '/')
			break;
		if (!isdigit (*p))
			return;
		p++;
	}

	buf->nr_running  = strtoull (old, &p, 0); p++;
	buf->nr_tasks    = strtoull (p, &p, 0);
	buf->last_pid    = strtoull (p, &p, 0);

	buf->flags |= _glibtop_sysdeps_loadavg_tasks;
}
コード例 #3
0
ファイル: tcp_utils.c プロジェクト: OniOni/VideoServ
int send_image_tcp(int sock, int image, char * rep)
{
  int len, len_buff, sent;
  char str[32], *buff_ima;
  sprintf(str, "%s/%d.jpg", rep, image);

  file_to_buffer(str, &buff_ima, &len);
  errno = 0;

  char buff[100];

  sprintf(buff, "%d\r\n%d\r\n", image, len);

  sent = len_buff = strlen(buff);

  do{
    sent -= send(sock, buff, len_buff, MSG_MORE);
  }
  while(sent > 0);

  sent = len;
  sent = send(sock, buff_ima, len, 0);

  free(buff_ima);
  perror("free");
}
コード例 #4
0
ファイル: med.c プロジェクト: jbebe/all-my-projects
int main(int argc, char **args)
{
	RAND = ((int)time(NULL))%10;
	init_console();
	init_buffer();
	init_clipboard();
	if (argc > 1)
	{
		FILENAME = (unsigned char *)malloc(256*sizeof(char));
		strcpy((char *)FILENAME, args[1]);
		file_to_buffer();
	}
	else 
	{
		MAX_VPOS = 1;
	}
	while (RUN)
	{
		redraw_screen();
#ifdef DEBUG_MODE
		printf("%d", INPUT_KEY);
#endif
		INPUT_KEY = _getch();
		process_key();
	}
	DestroyAndExit("Exiting...");
	return 0;
}
コード例 #5
0
ファイル: text.c プロジェクト: sb057/hexchat
static void
scrollback_shrink (session *sess)
{
	char file[1024];
	char *buf;
	int fh;
	int lines;
	int line;
	int len;
	char *p;

	scrollback_close (sess);
	sess->scrollwritten = 0;
	lines = 0;

	if (scrollback_get_filename (sess, file, sizeof (file)) == NULL)
		return;

	buf = file_to_buffer (file, &len);
	if (!buf)
		return;

	/* count all lines */
	p = buf;
	while (p != buf + len)
	{
		if (*p == '\n')
			lines++;
		p++;
	}

	fh = open (file, O_CREAT | O_TRUNC | O_APPEND | O_WRONLY, 0644);
	if (fh == -1)
	{
		free (buf);
		return;
	}

	line = 0;
	p = buf;
	while (p != buf + len)
	{
		if (*p == '\n')
		{
			line++;
			if (line >= lines - prefs.max_lines &&
				 p + 1 != buf + len)
			{
				p++;
				write (fh, p, len - (p - buf));
				break;
			}
		}
		p++;
	}

	close (fh);
	free (buf);
}
コード例 #6
0
ファイル: main.c プロジェクト: bilgin1812/hepiaOS
void sfsadd(sSuperStruct *s, char *name){
	printf("dans sfs add avec fichier : %s \n", name);
	if(fileExists(name)){
		int compteur=0;
		int add_taille=0; //addition des tailles->permet de récupérer la taille du bitmap
		int num_bit;
		//quelle place est encore disponible dans les files entries
		if(s->fe[0].size!=0)
		printf("le premier fichier est %s \n",s->fe[0].name);

		// CHECK_BIT(var, pos) ((var) &(1<<pos))
		while( CHECK_BIT(s->fe[compteur].name[0], 6) ){
		//while(s->fe[compteur].size!=0){
			//printf("parcours fichier %s",s->fe[compteur].name);
			compteur++;
		}
		printf("on recupere la taille des num_bit \n");
		num_bit=get_bit_free();
		printf("on a récuperer les bits \n");

		// printf("nous sommes au %d compteur et add_taille vaut %d num_bit %d \n", compteur, add_taille, num_bit);



		//récupération taille fichier
		struct stat st;

		stat(name, &st);
		printf("la taille du fichier est %d \n", st.st_size);
		strcpy(s->fe[compteur].name, name);
		s->fe[compteur].size=st.st_size;
		int num=0;
		//remplissage des bytes du bitmap
		int nbre_bloc= (st.st_size/1024)+1; //obtient le nombre de bloc == le nombre de bits du bitmap

		int byte_asked; //le byte du tab_bitmap sur lequel l'on travail
		byte buf[1024];
		init_byte(buf, 1024);
		int i, fp;
		fp=fopen(name, "r");
		for(i=num_bit; i<num_bit+nbre_bloc; i++){
			byte_asked= i/8; //quel byte de tabBitmap est affecté?
			s->fe[compteur].indexBlock[num]=i; //enregistre le numéro du bloc dans la file entries
			s->sbit.tabBitmap[byte_asked]=s->sbit.tabBitmap[byte_asked]^(1<<(i%8)); //enregistre la présence du fichier sur le bit XXX byte_asked
			printf("remplissage du tabBitmap et le byte vaut %d \n",s->sbit.tabBitmap[byte_asked]);
			fread(buf, 1024,1, fp); //lecture des bytes du fichier demandée
			printf("LE BUFFER contient %s \n", buf);

			file_to_buffer(s->fc.data[i], buf, 1024);
			printf("Après copies l'on a dans le tableau %s \n", s->fc.data[i]);
			num++;
		}

		fclose(fp);
	} else {
		printf("Fichier existe pas : %s \n\n", name);
	}
}
コード例 #7
0
ファイル: mem.c プロジェクト: JackOfMostTrades/jtop
void glibtop_get_mem (struct glibtop_mem *buf)
{
	char buffer [4096];

	file_to_buffer(buffer, sizeof buffer, FILENAME);

	buf->total  = get_scaled(buffer, "MemTotal:");
	buf->free   = get_scaled(buffer, "MemFree:");
	buf->used   = buf->total - buf->free;
}
コード例 #8
0
ファイル: solver.c プロジェクト: frostburn/tinytsumego
void upgrade(int argc, char *argv[]) {
    parse_args(argc - 1, argv + 1);

    solution sol_;
    solution *sol = &sol_;
    char *buffer = file_to_buffer(tsumego_name);  // Not really a tsumego name. Needs extension too.
    buffer = load_solution(sol, buffer, 1);

    if (sol->si->color_symmetry) {
        num_layers = 2 * abs(ko_threats) + 1;
    }
    else if (num_layers <= 0) {
        num_layers = abs(ko_threats) + 1;
    }

    sol->base_nodes = (node_value**) realloc(sol->base_nodes, sol->num_layers * sizeof(node_value*));
    sol->ko_nodes = (node_value**) realloc(sol->ko_nodes, sol->num_layers * sizeof(node_value*));

    size_t zero_layer = abs(sol->base_state->ko_threats);
    size_t new_zero_layer = abs(ko_threats);

    sol->base_nodes[new_zero_layer] = sol->base_nodes[zero_layer];
    sol->ko_nodes[new_zero_layer] = sol->ko_nodes[zero_layer];

    sol->base_state->ko_threats = ko_threats;
    sol->num_layers = num_layers;

    size_t num_states = num_keys(sol->d);
    for (size_t k = 0; k < sol->num_layers; k++) {
        if (k == new_zero_layer) {
            continue;
        }
        sol->base_nodes[k] = (node_value*) malloc(num_states * sizeof(node_value));
        for (size_t i = 0; i < num_states; i++) {
            (sol->base_nodes[k])[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
    }

    for (size_t k = 0; k < sol->num_layers; k++) {
        if (k == new_zero_layer) {
            continue;
        }
        sol->ko_nodes[k] = (node_value*) malloc(sol->ko_ld->num_keys * sizeof(node_value));
        for (size_t i = 0; i < sol->ko_ld->num_keys; i++) {
            sol->ko_nodes[k][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
    }

    FILE *f = fopen(tsumego_name, "wb");
    save_solution(sol, f);
    fclose(f);
    printf("Done!\n");
}
コード例 #9
0
ファイル: cpu.c プロジェクト: GNOME/libgtop
void
glibtop_get_cpu_s (glibtop *server, glibtop_cpu *buf)
{
	char buffer [BUFSIZ], *p;
	int i;

	memset (buf, 0, sizeof (glibtop_cpu));

	file_to_buffer(server, buffer, sizeof buffer, FILENAME);

	/*
	 * GLOBAL
	 */

	p = skip_token (buffer);	/* "cpu" */

	buf->user = strtoull (p, &p, 0);
	buf->nice = strtoull (p, &p, 0);
	buf->sys  = strtoull (p, &p, 0);
	buf->idle = strtoull (p, &p, 0);
	buf->total = buf->user + buf->nice + buf->sys + buf->idle;

	buf->frequency = 100;
	buf->flags = _glibtop_sysdeps_cpu;

	/*
	 * PER CPU
	 */

	for (i = 0; i <= server->ncpu; i++) {

		p = skip_line(p); /* move to ^ */

		if (!check_cpu_line_warn(server, p, i))
			break;

		p = skip_token(p); /* "cpuN" */

		buf->xcpu_user [i] = strtoull (p, &p, 0);
		buf->xcpu_nice [i] = strtoull (p, &p, 0);
		buf->xcpu_sys  [i] = strtoull (p, &p, 0);
		buf->xcpu_idle [i] = strtoull (p, &p, 0);
		buf->xcpu_total[i] = buf->xcpu_user [i] \
			+ buf->xcpu_nice [i] \
			+ buf->xcpu_sys  [i] \
			+ buf->xcpu_idle [i];
	}

	if(server->ncpu) /* ok, that's a real SMP */
		buf->flags |= _glibtop_sysdeps_cpu_smp;
}
コード例 #10
0
ファイル: pkg_manifest.c プロジェクト: dnaeon/pkgng
int
pkg_load_manifest_file(struct pkg *pkg, const char *fpath)
{
	char *manifest = NULL;
	off_t sz;
	int ret = EPKG_OK;

	if ((ret = file_to_buffer(fpath, &manifest, &sz)) != EPKG_OK)
		return (ret);

	ret = pkg_parse_manifest(pkg, manifest);
	free(manifest);

	return (ret);
}
コード例 #11
0
ファイル: udp_utils.c プロジェクト: OniOni/VideoServ
int send_image_udp(int sock, struct sockaddr_in dest, char * rep, int image, int frag_size)
{
  int len_ima = 0, len, sent = 0, read, start = 0, pos_pack = 0;
  char str[32], *buff_ima, header[32];
  errno = 0;
  sprintf(str, "%s/%d.jpg", rep, image);

  frag_size -= 100;

  file_to_buffer(str, &buff_ima, &len_ima);
  
  int num_frag = len_ima / frag_size;

  char * buff, * buff_fin = malloc((len_ima + 20) * sizeof(char));

  pos_pack = 0;
  do
  {
    //get next fragment
    read = get_fragment(buff_ima, len_ima, start, frag_size, &buff, &buff_fin);
    
    //build "header"
    sprintf(header, "%d\r\n%d\r\n%d\r\n%d\r\n", image, len_ima, start, read);
        
    len = strlen(header);

    //send "header"
    sendto(sock, header, len, MSG_MORE, (struct sockaddr*)&dest, sizeof(dest));
    
    //send fragment
    sent += sendto(sock, buff, read, 0, (struct sockaddr*)&dest, sizeof(dest));;      

    start += read;
    pos_pack += 1;
  }
  while(sent < len_ima);

  free(buff_ima);
  perror("free");
  free(buff);
  perror("free");
  free(buff_fin);
  perror("free");
}
コード例 #12
0
ファイル: rsa.c プロジェクト: HardenedBSD/pkg
int
rsa_verify(const char *path, const char *key, unsigned char *sig,
    unsigned int sig_len, int fd)
{
	int ret;
	bool need_close = false;
	struct rsa_verify_cbdata cbdata;
	char *key_buf;
	off_t key_len;

	if (file_to_buffer(key, (char**)&key_buf, &key_len) != EPKG_OK) {
		pkg_emit_errno("rsa_verify", "cannot read key");
		return (EPKG_FATAL);
	}

	if (fd == -1) {
		if ((fd = open(path, O_RDONLY)) == -1) {
			pkg_emit_errno("fopen", path);
			free(key_buf);
			return (EPKG_FATAL);
		}
		need_close = true;
	}
	(void)lseek(fd, 0, SEEK_SET);

	cbdata.key = key_buf;
	cbdata.keylen = key_len;
	cbdata.sig = sig;
	cbdata.siglen = sig_len;

	SSL_load_error_strings();
	OpenSSL_add_all_algorithms();
	OpenSSL_add_all_ciphers();

	ret = pkg_emit_sandbox_call(rsa_verify_cb, fd, &cbdata);
	if (need_close)
		close(fd);

	free(key_buf);

	return (ret);
}
コード例 #13
0
ファイル: central.c プロジェクト: OniOni/VideoServ
void send_get_answer(int fd)
{
  int size;
  char * buf = NULL;
  /*On recuper le fichier sous forme de chaine de cara*/
  file_to_buffer("catalogue.txt", &buf, &size);
  /*On construit l'entete HTML aproprié*/
  char * header = build_http_header("text/plain", size);

  /*Et on envoie les données*/
  puts("Going to send");
  send(fd, header, strlen(header), MSG_MORE);
  printf("send : %s\n", strerror(errno));
  send(fd, buf, size, 0);
  printf("send : %s\n", strerror(errno));

  /*On libere les ressources alloué*/
  free(header);
  free(buf);
}
コード例 #14
0
ファイル: pkg_add.c プロジェクト: WorldofOpenDev/pkg
static void
attempt_to_merge(bool renamed, struct pkg_config_file *rcf,
  struct pkg *local, char *pathname, const char *path, struct sbuf *newconf)
{
	const struct pkg_file *lf = NULL;
	struct pkg_config_file *lcf = NULL;

	char *localconf = NULL;
	size_t sz;
	char *localsum;

	if (!renamed) {
		pkg_debug(3, "Not renamed");
		return;
	}

	if (rcf == NULL) {
		pkg_debug(3, "No remote config file");
		return;
	}

	if (local == NULL) {
		pkg_debug(3, "No local package");
		return;
	}

	if (!pkg_is_config_file(local, path, &lf, &lcf)) {
		pkg_debug(3, "No local package");
		return;
	}

	if (lcf->content == NULL) {
		pkg_debug(3, "Empty configuration content for local package");
		return;
	}
	
	pkg_debug(1, "Config file found %s", pathname);
	file_to_buffer(pathname, &localconf, &sz);

	pkg_debug(2, "size: %d vs %d", sz, strlen(lcf->content));

	if (sz == strlen(lcf->content)) {
		pkg_debug(2, "Ancient vanilla and deployed conf are the same size testing checksum");
		localsum = pkg_checksum_data(localconf, sz,
		    PKG_HASH_TYPE_SHA256_HEX);
		if (localsum && strcmp(localsum, lf->sum) == 0) {
			pkg_debug(2, "Checksum are the same %d", strlen(localconf));
			free(localconf);
			free(localsum);
			return;
		}
		free(localsum);
		pkg_debug(2, "Checksum are different %d", strlen(localconf));
	}

	pkg_debug(1, "Attempting to merge %s", pathname);
	if (merge_3way(lcf->content, localconf, rcf->content, newconf) != 0) {
		pkg_emit_error("Impossible to merge configuration file");
		sbuf_clear(newconf);
		strlcat(pathname, ".pkgnew", MAXPATHLEN);
	}
	free(localconf);
}
コード例 #15
0
ファイル: solver.c プロジェクト: frostburn/tinytsumego
void test() {
    solution sol_;
    solution *sol = &sol_;
    char *buffer = file_to_buffer("cho589_capture.dat");
    buffer = load_solution(sol, buffer, 1);
    state s_;
    state *s = &s_;
    // sscanf_state("4337799298623 4335912108032 1879319553 0 1879048192 4335912108032 0 0 0", s);
    sscanf_state("4337799298623 4335918405632 1879319581 0 1879048192 4335912108032 0 0 0", s);
    print_state(s);
    size_t layer;
    size_t key = to_key_s(sol, s, &layer);
    // node_value v = negamax_node(sol, s, key, layer, 0);
    // print_node(v);
    // node_value v_b = sol->base_nodes[layer][key_index(sol->d, key)];
    // print_node(v_b);
    // endstate(sol, s, v, 0, 1);
    // print_state(s);

    state new_s_;
    state *new_s = &new_s_;
    *new_s = *s;
    node_value v = negamax_node(sol, s, key, 0, 0);
    endstate(sol, new_s, v, 0, 1);

    print_state(new_s);

    // Use a flood of life so that partially dead nakade won't give extra points.
    // Note while this won't mark dead groups as alive, it can treat living nakade stones as dead.
    stones_t player_alive = flood(new_s->player, s->player);
    stones_t opponent_alive = flood(new_s->opponent, s->opponent);

    print_stones(player_alive);
    print_stones(opponent_alive);

    int score;

    // First check if a target is not alive.
    stones_t player_target = s->player & s->target;
    stones_t opponent_target = s->opponent & s->target;
    if (opponent_target & ~opponent_alive) {
        assert(!(player_target & ~player_alive));  // Both shouldn't be dead.
        score = TARGET_SCORE;
    }
    else if (player_target & ~player_alive) {
        score = -TARGET_SCORE;
    }
    else {
        stones_t player_territory = 0;
        stones_t opponent_territory = 0;
        stones_t player_region_space = s->playing_area & ~player_alive;
        stones_t opponent_region_space = s->playing_area & ~opponent_alive;
        for (int j = 0; j < STATE_SIZE; j++) {
            stones_t p = 1ULL << j;
            stones_t region = flood(p, player_region_space);
            player_region_space ^= region;
            if (!(region & opponent_alive)) {
                player_territory |= region;
            }
            region = flood(p, opponent_region_space);
            opponent_region_space ^= region;
            if (!(region & player_alive)) {
                opponent_territory |= region;
            }
        }
        // Subtract friendly stones on the board from territory.
        player_territory &= ~s->player;
        opponent_territory &= ~s->opponent;
        score = popcount(player_territory) + popcount(player_territory & s->opponent) - popcount(opponent_territory) - popcount(opponent_territory & s->player);
    }
    printf("%d\n", score);
}
コード例 #16
0
ファイル: proc.c プロジェクト: nokute78/fluent-bit
struct proc_task *proc_stat(pid_t pid, int page_size)
{
    int ret;
    char *p, *q;
    char *buf;
    char pid_path[PROC_PID_SIZE];
    struct proc_task *t;

    t = flb_calloc(1, sizeof(struct proc_task));
    if (!t) {
        flb_errno();
        return NULL;
    }

    /* Compose path for /proc/PID/stat */
    ret = snprintf(pid_path, PROC_PID_SIZE, "/proc/%i/stat", pid);
    if (ret < 0) {
        flb_errno();
        return NULL;
    }

    buf = file_to_buffer(pid_path);
    if (!buf) {
        flb_free(t);
        return NULL;
    }

    sscanf(buf, "%d", &t->pid);

    /*
     * workaround for process with spaces in the name, so we dont screw up
     * sscanf(3).
     */
    p = buf;
    while (*p != '(') p++; p++;
    q = p;
    while (*q != ')') q++;
    strncpy(t->comm, p, q - p);
    q += 2;

    /* Read pending values */
    sscanf(q, PROC_STAT_FORMAT,
           &t->state,
           &t->ppid,
           &t->pgrp,
           &t->session,
           &t->tty_nr,
           &t->tpgid,
           &t->flags,
           &t->minflt,
           &t->cminflt,
           &t->majflt,
           &t->cmajflt,
           &t->utime,
           &t->stime,
           &t->cutime,
           &t->cstime,
           &t->priority,
           &t->nice,
           &t->num_threads,
           &t->itrealvalue,
           &t->starttime,
           &t->vsize,
           &t->rss);

    /* Internal conversion */
    t->proc_rss    = (t->rss * page_size);
    t->proc_rss_hr = human_readable_size(t->proc_rss);

    flb_free(buf);
    return t;
}
コード例 #17
0
ファイル: solver.c プロジェクト: frostburn/tinytsumego
int main(int argc, char *argv[]) {
    #ifdef TEST
        test();
        return 0;
    #endif
    #ifdef REPAIR
        repair(argc, argv);
        return 0;
    #endif
    #ifdef UPGRADE
        upgrade(argc, argv);
        return 0;
    #endif

    int load_sol = 0;
    int resume_sol = 0;
    if (strcmp(argv[argc - 1], "load") == 0) {
        load_sol = 1;
        argc--;
    }
    if (strcmp(argv[argc - 1], "resume") == 0) {
        resume_sol = 1;
        argc--;
    }
    parse_args(argc - 1, argv + 1);

    int width = board_width;
    int height = board_height;
    if (board_width >= 10) {
        fprintf(stderr, "Width must be less than 10.\n");
        exit(EXIT_FAILURE);
    }
    if (board_height >= 8) {
        fprintf(stderr, "Height must be less than 8.\n");
        exit(EXIT_FAILURE);
    }

    #include "tsumego.c"

    state base_state_;
    state *base_state = &base_state_;

    char sol_name[64] = "unknown";
    char temp_filename[128];
    char filename[128];
    if (board_width > 0) {
        *base_state = (state) {rectangle(width, height), 0, 0, 0, 0};
        sprintf(sol_name, "%dx%d", width, height);
    }
    else {
        int i;
        int found = 0;

        for (i = 0; tsumego_infos[i].name; ++i) {
            if (!strcmp(tsumego_name, tsumego_infos[i].name)) {
                *base_state = *(tsumego_infos[i].state);
                strcpy(sol_name, tsumego_name);
                found = 1;
                break;
            }
        }
        if (!found) {
            fprintf(stderr, "unknown tsumego: `%s'\n", tsumego_name);
            exit(EXIT_FAILURE);
        }
    }
    base_state->ko_threats = ko_threats;

    sprintf(temp_filename, "%s_temp.dat", sol_name);


    state_info si_;
    state_info *si = &si_;
    init_state(base_state, si);

    if (si->color_symmetry) {
        num_layers = 2 * abs(base_state->ko_threats) + 1;
    }
    else if (num_layers <= 0) {
        num_layers = abs(base_state->ko_threats) + 1;
    }
    else {
        assert(num_layers >= abs(base_state->ko_threats) + 1);
    }

    print_state(base_state);
    for (int i = 0; i < si->num_external; i++) {
        print_stones(si->externals[i]);
    }
    printf(
        "width=%d height=%d c=%d v=%d h=%d d=%d\n",
        si->width,
        si->height,
        si->color_symmetry,
        si->mirror_v_symmetry,
        si->mirror_h_symmetry,
        si->mirror_d_symmetry
    );

    state s_;
    state *s = &s_;

    dict d_;
    dict *d = &d_;

    solution sol_;
    solution *sol = &sol_;
    sol->base_state = base_state;
    sol->si = si;
    sol->d = d;
    sol->num_layers = num_layers;
    size_t num_states;

    // Re-used at frontend. TODO: Allocate a different pointer.
    state child_;
    state *child = &child_;

    if (load_sol) {
        goto frontend;
    }

    if (resume_sol) {
        char *buffer = file_to_buffer(temp_filename);
        buffer = load_solution(sol, buffer, 1);
        num_states = num_keys(sol->d);
        if (sol->leaf_rule == japanese_double_liberty) {
            goto iterate_capture;
        }
        else {
            goto iterate_japanese;
        }
    }

    size_t k_size = key_size(sol->si);
    if (!sol->si->color_symmetry) {
        k_size *= 2;
    }
    init_dict(sol->d, k_size);

    size_t total_legal = 0;
    for (size_t k = 0; k < k_size; k++) {
        if (!from_key_s(sol, s, k, 0)){
            continue;
        }
        total_legal++;
        size_t layer;
        size_t key = to_key_s(sol, s, &layer);
        assert(layer == 0);
        add_key(sol->d, key);
    }
    finalize_dict(sol->d);
    num_states = num_keys(sol->d);

    printf("Total positions %zu\n", total_legal);
    printf("Total unique positions %zu\n", num_states);

    node_value **base_nodes = (node_value**) malloc(sol->num_layers * sizeof(node_value*));
    for (size_t i = 0; i < sol->num_layers; i++) {
        base_nodes[i] = (node_value*) malloc(num_states * sizeof(node_value));
    }
    value_t *leaf_nodes = (value_t*) malloc(num_states * sizeof(value_t));

    lin_dict ko_ld_ = (lin_dict) {0, 0, 0, NULL};
    lin_dict *ko_ld = &ko_ld_;

    sol->base_nodes = base_nodes;
    sol->leaf_nodes = leaf_nodes;
    sol->ko_ld = ko_ld;

    size_t child_key;
    size_t key = sol->d->min_key;
    for (size_t i = 0; i < num_states; i++) {
        assert(from_key_s(sol, s, key, 0));
        // size_t layer;
        // assert(to_key_s(sol, s, &layer) == key);
        sol->leaf_nodes[i] = 0;
        for (size_t k = 0; k < sol->num_layers; k++) {
            (sol->base_nodes[k])[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
        for (int j = 0; j < STATE_SIZE; j++) {
            *child = *s;
            int prisoners;
            if (make_move(child, 1ULL << j, &prisoners)) {
                if (target_dead(child)) {
                    continue;
                }
                if (child->ko) {
                    size_t child_layer;
                    child_key = to_key_s(sol, child, &child_layer);
                    add_lin_key(sol->ko_ld, child_key);
                }
            }
        }
        key = next_key(sol->d, key);
    }

    finalize_lin_dict(sol->ko_ld);

    node_value **ko_nodes = (node_value**) malloc(sol->num_layers * sizeof(node_value*));
    sol->ko_nodes = ko_nodes;
    for (size_t i = 0; i < sol->num_layers; i++) {
        sol->ko_nodes[i] = (node_value*) malloc(sol->ko_ld->num_keys * sizeof(node_value));
    }
    printf("Unique positions with ko %zu\n", sol->ko_ld->num_keys);

    for (size_t i = 0; i < sol->ko_ld->num_keys; i++) {
        for (size_t k = 0; k < sol->num_layers; k++) {
            sol->ko_nodes[k][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
    }

    #ifdef CHINESE
    printf("Negamax with Chinese rules.\n");
    sol->count_prisoners = 0;
    sol->leaf_rule = chinese_liberty;
    iterate(sol, temp_filename);
    #endif

    // NOTE: Capture rules may refuse to kill stones when the needed nakade sacrifices exceed triple the number of stones killed.
    printf("Negamax with capture rules.\n");
    sol->count_prisoners = 1;
    sol->leaf_rule = japanese_double_liberty;
    iterate_capture:
    iterate(sol, temp_filename);

    sprintf(filename, "%s_capture.dat", sol_name);
    FILE *f = fopen(filename, "wb");
    save_solution(sol, f);
    fclose(f);


    calculate_leaves(sol);

    // Clear the rest of the tree.
    for (size_t j = 0; j < sol->num_layers; j++) {
        for (size_t i = 0; i < num_states; i++) {
            sol->base_nodes[j][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
        for (size_t i = 0; i < sol->ko_ld->num_keys; i++) {
            sol->ko_nodes[j][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
    }

    printf("Negamax with Japanese rules.\n");
    sol->count_prisoners = 1;
    sol->leaf_rule = precalculated;
    iterate_japanese:
    iterate(sol, temp_filename);

    sprintf(filename, "%s_japanese.dat", sol_name);
    f = fopen(filename, "wb");
    save_solution(sol, f);
    fclose(f);

    frontend:
    if (load_sol) {
        sprintf(filename, "%s_japanese.dat", sol_name);
        char *buffer = file_to_buffer(filename);
        buffer = load_solution(sol, buffer, 1);
    }

    *s = *sol->base_state;

    char coord1;
    int coord2;

    int total_prisoners = 0;
    int turn = 0;

    while (1) {
        size_t layer;
        size_t key = to_key_s(sol, s, &layer);
        node_value v = negamax_node(sol, s, key, layer, 0);
        print_state(s);
        if (turn) {
            print_node((node_value) {total_prisoners - v.high, total_prisoners - v.low, v.high_distance, v.low_distance});
        }
        else {
            print_node((node_value) {total_prisoners + v.low, total_prisoners + v.high, v.low_distance, v.high_distance});
        }
        if (target_dead(s) || s->passes >= 2) {
            break;
        }
        for (int j = -1; j < STATE_SIZE; j++) {
            *child = *s;
            stones_t move;
            if (j == -1){
                move = 0;
            }
            else {
                move = 1ULL << j;
            }
            char c1 = 'A' + (j % WIDTH);
            char c2 = '0' + (j / WIDTH);
            int prisoners;
            if (make_move(child, move, &prisoners)) {
                size_t child_layer;
                size_t child_key = to_key_s(sol, child, &child_layer);
                node_value child_v = negamax_node(sol, child, child_key, child_layer, 0);
                if (sol->count_prisoners) {
                    if (child_v.low > VALUE_MIN && child_v.low < VALUE_MAX) {
                        child_v.low = child_v.low - prisoners;
                    }
                    if (child_v.high > VALUE_MIN && child_v.high < VALUE_MAX) {
                        child_v.high = child_v.high - prisoners;
                    }
                }
                if (move) {
                    printf("%c%c", c1, c2);
                }
                else {
                    printf("pass");
                }
                if (-child_v.high == v.low) {
                    printf("-");
                    if (child_v.high_distance + 1 == v.low_distance) {
                        printf("L");
                    }
                    else {
                        printf("l");
                    }
                }
                if (-child_v.high == v.low) {
                    printf("-");
                    if (child_v.low_distance + 1 == v.high_distance) {
                        printf("H");
                    }
                    else {
                        printf("h");
                    }
                }
                printf(" ");
            }
        }
        printf("\n");
        printf("Enter coordinates:\n");
        assert(scanf("%c %d", &coord1, &coord2));
        int c;
        while ((c = getchar()) != '\n' && c != EOF);
        coord1 = tolower(coord1) - 'a';
        stones_t move;
        if (coord1 < 0 || coord1 >= WIDTH) {
            // printf("%d, %d\n", coord1, coord2);
            move = 0;
        }
        else {
            move = 1ULL << (coord1 + V_SHIFT * coord2);
        }
        int prisoners;
        if (make_move(s, move, &prisoners)) {
            if (turn) {
                total_prisoners -= prisoners;
            }
            else {
                total_prisoners += prisoners;
            }
            turn = !turn;
        }
    }

    return 0;
}
コード例 #18
0
ファイル: cygwin.c プロジェクト: juntalis/cygwin-virtualenv
static wchar_t* readlink(wchar_t* path)
{
	size_t szbuf = 0;
	wchar_t* result = path;
	char* cygbuf = NULL;
	byte* buffer = NULL;
	pcyglink slink = NULL;
	
	verbose(L"Checking %s for symbolic link..", path);
	
	// Make sure path is a file flagged as a system file.
	if(!is_file(path) || !has_system_attr(path)) goto cleanup;
	
	// Allocate our buffer and read the file into it.
	buffer = file_to_buffer(path, &szbuf);
	
	// Check if our buffer contains a symbolic link.
	if(!is_buf_symlink(buffer, szbuf)) goto cleanup;
	
	// If we get to this point, we're definitely working
	// with a symbolic link, so cast it to the struct.
	verbose(L"Detected symbolic link..");
	slink = (pcyglink)buffer;
	
	// Get the string length of our link's target.
	szbuf = wcslen(slink->target);
	if(szbuf == 0) {
		fatal(1, L"Empty path found as target of the symbolic link at %s.", path);
	}
	
	// Before converting it, we need to check whether it's a relative
	// or absolute file path.
	if(slink->target[0] != L'/') {
		verbose(L"Symbolic link target resolved to a relative path. Prefixing bin dir..");
		virtRootCyg = fix_path(virtRootWin);
		// len(virtualenv root) + len('/bin/') + len(target)
		szbuf += wcslen(virtRootCyg) + 5;
		result = walloc(szbuf++);
		swprintf(result, szbuf, L"%s/bin/%s", virtRootCyg, slink->target);
	} else {
		// Duping it to allow freeing the memory a few
		// lines later without issue.
		verbose(L"Symbolic link target appears to be an absolute path. Continuing..");
		result = _wcsdup(slink->target);
	}
	
	// Convert it to a ANSI string to allow converting
	// it with cygwin.
	cygbuf = xalloc(szbuf, sizeof(char));
	wcstombs(cygbuf, result, szbuf+1);
	xfree(result);
	if(!(result = fix_path_type((void*)cygbuf, false, CCP_POSIX_TO_WIN_A))) {
		result = path;
		goto cleanup;
	}
	verbose_step(L"readlink(x)");
	verbose_step(L"  x -> %s", path);
	verbose_step(L"  r <- %s", result);
cleanup:
	xfree(buffer);
	xfree(cygbuf);
	#ifdef WITHOUT_ENVVARS
	xfree(virtRootCyg);
	#endif
	return result;
}
コード例 #19
0
v8::Handle<v8::Value> Compile(v8::Arguments const &args)
{
    texture_compiler_args_t    tcarg;
    texture_compiler_inputs_t  tcinp;
    texture_compiler_outputs_t tcout;
    image::buffer_t            image;
    v8::HandleScope            scope;
    v8::Local<v8::Object>      params = args[0]->ToObject();

    // extract the arguments into something we can work with
    // without V8; verify that required arguments are present.
    v8::Handle<v8::Value> r1 = v8_object_to_compiler_args(params, &tcarg);
    if (!r1->IsUndefined())
    {
        // an exception was thrown. return it.
        free_compiler_args(&tcarg);
        return scope.Close(v8::ThrowException(r1));
    }

    // load the image from the specified source file.
    if (!file_to_buffer(tcarg.source_path, &image))
    {
        free_compiler_args(&tcarg);
        return scope.Close(ex("Cannot load file specified by sourcePath."));
    }

    // validate the arguments against the image properties.
    v8::Handle<v8::Value> r2 = validate_arguments(&tcarg, &image);
    if (!r2->IsUndefined())
    {
        // an exception was thrown. return it.
        free_buffer(&image);
        free_compiler_args(&tcarg);
        return scope.Close(v8::ThrowException(r2));
    }

    // set up the inputs to the texture compiler.
    texture_compiler_inputs_init(&tcinp);
    texture_compiler_outputs_init(&tcout);
    tcinp.input_image    = &image;
    tcinp.border_mode    = border_sample_mode(tcarg.border_mode);
    tcinp.target_width   = tcarg.target_width;
    tcinp.target_height  = tcarg.target_height;
    tcinp.maximum_levels = tcarg.level_count;
    tcinp.build_mipmaps  = tcarg.build_mipmaps;
    tcinp.force_pow2     = tcarg.force_pow2;
    tcinp.premultiply_a  = tcarg.premultiplied;
    tcinp.flip_y         = tcarg.flip_y;

    // build the texture data.
    if (!compile_texture(&tcinp, &tcout))
    {
        free_compiler_args(&tcarg);
        return scope.Close(v8::ThrowException(ex(tcout.error_message)));
    }

    // write the raw texture data.
    size_t                 nlevels  = tcout.level_count;
    size_t                 channels = tcout.channel_count;
    int32_t                format   = texture_format(tcarg.target_format, channels);
    char const            *target   = tcarg.target_path;
    v8::Handle<v8::Array>  levels   = v8::Array::New((int) nlevels);
    v8::Handle<v8::Value>  r3       = v8_output_raw(target, format, levels, &tcout);
    if (!r3->IsUndefined())
    {
        texture_compiler_outputs_free(&tcout);
        free_buffer(&image);
        free_compiler_args(&tcarg);
        return scope.Close(v8::ThrowException(r3));
    }

    // build the object to return to JavaScript.
    v8::Handle<v8::Object> metadata = output_to_v8_object(&tcarg, &tcout, levels);

    // release resources that are no longer needed.
    texture_compiler_outputs_free(&tcout);
    free_buffer(&image);
    free_compiler_args(&tcarg);

    return scope.Close(metadata);
}