void dogoto_command(const char *arg, struct session *ses) { char A[BUFFER_SIZE], B[BUFFER_SIZE], distvar[BUFFER_SIZE], locvar[BUFFER_SIZE], pathvar[BUFFER_SIZE]; char left[BUFFER_SIZE], right[BUFFER_SIZE], tmp[BUFFER_SIZE], cond[BUFFER_SIZE]; int a, b, i, j, s; int d[MAX_LOCATIONS], ok[MAX_LOCATIONS], way[MAX_LOCATIONS]; char path[BUFFER_SIZE], *pptr; arg=get_arg(arg, A, 0, ses); arg=get_arg(arg, B, 0, ses); arg=get_arg(arg, distvar, 0, ses); arg=get_arg(arg, locvar, 0, ses); arg=get_arg(arg, pathvar, 0, ses); if ((!*A)||(!*B)) { tintin_eprintf(ses, "#SYNTAX: #dogoto <from> <to> [<distvar> [<locvar> [<pathvar>]]] [#else ...]"); return; } bool flag=*distvar||*locvar||*pathvar; for (a=0;a<MAX_LOCATIONS;a++) if (ses->locations[a]&&!strcmp(ses->locations[a], A)) break; if (a==MAX_LOCATIONS) goto not_found; for (b=0;b<MAX_LOCATIONS;b++) if (ses->locations[b]&&!strcmp(ses->locations[b], B)) break; if (b==MAX_LOCATIONS) goto not_found; for (i=0;i<MAX_LOCATIONS;i++) { d[i]=INF; ok[i]=0; } d[a]=0; do { s=INF; for (j=0;j<MAX_LOCATIONS;j++) if (!ok[j]&&(d[j]<s)) s=d[i=j]; if (s==INF) goto not_found; ok[i]=1; for (struct routenode *r=ses->routes[i];r;r=r->next) if (d[r->dest]>s+r->distance) { if (!*(r->cond)) goto good; substitute_vars(r->cond, tmp); substitute_myvars(tmp, cond, ses); if (eval_expression(cond, ses)) { good: d[r->dest]=s+r->distance; way[r->dest]=i; } } } while (!ok[b]); sprintf(tmp, "%d", d[b]); if (*distvar) set_variable(distvar, tmp, ses); j=0; for (i=b;i!=a;i=way[i]) d[j++]=i; d[j]=a; pptr=path; for (i=j;i>=0;i--) pptr+=snprintf(pptr, path-pptr+BUFFER_SIZE, " %s", ses->locations[d[i]]); pptr=path+(pptr!=path); if (*locvar) set_variable(locvar, pptr, ses); pptr=path; for (i=j;i>0;i--) { for (struct routenode *r=ses->routes[d[i]];r;r=r->next) if (r->dest==d[i-1]) { if (flag) pptr+=snprintf(pptr, path-pptr+BUFFER_SIZE, " {%s}", r->path); else { tintin_printf(ses, "%-10s>%-10s {%s}", ses->locations[d[i]], ses->locations[d[i-1]], r->path); } } } pptr=path+(pptr!=path); if (*pathvar) set_variable(pathvar, pptr, ses); return; not_found: arg=get_arg_in_braces(arg, left, 0); if (*left == tintin_char) { if (is_abrev(left + 1, "else")) { get_arg_in_braces(arg, right, 1); parse_input(right, true, ses); return; } if (is_abrev(left + 1, "elif")) { if_command(arg, ses); return; } } if (*left) tintin_eprintf(ses, "#ERROR: cruft after #dogoto: {%s}", left); if (!flag) tintin_printf(ses, "No paths from %s to %s found.", A, B); }
int main(int argc, char *argv[]) { long arg_max; int ch, Jflag, nargs, nflag, nline; size_t linelen; char *endptr; inpline = replstr = NULL; ep = environ; eofstr = ""; Jflag = nflag = 0; (void)setlocale(LC_ALL, ""); /* * POSIX.2 limits the exec line length to ARG_MAX - 2K. Running that * caused some E2BIG errors, so it was changed to ARG_MAX - 4K. Given * that the smallest argument is 2 bytes in length, this means that * the number of arguments is limited to: * * (ARG_MAX - 4K - LENGTH(utility + arguments)) / 2. * * We arbitrarily limit the number of arguments to 5000. This is * allowed by POSIX.2 as long as the resulting minimum exec line is * at least LINE_MAX. Realloc'ing as necessary is possible, but * probably not worthwhile. */ nargs = 5000; if ((arg_max = sysconf(_SC_ARG_MAX)) == -1) errx(1, "sysconf(_SC_ARG_MAX) failed"); nline = arg_max - 4 * 1024; while (*ep != NULL) { /* 1 byte for each '\0' */ nline -= strlen(*ep++) + 1 + sizeof(*ep); } maxprocs = 1; while ((ch = getopt(argc, argv, "0E:I:J:L:n:oP:pR:S:s:rtx")) != -1) switch (ch) { case 'E': eofstr = optarg; break; case 'I': Jflag = 0; Iflag = 1; Lflag = 1; replstr = optarg; break; case 'J': Iflag = 0; Jflag = 1; replstr = optarg; break; case 'L': Lflag = atoi(optarg); break; case 'n': nflag = 1; if ((nargs = atoi(optarg)) <= 0) errx(1, "illegal argument count"); break; case 'o': oflag = 1; break; case 'P': if ((maxprocs = atoi(optarg)) <= 0) errx(1, "max. processes must be >0"); break; case 'p': pflag = 1; break; case 'R': Rflag = strtol(optarg, &endptr, 10); if (*endptr != '\0') errx(1, "replacements must be a number"); break; case 'r': /* GNU compatibility */ break; case 'S': Sflag = strtoul(optarg, &endptr, 10); if (*endptr != '\0') errx(1, "replsize must be a number"); break; case 's': nline = atoi(optarg); break; case 't': tflag = 1; break; case 'x': xflag = 1; break; case '0': zflag = 1; break; case '?': default: usage(); } argc -= optind; argv += optind; if (!Iflag && Rflag) usage(); if (!Iflag && Sflag) usage(); if (Iflag && !Rflag) Rflag = 5; if (Iflag && !Sflag) Sflag = 255; if (xflag && !nflag) usage(); if (Iflag || Lflag) xflag = 1; if (replstr != NULL && *replstr == '\0') errx(1, "replstr may not be empty"); pids_init(); /* * Allocate pointers for the utility name, the utility arguments, * the maximum arguments to be read from stdin and the trailing * NULL. */ linelen = 1 + argc + nargs + 1; if ((av = bxp = malloc(linelen * sizeof(char **))) == NULL) errx(1, "malloc failed"); /* * Use the user's name for the utility as argv[0], just like the * shell. Echo is the default. Set up pointers for the user's * arguments. */ if (*argv == NULL) cnt = strlen(*bxp++ = echo); else { do { if (Jflag && strcmp(*argv, replstr) == 0) { char **avj; jfound = 1; argv++; for (avj = argv; *avj; avj++) cnt += strlen(*avj) + 1; break; } cnt += strlen(*bxp++ = *argv) + 1; } while (*++argv != NULL); } /* * Set up begin/end/traversing pointers into the array. The -n * count doesn't include the trailing NULL pointer, so the malloc * added in an extra slot. */ endxp = (xp = bxp) + nargs; /* * Allocate buffer space for the arguments read from stdin and the * trailing NULL. Buffer space is defined as the default or specified * space, minus the length of the utility name and arguments. Set up * begin/end/traversing pointers into the array. The -s count does * include the trailing NULL, so the malloc didn't add in an extra * slot. */ nline -= cnt; if (nline <= 0) errx(1, "insufficient space for command"); if ((bbp = malloc((size_t)(nline + 1))) == NULL) errx(1, "malloc failed"); ebp = (argp = p = bbp) + nline - 1; for (;;) parse_input(argc, argv); }
int main (int argc, char **argv) { sdhn_t net = NULL; /* Neural Network */ unsigned int N = 0, /* # of neurons in the net */ C = 0, /* # of neighbours per neuron */ Pmax = 0, /* max # of memories to store */ Phop = 0; /* step increment in the # of memories */ int nu = 0, /* current memory to overlap with */ p = 0, /* current # of memories in the net */ k = 0; double overlap = 0.0; parse_input (argc, argv, &N, &C, &Pmax, &Phop); #ifdef PP printf ("\nVersion ULTRA DILUIDA del modelo de HOPFIELD para " "redes neuronales\n\nArgumentos recibidos:\n" "\ta) # de neuronas de la red:\t\t\t%u\n" "\tb) # de vecinos por neurona:\t\t\t%u\n" "\tc) Máximo # de memorias de la red:\t\t%u\n" "\td) Magnitud del salto en el # de memorias:\t%u\n", N, C, Pmax, Phop); printf ("\n____________________________________________________________" "_____\n| α'\t|\t μ\t\t|\t σ²\t\t|\n|~~~~~~~~~" "~~~~~~|~~~~~~~~~~~~~~~~~~~~~~~|~~~~~~~~~~~~~~~~~~~~~~~|\n"); #endif for (p = Phop ; p <= Pmax ; p += Phop) { /* Create new network with 'p' memories */ net = sdhn_create (N, p, C); sdhn_set_traced (net, TRACED); sdhn_set_untraced (net, UNTRACED); /* Restart statistical values */ reset_media_m (); reset_var_m (); nu = 0; for (k=0 ; k<KMAX ; k++) { /* Choose a new memory to overlap with */ if (--nu < 0) { sdhn_init_XI (net); nu = p-1; /* NOTE * ¿Estas 2 actualizaciones pueden ir acá? * ¿O hay que hacerlas en todas las vueltas? */ sdhn_init_neigh (net); sdhn_init_w (net); } sdhn_init_S (net, nu); /* Run the network for TRACED time intervals */ overlap = sdhn_run_net (net, nu); media_m (overlap , k+1); var_m (overlap , k+1); } net = sdhn_destroy (net); #ifdef PP printf ("| %.8f\t|\t%.8f\t|\t%.8f\t|\n", ((double)p) / ((double)C), get_media_m(), get_var_m()); #else printf ("%.8f\t%.8f\t%.8f\t\n", ((double)p) / ((double)C), get_media_m(), get_var_m()); #endif } #ifdef PP printf ("============================================================" "=====\nFin del programa\n\n"); #endif return 0; }
/** * rarch_main_init: * @argc : Count of (commandline) arguments. * @argv : (Commandline) arguments. * * Initializes RetroArch. * * Returns: 0 on success, otherwise 1 if there was an error. **/ int rarch_main_init(int argc, char *argv[]) { int sjlj_ret; global_t *global = global_get_ptr(); init_state(); if ((sjlj_ret = setjmp(global->error_sjlj_context)) > 0) { RARCH_ERR("Fatal error received in: \"%s\"\n", global->error_string); return sjlj_ret; } global->error_in_init = true; parse_input(argc, argv); if (global->verbosity) { char str[PATH_MAX_LENGTH] = {0}; RARCH_LOG_OUTPUT("=== Build ======================================="); rarch_info_get_capabilities(RARCH_CAPABILITIES_CPU, str, sizeof(str)); fprintf(stderr, "%s", str); fprintf(stderr, "Built: %s\n", __DATE__); RARCH_LOG_OUTPUT("Version: %s\n", PACKAGE_VERSION); #ifdef HAVE_GIT_VERSION RARCH_LOG_OUTPUT("Git: %s\n", rarch_git_version); #endif RARCH_LOG_OUTPUT("=================================================\n"); } validate_cpu_features(); config_load(); init_libretro_sym(global->libretro_dummy); init_system_info(); init_drivers_pre(); if (!event_command(EVENT_CMD_CORE_INIT)) goto error; event_command(EVENT_CMD_DRIVERS_INIT); event_command(EVENT_CMD_COMMAND_INIT); event_command(EVENT_CMD_REWIND_INIT); event_command(EVENT_CMD_CONTROLLERS_INIT); event_command(EVENT_CMD_RECORD_INIT); event_command(EVENT_CMD_CHEATS_INIT); event_command(EVENT_CMD_REMAPPING_INIT); event_command(EVENT_CMD_SAVEFILES_INIT); #if defined(GEKKO) && defined(HW_RVL) { settings_t *settings = config_get_ptr(); if (settings) { event_command(EVENT_CMD_VIDEO_SET_ASPECT_RATIO); video_driver_set_aspect_ratio(settings->video.aspect_ratio_idx); } } #endif global->error_in_init = false; global->main_is_init = true; return 0; error: event_command(EVENT_CMD_CORE_DEINIT); global->main_is_init = false; return 1; }
void ppp_input_task(intptr_t exinf) { T_NET_BUF *input; T_PPP_PROTENT *proto; ID tskid; int_t ix; /* ポートを初期設定する */ syscall(serial_opn_por(HDLC_PORTID)); syscall(serial_ctl_por(HDLC_PORTID, IOCTL_FCSND | IOCTL_FCRCV)); get_tid(&tskid); #ifdef PPP_CFG_MODEM init_modem(); syslog(LOG_NOTICE, "[PPP INPUT:%d] started with modem on port %d.", tskid, HDLC_PORTID); #else /* of #ifdef PPP_CFG_MODEM */ syslog(LOG_NOTICE, "[PPP INPUT:%d] started on port %d.", tskid, HDLC_PORTID); #endif /* of #ifdef PPP_CFG_MODEM */ /* ネットワークタイマタスクを起動する */ syscall(act_tsk(NET_TIMER_TASK)); /* 上位プロトコルを初期化する */ for (ix = 0; (proto = protocols[ix]) != NULL; ix ++) if (proto->init != NULL) (*proto->init)(); lcp_lowerup(); lcp_open(PPP_OPEN_PASSIVE); /* PPP 出力タスクを起動する */ syscall(act_tsk(PPP_OUTPUT_TASK)); while (true) { if (tget_net_buf(&input, IF_PDU_SIZE, TMO_PPP_GET_NET_BUF) == E_OK) { while (HDLC_read(input, IF_PDU_SIZE) != E_OK) ; if (input->len > 0) { #ifdef PPP_IDLE_TIMEOUT wai_sem(SEM_IDLE_TIMEOUT); if (idle && ntohs(*GET_PPP_HDR(input)) != PPP_LCP) { untimeout((FP)idle_timeout, NULL); idle = false; } sig_sem(SEM_IDLE_TIMEOUT); #endif /* of #ifdef PPP_IDLE_TIMEOUT */ parse_input(input); } else syscall(rel_net_buf(input)); #ifdef PPP_IDLE_TIMEOUT wai_sem(SEM_IDLE_TIMEOUT); if (!idle && ppp_phase == PPP_PHASE_NETWORK) { timeout((FP)idle_timeout, NULL, PPP_IDLE_TIMEOUT); idle = true; } else if (idle && ppp_phase != PPP_PHASE_NETWORK) { untimeout((FP)idle_timeout, NULL); idle = false; } sig_sem(SEM_IDLE_TIMEOUT); #endif /* of #ifdef PPP_IDLE_TIMEOUT */ } else { HDLC_dummy_read(); NET_COUNT_PPP(net_count_ppp.in_err_packets, 1); NET_COUNT_PPP(net_count_ppp_no_bufs, 1); } } }
/*! @brief Switch case for tone parsing and executing @authors Stepan Stepasyuk. */ int processTone(int tone){ if(in_hash_mode){ if(tone != 12){ if(newToneIndex <= 3){ unsigned char toneByte = tone | 0b10100000; receivedCode[newToneIndex++] = toneByte; } }else{ in_hash_mode = !in_hash_mode; Serial.print("in hash tone is: "); Serial.println(in_hash_mode); //checkpin here } }else if(receivedCode[0] != '\0' || tone == 12){ switch(tone){ unsigned char command; case 1: Serial.println("processTone says 1"); command = 0b00100100; parse_input(&command); break; case 2: Serial.println("processTone says 2"); command = 0b00100000; parse_input(&command); break; case 3: Serial.println("processTone says 2"); command = 0b00100011; parse_input(&command); break; case 4: Serial.println("processTone says 4"); command = 0b00100001; parse_input(&command); break; case 5: Serial.println("processTone says 2"); command = 0b10010001; parse_input(&command); break; case 6: Serial.println("processTone says 6"); command = 0b00100010; parse_input(&command); break; case 7: Serial.println("processTone says 2"); command = 0b00011000; parse_input(&command); break; case 8: Serial.println("processTone says 8"); command = 0b00001000; parse_input(&command); break; case 9: Serial.println("processTone says 2"); command = 0b10000000; parse_input(&command); break; case 10: Serial.println("processTone says 2"); command = 0b00001001; parse_input(&command); break; case 11: Serial.println("processTone says 2"); command = 0b00011001; parse_input(&command); break; case 12: Serial.println("processTone says #"); if(receivedCode[0] == '\0'){ in_hash_mode = !in_hash_mode; Serial.print("in hash tone is: "); Serial.println(in_hash_mode); }else{ command = 0b00000111; parse_input(&command); } break; default: Serial.print("processTone says unknown tone: "); Serial.println(tone); } } return 0; }
void *manage_input(void *job) { struct thread_struct *p = (struct thread_struct *)job; struct conn_node *node = p->node; struct data *data_to_send; void *rcvd_data; int size; unsigned long int time; data_to_send = parse_input(); if (data_to_send == NULL) { printf("Exiting\n"); exit(EXIT_SUCCESS); } /* if (data_to_send->data_type != LIST) pthread_barrier_wait(p->bar); */ if(data_to_send->data_type == PUT) printf("Sending %s\n", data_to_send->str); size = data_to_send->size + sizeof(struct data); if (send_to(node, data_to_send, size) != 0) { printf("\nError trying to send the request: "); if (data_to_send->data_type == LIST) { printf("list\n"); pthread_barrier_wait(p->bar); } else if (data_to_send->data_type == GET) printf("get %s", data_to_send->str); else if(data_to_send->data_type == PUT) printf("put %s\n", data_to_send->str); printf("Try again.\n"); free(p); free(data_to_send); close_conn_client(node); pthread_exit(NULL); } if(data_to_send->data_type == GET) printf("Trying to download: %s\n", data_to_send->str); time = get_utime(); if (recv_from(node, &rcvd_data) != 0) { printf("\nError trying to receive the response for: "); if (data_to_send->data_type == LIST) { printf("list\n"); pthread_barrier_wait(p->bar); } else if (data_to_send->data_type == GET) printf("get %s", data_to_send->str); else if(data_to_send->data_type == PUT) printf("put %s\n", data_to_send->str); printf("Try again.\n"); free(p); free(data_to_send); close_conn_client(node); pthread_exit(NULL); } time = get_utime() - time; printf("THE TIME: %lu\n", time); unsigned long int th = (((struct data *)rcvd_data)->size + sizeof(struct data)); float THH = (float)th/(float)time; printf("TRUGPUT %f\n", THH); fprintf(p->file, "%lu %f\n",time, THH); manage_mess_rcvd(rcvd_data); /* if (data_to_send->data_type == LIST) */ pthread_barrier_wait(p->bar); printf("FREEING\n"); free(p); free(data_to_send); free(rcvd_data); close_conn_client(node); pthread_exit(NULL); }
void grab_command(char *arg) { char arg1[BUFFER_SIZE], arg2[BUFFER_SIZE], arg3[BUFFER_SIZE], buffer[BUFFER_SIZE], result[BUFFER_SIZE], *cptr; FILE *myfile; int needLine = 0; BOOL wn = FALSE; arg=get_arg_in_braces(arg, arg1, STOP_SPACES); arg=get_arg_in_braces(arg, arg2, WITH_SPACES); arg=get_arg_in_braces(arg, arg3, WITH_SPACES); if(*arg1 && isdigit(*arg1)) { wn = TRUE; needLine = atoi(arg1); } else if(!strcmpi(arg1,lastGrab)) needLine = lastLine+1; else { needLine = 1; maxLines = count_lines(arg1); } if (((!wn)&&(!arg1||!*arg1))||((wn)&&(!arg2||!*arg2))) { tintin_puts2(rs::rs(1173)); return; } if (((!wn)&&(!arg2||!*arg2))||((wn)&&(!arg3||!*arg3))) { strcpy(wn?arg3:arg2,"%0\0"); } BOOL hasD = FALSE; cptr=wn?arg3:arg2; for(;*cptr&&*cptr!='\0';cptr++) if(*cptr=='%'&&*(cptr+1)=='0') hasD = TRUE; if(!hasD) strcpy(cptr," %0\0"); if((myfile=fopen(wn?arg2:arg1, "r"))==NULL) { char buff[MAX_PATH]; sprintf(buff, rs::rs(1174), wn?arg2:arg1); tintin_puts2(buff); return; } int currLine = 0; while(fgets(buffer, sizeof(buffer), myfile)) { currLine++; if(currLine == needLine) { for(cptr=buffer;*cptr&&*cptr!='\n';cptr++); *cptr='\0'; sprintf(vars[0], "%s", buffer); substitute_vars(wn?arg3:arg2,result); parse_input(result); break; } } lastLine = (needLine != maxLines)?needLine:0; strcpy(lastGrab,wn?arg2:arg1); fclose(myfile); }
//* en void spit_command(char *arg) { char filename[BUFFER_SIZE], spformat[BUFFER_SIZE], soptions[BUFFER_SIZE], buffer[BUFFER_SIZE], *cptr1/*,*cptr2,*cptr3*/; FILE *myfile; BOOL bPassSpace = FALSE; BOOL bSilent = FALSE; arg=get_arg_in_braces(arg, filename, STOP_SPACES); arg=get_arg_in_braces(arg, spformat, WITH_SPACES); arg=get_arg_in_braces(arg, soptions, STOP_SPACES); if ( !filename || !*filename ) { tintin_puts2(rs::rs(1173)); return; } if ( !spformat || !*spformat ) { strcpy(spformat,"%0"); } BOOL hasD = FALSE; for(cptr1=spformat;*cptr1&&*cptr1!='\0';cptr1++) if(*cptr1=='%'&&*(cptr1+1)=='0') hasD = TRUE; if(!hasD) strcpy(cptr1," %0\0"); for(cptr1=soptions;*cptr1&&*cptr1!='\0';cptr1++) { if(*cptr1=='n') bPassSpace = TRUE; if(*cptr1=='s') bSilent = TRUE; } if((myfile=fopen(filename, "r"))==NULL) { char buff[MAX_PATH]; sprintf(buff, rs::rs(1174), filename); tintin_puts2(buff); return; } while(fgets(buffer, sizeof(buffer), myfile)) { char cbuffer[BUFFER_SIZE]; if((*buffer=='\n'||strlen(buffer)<2)&&bPassSpace) continue; /* for(cptr1=spformat,cptr3=cbuffer; *cptr1 && *cptr1!='\0'; cptr1++,cptr3++) if(*cptr1=='@') { for(cptr2=buffer;*cptr2&&*cptr2!='\0'&&*cptr2!='\n';cptr2++,cptr3++) *cptr3=*cptr2; cptr3--; } else *cptr3=*cptr1; *cptr3='\0'; */ for(cptr1=buffer;*cptr1&&*cptr1!='\n';cptr1++); *cptr1='\0'; sprintf(vars[0], "%s", buffer); substitute_vars(spformat,cbuffer); parse_input(cbuffer); } fclose(myfile); if(!bSilent) tintin_puts2(rs::rs(1175)); }
void *manage_input(void *job) { struct thread_struct *p = (struct thread_struct *)job; struct conn_node *node = p->node; struct data *data_to_send; void *rcvd_data; int size; data_to_send = parse_input(); if (data_to_send == NULL) exit(EXIT_SUCCESS); if (data_to_send->data_type != LIST) pthread_barrier_wait(p->bar); if(data_to_send->data_type == PUT) printf("Sending %s\n", data_to_send->str); size = data_to_send->size + sizeof(struct data); if (send_to(node, data_to_send, size) != 0){ printf("\nError trying to send the request: "); if (data_to_send->data_type == LIST){ printf("list\n"); pthread_barrier_wait(p->bar); } else if (data_to_send->data_type == GET) printf("get %s", data_to_send->str); else if(data_to_send->data_type == PUT) printf("put %s\n", data_to_send->str); printf("Try again.\n"); free(p); free(data_to_send); close_conn_client(node); pthread_exit(NULL); } if(data_to_send->data_type == GET) printf("Trying to download: %s\n", data_to_send->str); if (recv_from(node, &rcvd_data) != 0){ printf("\nError trying to receive the response for: "); if (data_to_send->data_type == LIST){ printf("list\n"); pthread_barrier_wait(p->bar); } else if (data_to_send->data_type == GET) printf("get %s", data_to_send->str); else if(data_to_send->data_type == PUT) printf("put %s\n", data_to_send->str); printf("Try again.\n"); free(p); free(data_to_send); close_conn_client(node); pthread_exit(NULL); } manage_mess_rcvd(rcvd_data); if (data_to_send->data_type == LIST) pthread_barrier_wait(p->bar); free(p); free(data_to_send); free(rcvd_data); close_conn_client(node); pthread_exit(NULL); }
int main (int argc, char **argv) { int i = 0, error = 0, p = 0; size_t nlines = 0; FILE *fout = NULL, *ferr = NULL, *f_imf = NULL, *f_fmf = NULL; double *y = NULL; t_sample *sample = NULL; MF_t *mfs = NULL; anfis_t net = NULL; /* Obtenemos los datos */ parse_input (argc, argv, &y, &nlines, &fout, &ferr, &f_imf, &f_fmf); printf ("\n\nT = %zu\tN = %zu\n", _T, _N); /* Creamos la red */ mfs = gen_mfs (_N, _T, _LB, _UB); net = anfis_create (_N, _T, mfs); printf ("Red ANFIS antes del aprendizaje:\n\n"); anfis_print (net); /* Imprimimos las funciones membresía iniciales (antes del aprendizaje) */ mf_print (net, f_imf); /** Generamos un conjunto de entrenamiento con la mitad de los datos ** y entrenamos la red con él */ sample = sample_alloc (_N, nlines); p = nlines / (2*NITER); for (i=0 ; i < NITER ; i++) { sample_gen (sample, _N, p, JUMP, &(y[i*p])); error = anfis_train (net, sample, p); assert (error == ANFIS_OK); } printf ("\n\nRed ANFIS después del aprendizaje:\n"); anfis_print (net); /** Alimentamos la red con todos los datos a disposición ** para analizar qué tan bueno fue su aprendizaje */ p = nlines - (_N+1) * JUMP; sample_gen (sample, _N, p, JUMP, y); exercise_network (net, sample, p, 118, fout, ferr); /* Imprimimos las funciones membresía resultantes del aprendizaje */ mf_print (net, f_fmf); /* Limpiando memoria */ net = anfis_destroy (net); free (mfs); mfs = NULL; sample = sample_free (sample, p); free (y); y = NULL; fclose (fout); fout = NULL; if (ferr != NULL && fileno (ferr) >= 0) { fclose (ferr); ferr = NULL; } if (f_imf != NULL && fileno (f_imf) >= 0) { fclose (f_imf); f_imf = NULL; } if (f_fmf != NULL && fileno (f_fmf) >= 0) { fclose (f_fmf); f_fmf = NULL; } return EXIT_SUCCESS; }
int main(int argc, char **argv){ int task, len, chunks = CHUNK; MPI_Status status; char hostname[MPI_MAX_PROCESSOR_NAME]; #ifdef GETTIME double start = MPI_Wtime(); #endif const int nitems=3; int blocklengths[3] = {2,2,1}; MPI_Datatype types[3] = {MPI_CHAR, MPI_UNSIGNED_SHORT, MPI_UNSIGNED}; MPI_Aint offsets[3]; offsets[0] = offsetof(world_cell, type); offsets[1] = offsetof(world_cell, breeding_period); offsets[2] = offsetof(world_cell, number); /* MPI Initialization */ if (MPI_Init(&argc, &argv) != MPI_SUCCESS) { printf ("Error starting MPI program. Terminating.\n"); /*MPI_Abort(MPI_COMM_WORLD, ret);*/ return -1; } MPI_Get_processor_name(hostname, &len); MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_world_cell_type); MPI_Type_commit(&mpi_world_cell_type); MPI_Comm_size(MPI_COMM_WORLD, &numtasks); MPI_Comm_rank(MPI_COMM_WORLD, &taskid); if(taskid == MASTER){ MPI_Request size_reqs[numtasks-1]; info[1] = wolf_breeding_period = atoi(argv[2]); info[2] = squirrel_breeding_period = atoi(argv[3]); info[3] = wolf_starvation_period = atoi(argv[4]); info[4] = number_of_generations = atoi(argv[5]); parse_input(argv[1]); info[0] = grid_size; bottom = 0; top = chunk_size = CHUNK; payload = top + 2; for(task = 1; task < numtasks; task++) MPI_Isend(info, 5, MPI_INT, task, INIT_TAG, MPI_COMM_WORLD, &size_reqs[task-1]); MPI_Waitall(numtasks - 1, size_reqs, MPI_STATUS_IGNORE); for(task = 1; task < numtasks; task++){ int bottom_task = FLIMIT_INF_CHUNK(task), top_task = FLIMIT_SUP_CHUNK(task), chunk_size = top_task-bottom_task; bottom_task -= 2; if (task == numtasks-1) top_task += CHUNK_REMAINDER; else top_task += 2; for( ; bottom_task < top_task; bottom_task++) MPI_Send(world[bottom_task], grid_size, mpi_world_cell_type, task, FILL_TAG, MPI_COMM_WORLD); } } else { int j = 0; MPI_Recv(info, 5, MPI_INT, MASTER, INIT_TAG, MPI_COMM_WORLD, &status); grid_size = info[0]; wolf_breeding_period = info[1]; squirrel_breeding_period = info[2]; wolf_starvation_period = info[3]; number_of_generations = info[4]; bottom = 2; if(taskid == numtasks-1){ chunk_size = CHUNK + CHUNK_REMAINDER; payload = top = chunk_size+bottom; } else { chunk_size = CHUNK; top = chunk_size+bottom; payload = top + 2; } initialize_world_array(payload ); for( ; j < payload; j++) MPI_Recv(world[j], grid_size, mpi_world_cell_type, MASTER, FILL_TAG, MPI_COMM_WORLD, &status); } start_world_simulation(); gather(); #ifdef GETTIME if(taskid == MASTER){ printf("MPI time: %lf\n", MPI_Wtime() - start); print_world(grid_size); } #endif //freemem(); MPI_Finalize(); return 0; }
void parse_input(char *input) { char command[BUFFER_SIZE], arg[BUFFER_SIZE], result[BUFFER_SIZE]; char *input2; bPasswordEcho = TRUE; if(*input=='\0') { write_line_mud(""); return ; } if ( verbatim && *input == cCommandChar && *(input+1) == 'v' ) {// check verbatim command char command[BUFFER_SIZE]; char* input2=get_arg_stop_spaces(input+1, command); if(command[0] == 'v' && is_abrev(command, "verbatim")){ char arg[BUFFER_SIZE]; get_arg_all(input2, arg); verbatim_command(arg); return; } } if (verbatim ) { write_line_mud(input); return ; } if (*input==verbatim_char) { input++; write_line_mud(input); return ; } substitute_myvars(input, result); input2=result; while(*input2) { //* en:colon // if(*input2==';') if(*input2==cCommandDelimiter||(bColon && *input2==';')&&*(input2-1)!='\\') input2++; //*/en input2=get_arg_stop_spaces(input2, command); input2=get_arg_all(input2, arg); //* en:prefix if(s_prefix[0] && command[0] != cCommandChar) { char p_command[BUFFER_SIZE]; strcpy(p_command,command); strcat(p_command," "); strcat(p_command,arg); strcpy(command,s_prefix); strcpy(arg,p_command); } //*/en if(*command==cCommandChar) { if (bDisplayCommands) { // output command in square brackets char strInputCommand[BUFFER_SIZE], strOutputBuffer[BUFFER_SIZE]; strcpy(strInputCommand, "\n["); strcat(strInputCommand, command); if (*arg != '\0') { strcat(strInputCommand, " "); strcat(strInputCommand, arg); } strcat(strInputCommand, "]"); add_codes(strInputCommand, strOutputBuffer, "brown", TRUE); tintin_puts2(strOutputBuffer); if (hLogFile.is_open()) { log(strInputCommand); } } parse_tintin_command(command+1, arg); } //* en:comments else if(*command==cCommentChar); //*/en else { //* en:waits if(iWaitState>0) { char *ptr1,*ptr2; for(ptr1=mQueue;*ptr1&&*ptr1!='\0';ptr1++); *ptr1++=cCommandDelimiter; for(ptr2=command;*ptr2&&*ptr2!='\0';ptr2++,ptr1++) *ptr1=*ptr2; if(*arg) *ptr1++=' '; for(ptr2=arg;*ptr2&&*ptr2!='\0';ptr2++,ptr1++) *ptr1=*ptr2; *ptr1++='\0'; continue; } //* en ALIAS_INDEX ind; if( (ind=AliasList.find(command)) != AliasList.end() && ind->second->m_pGroup->m_bEnabled ) { int i; char *cpsource, *cpsource2, newcommand[BUFFER_SIZE], end; strcpy(vars[0], arg); for(i=1, cpsource=arg; i<10; i++) { /* Next lines CHANGED to allow argument grouping with aliases */ while (*cpsource == ' ') cpsource++; end = (*cpsource == '{') ? '}' : ' '; cpsource = (*cpsource == '{') ? cpsource+1 : cpsource; for(cpsource2=cpsource; *cpsource2 && *cpsource2!=end; cpsource2++); strncpy(vars[i], cpsource, cpsource2-cpsource); *(vars[i]+(cpsource2-cpsource))='\0'; cpsource=(*cpsource2) ? cpsource2+1 : cpsource2; } ALIAS* pal = ind->second; prepare_actionalias((char*)pal->m_strRight.data(), newcommand); if(!strcmp(pal->m_strRight.data(), newcommand) && *arg) { strcat(newcommand, " "); strcat(newcommand, arg); } parse_input(newcommand); } else if(speedwalk && !*arg && is_speedwalk_dirs(command)) do_speedwalk(command); else { get_arg_with_spaces(arg,arg); write_com_arg_mud(command, arg); } } } return; }
int parse_input(const char *file_in, int set_used) { FILE *f; char *s; int c, length = 0; parse_result pc; if(strcmp(file_in, "-") == 0) f = stdin; else f = fopen(file_in, "r"); if(!f) return -1; /* error opening file */ /* we now read in the file and parse */ /* note: 40 is just a starter length, it is not a maximum */ length = 40; s = (char *)malloc(length + 1); do{ c = parse_get_line(f, &s, &length); if(*s){ if(strncmp("include ", s, 8) == 0 ){ /* include another file */ /* wipe out leading 'include' with blanks */ strncpy(s, " ", 7); str_trim(s); if(!disable_write) fprintf(fout, "# including file '%s'\n", s); c = parse_input(s, 0); if(c != 0) { fprintf(stderr, "Parser error: cannot open included file '%s'.\n", s); exit(1); } } else if(*s == '%'){ /* we have a block */ *s = ' '; str_trim(s); if(getsym(s) != NULL){ /* error */ fprintf(stderr, "Parser warning: %s \"%s\" %s.\n", "Block", s, "already defined"); do{ /* skip block */ c = parse_get_line(f, &s, &length); }while(c != EOF && *s != '%'); }else{ /* parse block */ symrec *rec; rec = putsym(s, S_BLOCK); rec->value.block = (sym_block *)malloc(sizeof(sym_block)); rec->value.block->n = 0; rec->value.block->lines = NULL; do{ c = parse_get_line(f, &s, &length); if(*s && *s != '%'){ char *s1, *tok; int l, col; l = rec->value.block->n; rec->value.block->n++; rec->value.block->lines = (sym_block_line *) realloc((void *)rec->value.block->lines, sizeof(sym_block_line)*(l+1)); rec->value.block->lines[l].n = 0; rec->value.block->lines[l].fields = NULL; /* parse columns */ for(s1 = s; (tok = strtok(s1, "|\t")) != NULL; s1 = NULL){ char *tok2 = strdup(tok); str_trim(tok2); col = rec->value.block->lines[l].n; rec->value.block->lines[l].n++; rec->value.block->lines[l].fields = (char **) realloc((void *)rec->value.block->lines[l].fields, sizeof(char *)*(col+1)); rec->value.block->lines[l].fields[col] = tok2; } } }while(c != EOF && *s != '%'); } }else{ /* we can parse it np */ parse_exp(s, &pc); } } }while(c != EOF); free(s); if(f != stdin) fclose(f); if(set_used == 1) sym_mark_table_used(); return 0; }
int main (int argc, char *argv[]) { int i; /* * Parse command line arguments conforming with getopt_long syntax * Note: we have to support "xboard" and "post" as bare strings * for backward compatibility. */ int c; int opt_help = 0, opt_version = 0, opt_post = 0, opt_xboard = 0, opt_hash = 0, opt_memory = 0, opt_easy = 0, opt_manual = 0; char *endptr; progname = argv[0]; /* Save in global for cmd_usage */ while (1) { static struct option long_options[] = { {"hashsize", 1, 0, 's'}, {"memory", 1, 0, 'M'}, {"version", 0, 0, 'v'}, {"help", 0, 0, 'h'}, {"xboard", 0, 0, 'x'}, {"post", 0, 0, 'p'}, {"easy", 0, 0, 'e'}, {"manual", 0, 0, 'm'}, {0, 0, 0, 0} }; /* getopt_long stores the option index here. */ int option_index = 0; c = getopt_long (argc, argv, "ehmpvxs:M:", long_options, &option_index); /* Detect the end of the options. */ if (c == -1) break; /* * Options with a straight flag, could use getoopt_long * flag setting but this is more "obvious" and easier to * modify. */ switch (c) { case 'v': opt_version = 1; break; case 'h': opt_help = 1; break; case 'x': opt_xboard = 1; break; case 'p': opt_post = 1; break; case 'e': opt_easy = 1; break; case 'm': opt_manual = 1; break; case 's': if ( optarg == NULL ){ /* we have error such as two -s */ opt_help = 1; break; } errno = 0; /* zero error indicator */ opt_hash = strtol (optarg, &endptr, 10); if ( errno != 0 || *endptr != '\0' ){ printf("Hashsize out of Range or Invalid\n"); return(1); } break; case 'M': if ( optarg == NULL ){ /* we have error such as two -s */ opt_help = 1; break; } errno = 0; /* zero error indicator */ opt_memory = strtol (optarg, &endptr, 10); if ( errno != 0 || *endptr != '\0' ){ printf("Memory size invalid\n"); return(1); } break; case '?': /* On error give help - getopt does a basic message. */ opt_help = 1; break; default: puts ("Option Processing Failed\n"); abort(); } } /* end of getopt_long style parsing */ /* Initialize random number generator */ srand((unsigned int) time(NULL)); /* initialize control flags */ flags = ULL(0); /* output for thinking */ ofp = stdout; /* Handle old style command line options */ if (argc > 1) { for (i = 0; i < argc; i++) { if (strcmp(argv[i],"xboard") == 0) { SET (flags, XBOARD); } else if (strcmp(argv[i],"post") == 0) { SET (flags, POST); } } } if (opt_xboard == 1) SET (flags, XBOARD); if (opt_post == 1) SET (flags, POST); if (opt_manual ==1) SET (flags, MANUAL); cmd_version(); /* If the version option was specified we can exit here */ if (opt_version == 1) return(0); /* If a usage statement is required output it here */ if (opt_help == 1){ cmd_usage(); return (1); /* Maybe an error if due to bad arguments. */ } if (opt_memory != 0 && opt_hash != 0 ){ cmd_usage(); return (1); /* only one or the other */ } HashSize = 0 ; /* Set HashSize zero */ if ( opt_hash != 0) CalcHashSize(opt_hash); if ( opt_memory > 0 ){ int tablesize=(1048576*opt_memory)/(2*sizeof(HashSlot)); CalcHashSize(tablesize); } Initialize (); if ( opt_easy == 0) SET (flags, HARD); if (argc > 1) { for (i = 0; i < argc; i++) { if (strcmp(argv[i],"xboard") == 0) { SET (flags, XBOARD); } else if (strcmp(argv[i],"post") == 0) { SET (flags, POST); } } } bookmode = BOOKPREFER; bookfirstlast = 3; while (!(flags & QUIT)) { wait_for_input(); parse_input(); if ((flags & THINK) && !(flags & MANUAL) && !(flags & ENDED)) { if (!(flags & XBOARD)) printf("Thinking...\n"); Iterate (); CLEAR (flags, THINK); } RealGameCnt = GameCnt; RealSide = board.side; input_wakeup(); /* Ponder only after first move */ /* Ponder or (if pondering disabled) just wait for input */ if ((flags & HARD) && !(flags & QUIT) ) { ponder(); } } CleanupInput(); /* Some cleaning up */ free (HashTab[0]); free (HashTab[1]); return (0); }
void match_command(wchar_t *arg) { wchar_t pattern[BUFFER_SIZE], strng[BUFFER_SIZE], if_then[BUFFER_SIZE], if_else[BUFFER_SIZE], temp[BUFFER_SIZE]; CPCRE re; arg = get_arg_in_braces(arg,temp,STOP_SPACES,sizeof(temp)/sizeof(wchar_t)-1); prepare_actionalias(temp, pattern, sizeof(pattern)/sizeof(wchar_t)-1); BOOL i_flag = FALSE, m_flag = FALSE, g_flag = FALSE; std::wstring regexp = pattern; if ( *pattern == L'/' ) { regexp = (wchar_t*)pattern + 1; int size = regexp.size(); for (int i = size - 1; i >= 0; i--) { if (regexp[i] == L'i') { size--; i_flag = TRUE; } else if (regexp[i] == L'm') { size--; m_flag = TRUE; } else if (regexp[i] == L'g') { size--; g_flag = TRUE; } else if (regexp[i] == L'/') { size--; break; } else { size = regexp.size(); i_flag = m_flag = g_flag = FALSE; break; } } regexp.resize(size); } if (!re.SetSource(regexp, m_flag, i_flag)) { return; } arg = get_arg_in_braces(arg,temp,STOP_SPACES,sizeof(temp)/sizeof(wchar_t)-1); prepare_actionalias(temp, strng, sizeof(strng)/sizeof(wchar_t)-1); arg = get_arg_in_braces(arg,if_then,WITH_SPACES,sizeof(if_then)/sizeof(wchar_t)-1); arg = get_arg_in_braces(arg,if_else,WITH_SPACES,sizeof(if_else)/sizeof(wchar_t)-1); int offset = 0; int offsets[33]; bool no_match = true; wchar_t *test = (wchar_t*)strng; int test_len = wcslen(test); for (;;) { int captured = pcre16_exec(re.m_pPcre, re.m_pExtra, test, test_len, offset, 0, offsets, 33); if (captured <= 0) break; no_match = false; int i; for (i = 0; i < 10; i++) vars[i][0] = 0; for (i = 1; i < captured; i++) { if (offsets[i*2] >= 0) { int size = offsets[i*2 + 1] - offsets[i*2]; wcsncpy(vars[i-1], test + offsets[i*2], size); *(vars[i-1]+size) = L'\0'; } } prepare_actionalias(if_then, temp, sizeof(temp)/sizeof(wchar_t)-1); parse_input(temp, g_flag); offset = offsets[1]; if (!g_flag) break; } if (no_match) parse_input(if_else); }
int main(int argc, char *argv[]) { const char *basebase = ".manynodes"; const char *graphexporttimeout = NULL; char buf[1024]; if(argc > 1) n = atoi(argv[1]); if(n < 1) { fprintf(stderr, "Usage: %s [number of local nodes] [confbase] [prefixnodenames] [graphexport timeout]\n", argv[0]); return 1; } if(argc > 2) basebase = argv[2]; if(argc > 3) namesprefix = argv[3]; if(argc > 4) graphexporttimeout = argv[4]; mesh = calloc(n, sizeof *mesh); meshlink_set_log_cb(NULL, MESHLINK_DEBUG, log_message); #ifndef _WIN32 mkdir(basebase, 0750); #else mkdir(basebase); #endif char filename[PATH_MAX]; char nodename[100]; for(int i = 0; i < n; i++) { snprintf(nodename, sizeof nodename, "%snode%d", namesprefix,i); snprintf(filename, sizeof filename, "%s/%s", basebase, nodename); bool itsnew = access(filename, R_OK); if (n/(i+1) > n/4) { mesh[i] = meshlink_open(filename, nodename, "manynodes", DEV_CLASS_BACKBONE); } else { mesh[i] = meshlink_open(filename, nodename, "manynodes", DEV_CLASS_PORTABLE); } meshlink_set_log_cb(mesh[i], MESHLINK_DEBUG, log_message); if(!mesh[i]) { fprintf(stderr, "errno is: %d\n", meshlink_errno); fprintf(stderr, "Could not open %s: %s\n", filename, meshlink_strerror(meshlink_errno)); return 1; } } int started = 0; for(int i = 0; i < n; i++) { if(!meshlink_start(mesh[i])) fprintf(stderr, "Could not start node %d: %s\n", i, meshlink_strerror(meshlink_errno)); else started++; } if(!started) { fprintf(stderr, "Could not start any node!\n"); return 1; } if(graphexporttimeout) { exportmeshgraph_begin(graphexporttimeout); } printf("%d nodes started.\nType /help for a list of commands.\n", started); // handle input while(fgets(buf, sizeof buf, stdin)) parse_input(buf); exportmeshgraph_end(NULL); printf("Nodes stopping.\n"); for(int i = 0; i < n; i++) meshlink_close(mesh[i]); return 0; }
int main() { // load datafiles parse_input("adal_inntak.in","velar_og_bidradir.in"); // initialize arrays and variables if((fail_list = malloc(sizeof(breakdown)*NUM_MACHINES+1))==NULL) { printf("Allocation Error\n"); exit(1); } for (failure_nr = min_no_failures; failure_nr<= max_no_failures; failure_nr++) { stream = (unsigned int)time(NULL) % 100; memset( is_machine_busy,0, NUM_MACHINES +1 ); memset( machine_broken,0, NUM_MACHINES +1); memset( queue_max_lengths,0, NUM_MACHINES +1); memset( fail_list,0, sizeof(breakdown)*(NUM_MACHINES+1)); fail_index = 0; skaut_throughput = 0; sampst_delays = number_of_machines +1; throughput_time = number_of_machines +2; skaut_id = 1; skaut_throughput = 0; // Initialize rndlib init_twister(); // Initialize simlib init_simlib(); maxatr = 6; // how many attributes do we need? /* Schedule first wagen arrival */ event_schedule( 10.0, EVENT_WAGEN_UNLOAD_ARRIVAL ); /* Schedule end of warmup time */ event_schedule( end_warmup_time, EVENT_END_WARMUP ); event_schedule(end_warmup_time, EVENT_GENERATE_FAILURES ); /* Schedule simulation termination */ event_schedule(end_simulation_time , EVENT_END_SIMULATION ); next_event_type = 0; while (next_event_type != EVENT_END_SIMULATION) { timing(); switch (next_event_type) { case EVENT_WAGEN_UNLOAD_ARRIVAL: wagen_unload_arrival(); break; case EVENT_SKAUT_ARRIVAL: skaut_arrival(); break; case EVENT_SKAUT_DEPARTURE: skaut_departure(); break; case EVENT_MACHINE_FAILURE: machine_failure(); break; case EVENT_MACHINE_FIXED: machine_fixed(); break; case EVENT_END_WARMUP: end_warmup(); break; case EVENT_END_SIMULATION: report(); break; case EVENT_GENERATE_FAILURES: create_machine_fail_events(); break; } } } }
int main(int argc, char * argv[]) { setvbuf(stdout, NULL, _IONBF, 0); //will not compile till you provide a declaration for stack Stack* stack = stack_init(); if (stack == NULL) { fprintf(stderr, STR_ERR_MEM); return EXIT_FAILURE; } stackpointer = stack; //to pass into parse_input FuncInfo funcInfo; printf(STR_WELCOME); printf(STR_PROMPT); //to store strings from stdin char readin[BUFSIZ]; while (fgets(readin, BUFSIZ, stdin) != NULL) { if (feof(stdin)) { break; } //parse input int r = parse_input(&funcInfo, readin); //input could not be parsed, continue to next iteation if (r == -1) { printf("\n"); printf(STR_PROMPT); continue; } //call appropriate function switch (funcInfo.func) { case 1: push(funcInfo.word); break; case 2: pop(); break; case 3: peek(); break; case 4: print(); break; case 5: check(funcInfo.word); break; default: printf(STR_ERR_UNKNOWN); } printf("\n"); printf(STR_PROMPT); } //destruct stack stack_delete(); printf("quit\n"); return EXIT_SUCCESS; return 0; }
static void apply_options(void) { char temp[BUFFER_SIZE], sname[BUFFER_SIZE]; char ustr[BUFFER_SIZE]; const char *home; FILE *f; # define DO_INPUT(str,iv) local_to_utf8(ustr, str, BUFFER_SIZE, 0);\ activesession=parse_input(str, iv, activesession); for (struct listnode *opt=options->next; opt; opt=opt->next) { switch (*opt->left) { case '#': *opt->left=tintin_char; activesession=parse_input(opt->left, true, activesession); break; case 'c': DO_INPUT(opt->right, false); break; case 'r': set_magic_hook(activesession); make_name(sname, opt->right); snprintf(temp, BUFFER_SIZE, "%crun %.*s {%s}", tintin_char, MAX_SESNAME_LENGTH, sname, opt->right); DO_INPUT(temp, true); break; case 's': set_magic_hook(activesession); make_name(sname, opt->right); snprintf(temp, BUFFER_SIZE, "%cses %.*s {%s %s}", tintin_char, MAX_SESNAME_LENGTH, sname, opt->right, opt->pr); DO_INPUT(temp, true); break; case 'S': set_magic_hook(activesession); make_name(sname, opt->right); snprintf(temp, BUFFER_SIZE, "%csslses %.*s {%s %s}", tintin_char, MAX_SESNAME_LENGTH, sname, opt->right, opt->pr); DO_INPUT(temp, true); break; case ' ': local_to_utf8(ustr, opt->right, BUFFER_SIZE, 0); if ((f=fopen(opt->right, "r"))) { if (activesession->verbose || !real_quiet) tintin_printf(0, "#READING {%s}", ustr); activesession = do_read(f, ustr, activesession); } else tintin_eprintf(0, "#FILE NOT FOUND: {%s}", ustr); break; case '-': if (!strcmp(DEFAULT_FILE_DIR, "HOME")) if ((home = getenv("HOME"))) strcpy(temp, home); else *temp = '\0'; else strcpy(temp, DEFAULT_FILE_DIR); strcat(temp, "/.tintinrc"); local_to_utf8(ustr, temp, BUFFER_SIZE, 0); if ((f=fopen(temp, "r"))) activesession = do_read(f, ustr, activesession); else if ((home = getenv("HOME"))) { strcpy(temp, home); strcat(temp, "/.tintinrc"); local_to_utf8(ustr, temp, BUFFER_SIZE, 0); if ((f=fopen(temp, "r"))) activesession = do_read(f, ustr, activesession); } } } kill_list(options); }
int main(int argc, char *argv[]) { INT *connect; int debug = EX_FALSE; /* EX_TRUE, display debug information; EX_FALSE */ /* otherwise. */ static char device_name[MAX_STRING_LEN]; static char file_name[MAX_STRING_LEN] = DEFAULT_FILE_NAME; int exodus = EX_TRUE; INT map_origin = DEFAULT_MAP_ORIGIN; INT num_domains = DEFAULT_NUM_DOMAINS; INT num_elements_1d; INT num_elements = DEFAULT_NUM_ELEMENTS; INT num_nodal_fields = DEFAULT_NUM_FIELDS; INT num_global_fields = DEFAULT_NUM_FIELDS; INT num_element_fields = DEFAULT_NUM_FIELDS; INT num_timesteps = DEFAULT_NUM_TIMESTEPS; INT num_nodes; int compression_level = 0; int shuffle = 0; int int64bit = 0; size_t size; realtyp *x; realtyp *y; realtyp *z; ex_opts(EX_VERBOSE | EX_ABORT); /* Parse Input */ parse_input(argc, argv, &debug, &map_origin, &num_elements, &num_domains, &num_nodal_fields, &num_global_fields, &num_element_fields, &num_timesteps, device_name, file_name, &exodus, &compression_level, &shuffle, &int64bit); /* Create Coordinates and Connectivity Array */ num_elements_1d = icbrt(num_elements); num_nodes = (num_elements_1d + 1) * (num_elements_1d + 1) * (num_elements_1d + 1); x = malloc(num_nodes * sizeof(realtyp)); y = malloc(num_nodes * sizeof(realtyp)); z = malloc(num_nodes * sizeof(realtyp)); assert(x != NULL && y != NULL && z != NULL); num_elements = num_elements_1d * num_elements_1d * num_elements_1d; size = (size_t)NUM_NODES_PER_ELEM * num_elements * sizeof(INT); assert(size > 0); connect = malloc(size); assert(connect != NULL); fprintf(stderr, "Creating a 3D mesh of %" PRId64 " hex elements and %" PRId64 " nodes.\n", num_elements, num_nodes); make_mesh(x, y, z, connect, map_origin, num_elements_1d); fprintf(stderr, "\t...Mesh topology created.\n"); /* * Write Out Mesh */ if (exodus) { write_exo_mesh(debug, file_name, map_origin, num_nodes, num_elements, num_domains, num_nodal_fields, num_global_fields, num_element_fields, num_timesteps, x, y, z, connect, compression_level, shuffle, int64bit); } free(x); free(y); free(z); free(connect); return 0; } /* end of main() */
static void tintin(void) { int i, result, maxfd; struct timeval tv; fd_set readfdmask; #ifdef XTERM_TITLE struct session *lastsession=0; #endif char kbdbuf[BUFFER_SIZE]; WC ch; int inbuf=0; mbstate_t instate; memset(&instate, 0, sizeof(instate)); for (;;) { #ifdef XTERM_TITLE if (ui_own_output && activesession!=lastsession) { lastsession=activesession; if (activesession==nullsession) user_title(XTERM_TITLE, "(no session)"); else user_title(XTERM_TITLE, activesession->name); } #endif tv.tv_sec = check_events(); tv.tv_usec = 0; maxfd=0; FD_ZERO(&readfdmask); if (!eofinput) FD_SET(0, &readfdmask); else if (activesession==nullsession) end_command(0, activesession); for (struct session *ses = sessionlist; ses; ses = ses->next) { if (ses==nullsession) continue; if (ses->nagle) flush_socket(ses); FD_SET(ses->socket, &readfdmask); if (ses->socket>maxfd) maxfd=ses->socket; } result = select(maxfd+1, &readfdmask, 0, 0, &tv); if (need_resize) { char buf[BUFFER_SIZE]; user_resize(); sprintf(buf, "#NEW SCREEN SIZE: %dx%d.", COLS, LINES); tintin_puts1(buf, activesession); } if (result == 0) continue; else if (result < 0 && errno == EINTR) continue; /* Interrupted system call */ else if (result < 0) syserr("select"); if (FD_ISSET(0, &readfdmask)) { PROFSTART; PROFPUSH("user interface"); result=read(0, kbdbuf+inbuf, BUFFER_SIZE-inbuf); if (result==-1) myquitsig(0); if (result==0 && !isatty(0)) eofinput=true; inbuf+=result; i=0; while (i<inbuf) { result=mbrtowc(&ch, kbdbuf+i, inbuf-i, &instate); if (result==-2) /* incomplete but valid sequence */ { memmove(kbdbuf, kbdbuf+i, inbuf-i); inbuf-=i; goto partial; } else if (result==-1) /* invalid sequence */ { ch=0xFFFD; i++; errno=0; /* Shift by 1 byte. We can use a more intelligent shift, * but staying charset-agnostic makes the code simpler. */ } else if (result==0) /* literal 0 */ i++; /* oops... bad ISO/ANSI, bad */ else i+=result; if (user_process_kbd(activesession, ch)) { hist_num=-1; if (term_echoing || (got_more_kludge && done_input[0])) /* got_more_kludge: echo any non-empty line */ { if (activesession && *done_input) if (strcmp(done_input, prev_command)) do_history(done_input, activesession); if (activesession->echo) echo_input(done_input); if (activesession->logfile) write_logf(activesession, done_input, activesession->loginputprefix, activesession->loginputsuffix); } if (*done_input) strcpy(prev_command, done_input); aborting=false; activesession = parse_input(done_input, false, activesession); recursion=0; } } inbuf=0; partial: PROFEND(kbd_lag, kbd_cnt); PROFPOP; } for (struct session *ses = sessionlist; ses; ses = ses->next) { if (ses->socket && FD_ISSET(ses->socket, &readfdmask)) { aborting=false; any_closed=false; do { read_mud(ses); if (any_closed) { any_closed=false; goto after_read; /* The remaining sessions will be done after select() */ } #ifdef HAVE_ZLIB } while (ses->mccp_more); #else } while (0); #endif } } after_read: if (activesession->server_echo && (2-activesession->server_echo != gotpassword)) { gotpassword= 2-activesession->server_echo; if (!gotpassword) got_more_kludge=false; user_passwd(gotpassword && !got_more_kludge); term_echoing=!gotpassword; } }
/* * graph_read_dimacs_binary() * * Reads a dimacs-format binary file from file stream fp with the first * line being firstline. * * Returns the newly-allocated graph or NULL if an error occurred. * * TODO: This function leaks memory when reading erroneous files. */ static graph_t *graph_read_dimacs_binary(FILE *fp,char *firstline) { int length=0; graph_t *g; int i,j; char *buffer; char *start; char *end; char **buf; char tmp[10]; if (sscanf(firstline," %d %2s",&length,tmp)!=1) return NULL; if (length<=0) { fprintf(stderr,"Malformed preamble: preamble size < 0.\n"); return NULL; } buffer=malloc(length+2); if (fread(buffer,1,length,fp)<length) { fprintf(stderr,"Malformed preamble: unexpected " "end of file.\n"); free(buffer); return NULL; } g=calloc(1,sizeof(graph_t)); start=buffer; while (start < buffer+length) { end=strchr(start,'\n'); if (end==NULL) end=buffer+length; end[0]=0; if (!parse_input(start,g)) { fprintf(stderr,"Malformed preamble: %s\n",start); free (buffer); return NULL; } start=end+1; } free(buffer); if (g->n <= 0) { fprintf(stderr,"Malformed preamble: number of " "vertices <= 0\n"); free(g); return NULL; } /* Binary part. */ buf=calloc(g->n,sizeof(char*)); for (i=0; i < g->n; i++) { buf[i]=calloc(g->n,1); if (fread(buf[i],1,i/8+1,fp) < (i/8+1)) { fprintf(stderr,"Unexpected end of file when " "reading graph.\n"); return NULL; } } for (i=0; i < g->n; i++) { for (j=0; j<i; j++) { if (buf[i][j/8]&(1<<(7-(j%8)))) { GRAPH_ADD_EDGE(g,i,j); } } free(buf[i]); } free(buf); return g; }
main(int argc, char **argv) { pthread_attr_t sched_attr; int maxprio, minprio; int go = 1; struct sched_param fifo_param; struct sigaction ignoreChildDeath = {NULL, 0, (SA_NOCLDSTOP | SA_RESTART), NULL}; struct sigaction hupAction = {hupcatch, 0, SA_RESTART, NULL}; struct sigaction termAction = {termcatch, 0, SA_RESTART, NULL}; myName=argv[0]; ch_flag = 0; terminate = 0; fprintf(stderr,"%s daemon start.\n", myName); pthread_attr_init(&sched_attr); pthread_attr_setinheritsched(&sched_attr, PTHREAD_EXPLICIT_SCHED); pthread_attr_setschedpolicy(&sched_attr, /*SCHED_RR */ SCHED_FIFO); maxprio = sched_get_priority_max(SCHED_FIFO); minprio = sched_get_priority_min(SCHED_FIFO); sigaction(SIGCHLD, &ignoreChildDeath, NULL); /*zombie protection */ sigaction(SIGHUP, &hupAction, NULL); sigaction(SIGTERM, &termAction, NULL); if (terminate == TERM_TERM) { go = 0; } else { go = 1; } while (go) { /*The main restart loop */ terminate = 0; /*read config file here */ cfg_read(CONFIG_FILE, "", ""); /* do command line option processing, they override config file opts */ do_opts(argc, argv); if (!foreground) { daemon(); } wxin = serial_open(opts.ttydev); last_write_time = time(NULL); if (wxin > 0) { sane_defaults(); init_db(); if (setupio(wxin) < 0) { errlog(9, "setupio bailed."); } iobuf = make_cbuf(BSIZE); pthread_mutex_init(¤t_obs_lock, pthread_mutexattr_default); pthread_mutex_init(¤t_cal_lock, pthread_mutexattr_default); pthread_mutex_init(&terminate_lock, pthread_mutexattr_default); pthread_mutex_init(&cond_update_lock, pthread_mutexattr_default); pthread_cond_init(&cond_update, pthread_condattr_default); #if USE_CBUF /* fifo_param.sched_priority = (minprio + maxprio) / 2; pthread_attr_setschedparam(&sched_attr, &fifo_param);*/ pthread_create(&reader, /*pthread_attr_default */ NULL, (pthread_startroutine_t) serial_reader, (pthread_addr_t) iobuf); pthread_create(&parser, NULL /*&sched_attr*/, (pthread_startroutine_t) parse_input, (pthread_addr_t) iobuf); #if SCREENOUT pthread_create(&writer, NULL /*&sched_attr*/, (pthread_startroutine_t) screen_writer, (pthread_addr_t) NULL); #else /* Make a db writer thread */ pthread_create(&writer, NULL /*&sched_attr*/, (pthread_startroutine_t) db_writer, (pthread_addr_t) NULL); #endif pthread_join(reader, NULL); pthread_join(parser, NULL); pthread_join(writer, NULL); #else parse_input(iobuf); #endif release_cbuf(iobuf); serial_close(opts.ttydev); if (terminate == TERM_TERM) { errlog1(1, "%s: TERMINATE.", argv[0]); go = 0; } if (terminate == TERM_RESTART) { errlog1(1, "%s: RESTART.", argv[0]); go = 1; } #if SCREENOUT #else db_getout(dbconn); #endif } else { go = 0; errlog2(1, "%s: cannot open serial port: %s", argv[0], opts.ttydev); } } errlog1(1,"%s daemon shutdown.", myName); exit(0); }
void shell_service(void){ int i = 0, c, character, rc, no_error; //MAX_LINE is the longest the stdin buffer can be, so we won't overflow it char line_data[MAX_LINE]; pid_t cpid, term_pid; /* pid_t is typedef for Linux process ID */ int chld_status; unsigned char new_line[MAX_LINE]; unsigned char tmp_name[MAX_TMP]; unsigned char id_str[MAX_TMP]; char response[MAX_LINE]; char temp[MAX_LINE]; int id; /* variable names for file "handles" */ FILE *tmpFP; FILE *fp; /* get the parent process ID and use it to create a file name for the * temporary file with the format "tmpxxxxx" where xxxxx is the ID */ id = (int) getpid(); sprintf(id_str, "%d", id); strcpy(tmp_name,"tmp"); strcat(tmp_name, id_str); /* will not use the server socket */ Socket_close(welcome_socket); while((c = Socket_getc(connect_socket)) != EOF){ if(c != NEWLINE){ line_data[i] = c; i ++; } else{ line_data[i] = STRING_END; i++; //make sure the string is terminated if(i == MAX_LINE){ line_data[MAX_LINE - 1] = STRING_END; } cpid = fork(); /* create child == service process */ if (cpid == ERROR){ perror("fork"); exit (ERROR); } if (cpid == NORMAL) {/* code for the service process */ /* dynamically redirect stdout to the named temporary * file open for writing */ fp = freopen(tmp_name, "w", stdout); parse_input(line_data, &connect_socket); } /* end service process */ else{ i = 0; term_pid = waitpid(cpid, &chld_status, 0); if (term_pid == ERROR) perror("waitpid"); else{ if (WIFEXITED(chld_status)) sprintf(response, "End of input: PID %d exited, status = %d\n", cpid, WEXITSTATUS(chld_status)); else sprintf(response, "End of Input: PID %d did not exit normally\n", cpid); } if ((tmpFP = fopen (tmp_name, "r")) == NULL) { fprintf (stderr, "error opening tmp file\n"); exit (ERROR); } no_error = 0; while (!feof (tmpFP)) { no_error = 1; /* Get line from file */ if (fgets (new_line, sizeof(new_line), tmpFP) == NULL) break; send(new_line, &connect_socket); } rc = Socket_putc(NEWLINE, connect_socket); check_put(rc, &connect_socket); if(no_error) send(response, &connect_socket); rc = Socket_putc(STRING_END, connect_socket); check_put(rc, &connect_socket); /* delete the temporary file */ remove(tmp_name); // } } } } }
int main(int argc, char ** argv) { int s = -1, s_new = -1, s_ctl = -1; connection_t conn; struct sockaddr_storage their_addr[2]; u[0].storage = &their_addr[0]; u[1].storage = &their_addr[1]; socklen_t addr_size; struct pollfd fd; /* Parses input and sets the global variables */ parse_input(argc, argv); #ifdef _WIN32 if ( daemonize ) FreeConsole(); #else /* Should we fork and kill our parent? :p */ if ( daemonize ) { if ( debug ) log_printf("Forking into background ...\n"); int i = fork(); if ( i < 0 ) exit(1); if ( i > 0 ) exit(0); /* Forking into background */ } #endif #ifdef HAVE_SYSLOG if (use_syslog) openlog("rsd", 0, LOG_USER); #endif /* Sets up listening socket */ s = set_up_socket(); if ( s < 0 ) { log_printf("Couldn't set up listening socket. Exiting ...\n"); exit(1); } // Need to have a global socket so that we can cleanly close the socket in the signal handling routines. listen_socket = s; if ( debug ) log_printf("Listening for connection ...\n"); fd.fd = s; fd.events = POLLIN; /* Set up listening socket */ if ( listen(s, 10) == -1 ) { log_printf("Couldn't listen for connections \"%s\"...\n", strerror(errno)); exit(1); } #ifdef _WIN32 atexit(cleanup); #else /* Sets up interface for cleanly shutting down the server */ write_pid_file(); signal(SIGINT, cleanup); signal(SIGTERM, cleanup); // SIGPIPE may cause trouble ;) signal(SIGPIPE, SIG_IGN); #endif /* In case our backend API needs some initializing functions */ initialize_audio(); #ifdef _WIN32 printf( "==============================================================================\n" ":: RSD server : Win32 : %s - Copyright (C) 2010-2011 Hans-Kristian Arntzen ::\n" "==============================================================================\n", RSD_VERSION); #endif /* We're accepting two connects after each other, as we have one stream socket for audio data and one for controlling the server. Currently, the control socket is only useful for determining quickly when the client has hung up the connection. In case a control socket isn't supplied in a short time window (nmap, port scanners, etc), we shut down the connection. The connection, if accepted, will be handled in a new thread. */ for(;;) { addr_size = sizeof (their_addr[0]); s_new = accept(s, u[0].addr, &addr_size); if ( s_new == -1 ) { log_printf("Accepting failed... Errno: %d\n", errno); log_printf("%s\n", strerror( errno ) ); continue; } /* Accepts a ctl socket. They have to come from same source. * Times out very quickly (in case the server is being queried from an unknown source. */ if (poll(&fd, 1, 200) < 0) { perror("poll"); close(s_new); close(s_ctl); close(s); exit(1); } /* Accepts the connection if there's one pending */ if (fd.revents & POLLIN) { addr_size = sizeof (their_addr[0]); s_ctl = accept(s, u[1].addr, &addr_size); } /* We didn't get a control socket, so we don't care about it :) If s_ctl is 0, the backend will not perform any operations on it. */ else { if ( debug ) log_printf("CTL-socket timed out. Ignoring CTL-socket. \n"); s_ctl = 0; } if ( s_ctl == -1 ) { close(s_new); s_new = -1; log_printf("%s\n", strerror( errno ) ); continue; } /* Checks if they are from same source, if not, close the connection. */ /* Check will be ignored if there is no ctl-socket active. */ /* TODO: Security here is *retarded* :D */ if ( (s_ctl > 0) && valid_ips(their_addr) < 0 ) { close(s_new); s_new = -1; close(s_ctl); s_ctl = -1; continue; } conn.socket = s_new; conn.ctl_socket = s_ctl; new_sound_thread(conn); s_new = -1; // Makes sure that we cannot clutter the backend connection in any way. s_ctl = -1; } return 0; }
int main(void) { #if CGIC_LOCAL_TEST_0 /* Get input from web */ char *pinput = get_input(); //char *pinput = get_input_test(); if ( NULL == pinput ) { return 0; } /* Parse input from web */ struct data_from_web info; /* Parse input fail */ if ( 0 != parse_input(pinput, &info) ) { free(pinput); return 0; } /* Deal with info from web, deliver task according to "action" */ switch(info.action) { case ACTION_GETLIST: action_getlist(&info); break; case ACTION_BACKUP: action_backup(&info); break; case ACTION_RECOVER: action_recover(&info); break; case ACTION_DELETE: action_delete(&info); break; case ACTION_SETIP: action_setip(&info); break; case ACTION_GETIP: action_getip(&info); break; default: break; } /* Output json string */ free(pinput); return 0; #elif CGIC_LOCAL_TEST_1 /* Get input from web */ char *pinput = get_input_test(); /* Parse input from web */ struct data_from_web info; /* Parse input fail */ if ( 0 != parse_input(pinput, &info) ) { puts("parse input fail"); free(pinput); return 0; } /* Deal with info from web */ printf("module = %s\n", info.module); printf("action = %d\n", info.action); printf("dbid = %d\n", info.dbid); printf("remark = %s\n", info.remark); /* Output json string */ output_test(); puts("output_test finished"); free(pinput); return 0; #elif CGIC_LOCAL_TEST_2 /* Get input from web */ char *pinput = get_input_test(); if ( NULL == pinput ) { puts("No input string"); return 0; } /* Parse input from web */ struct data_from_web info; /* Parse input fail */ if ( 0 != parse_input(pinput, &info) ) { puts("Input fail"); free(pinput); return 0; } /* Deal with info from web */ puts("Parse result"); printf("module = %s\n", info.module); printf("action = %d\n", info.action); printf("dbid = %d\n", info.dbid); printf("remark = %s\n", info.remark); putchar('\n'); /* Deal with info from web, deliver task according to "action" */ puts("Dealing"); switch(info.action) { case ACTION_GETLIST: puts("Action: getlist"); action_getlist(&info); break; case ACTION_BACKUP: puts("Action: backup"); action_backup(&info); break; case ACTION_RECOVER: puts("Action: recover"); action_recover(&info); break; case ACTION_DELETE: puts("Action: delete"); action_delete(&info); break; case ACTION_SETIP: puts("Action: setip"); action_setip(&info); break; case ACTION_GETIP: puts("Action: getip"); action_getip(&info); break; default: puts("Unexpected action"); break; } /* Output json string */ free(pinput); return 0; #else /* The normal function */ /* Get input from web */ char *pinput = get_input(); if ( NULL == pinput ) { return 0; } /* Parse input from web */ struct data_from_web info; /* Parse input fail */ if ( 0 != parse_input(pinput, &info) ) { free(pinput); return 0; } /* Deal with info from web, deliver task according to "action" */ switch(info.action) { case ACTION_GETLIST: action_getlist(&info); break; case ACTION_BACKUP: action_backup(&info); break; case ACTION_RECOVER: action_recover(&info); break; case ACTION_DELETE: action_delete(&info); break; case ACTION_SETIP: action_setip(&info); break; case ACTION_GETIP: action_getip(&info); break; default: break; } /* Output json string */ free(pinput); return 0; #endif }
/** * rarch_main_init: * @argc : Count of (commandline) arguments. * @argv : (Commandline) arguments. * * Initializes the program. * * Returns: 0 on success, otherwise 1 if there was an error. **/ int rarch_main_init(int argc, char *argv[]) { int sjlj_ret; global_t *global = global_get_ptr(); init_state(); if ((sjlj_ret = setjmp(global->error_sjlj_context)) > 0) { RARCH_ERR("Fatal error received in: \"%s\"\n", global->error_string); return sjlj_ret; } global->inited.error = true; global->log_file = stderr; parse_input(argc, argv); if (global->verbosity) { char str[PATH_MAX_LENGTH] = {0}; RARCH_LOG_OUTPUT("=== Build ======================================="); rarch_info_get_capabilities(RARCH_CAPABILITIES_CPU, str, sizeof(str)); fprintf(stderr, "%s", str); fprintf(stderr, "Built: %s\n", __DATE__); RARCH_LOG_OUTPUT("Version: %s\n", PACKAGE_VERSION); #ifdef HAVE_GIT_VERSION RARCH_LOG_OUTPUT("Git: %s\n", rarch_git_version); #endif RARCH_LOG_OUTPUT("=================================================\n"); } rarch_ctl(RARCH_ACTION_STATE_VALIDATE_CPU_FEATURES, NULL); config_load(); { settings_t *settings = config_get_ptr(); if (settings && (settings->multimedia.builtin_mediaplayer_enable || settings->multimedia.builtin_imageviewer_enable)) { switch (rarch_path_is_media_type(global->path.fullpath)) { case RARCH_CONTENT_MOVIE: case RARCH_CONTENT_MUSIC: if (settings->multimedia.builtin_mediaplayer_enable) { #ifdef HAVE_FFMPEG global->has_set.libretro = false; global->inited.core.type = CORE_TYPE_FFMPEG; #endif } break; #ifdef HAVE_IMAGEVIEWER case RARCH_CONTENT_IMAGE: if (settings->multimedia.builtin_imageviewer_enable) { global->has_set.libretro = false; global->inited.core.type = CORE_TYPE_IMAGEVIEWER; } break; #endif default: break; } } } init_libretro_sym(global->inited.core.type); rarch_system_info_init(); init_drivers_pre(); if (!event_command(EVENT_CMD_CORE_INIT)) goto error; event_command(EVENT_CMD_DRIVERS_INIT); event_command(EVENT_CMD_COMMAND_INIT); event_command(EVENT_CMD_REWIND_INIT); event_command(EVENT_CMD_CONTROLLERS_INIT); event_command(EVENT_CMD_RECORD_INIT); event_command(EVENT_CMD_CHEATS_INIT); event_command(EVENT_CMD_REMAPPING_INIT); event_command(EVENT_CMD_SAVEFILES_INIT); #if defined(GEKKO) && defined(HW_RVL) { settings_t *settings = config_get_ptr(); if (settings) { event_command(EVENT_CMD_VIDEO_SET_ASPECT_RATIO); video_driver_set_aspect_ratio(settings->video.aspect_ratio_idx); } unsigned width = 0, height = 0; (void)width; (void)height; width = global->console.screen.resolutions.width; height = global->console.screen.resolutions.height; video_driver_set_video_mode(width, height, true); char msg[PATH_MAX_LENGTH] = {0}; snprintf(msg, sizeof(msg),"Resolution: %dx%d",width, height); rarch_main_msg_queue_push(msg, 1, 100, true); } #endif global->inited.error = false; global->inited.main = true; return 0; error: event_command(EVENT_CMD_CORE_DEINIT); global->inited.main = false; return 1; }
int main(int argc, char* argv[]){ int sockfd; /*printf("\nSERVER: starting the server\n");*/ /* Create a socket */ /*printf("SERVER: creating socket\n");*/ if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){ /*perror("SERVER: socket() failed");*/ printf("1 SERVER ERROR\n"); exit(EXIT_FAILURE); } int opt = 1; /* Make it so we can reuse the address and don't get the annoying "address already in use" error message */ if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0){ printf("2 SERVER ERROR\n"); exit(EXIT_FAILURE); } /* Configure connection settings */ struct sockaddr_in addr; char ipaddr[] = "127.0.0.1"; addr.sin_family = AF_INET; addr.sin_port = htons(7890); /*printf("SERVER: configuring the server to listen on %s:%d\n",ipaddr,ntohs(addr.sin_port));*/ if (inet_pton(AF_INET, ipaddr, &addr.sin_addr.s_addr) < 1){ /*perror("inet_pton() failed");*/ if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("3 SERVER ERROR\n"); exit(EXIT_FAILURE); } /* Bind the socket to an address */ /*printf("SERVER: binding the server to %s:%d\n",ipaddr,ntohs(addr.sin_port));*/ if (bind(sockfd,(struct sockaddr*)&addr,sizeof(addr)) == -1){ /*perror("SERVER: bind() failed");*/ if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("4 SERVER ERROR\n"); exit(EXIT_FAILURE); } /* Listen for incoming connections */ /*printf("SERVER: listening for an incoming connection\n");*/ if (listen(sockfd,SOMAXCONN) == -1){ /*perror("SERVER: listen() failed");*/ if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("5 SERVER ERROR\n"); exit(EXIT_FAILURE); } int clisock; struct sockaddr_in cliaddr; socklen_t clilength = sizeof(cliaddr); /* Handle incoming connections */ while(1){ /*printf("SERVER: waiting for a connection from a client\n");*/ if ((clisock = accept(sockfd,(struct sockaddr*)&cliaddr,&clilength)) == -1){ /*perror("SERVER: accept() failed");*/ if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("6 SERVER ERROR\n"); exit(EXIT_FAILURE); } /* Get information about the connecting client */ char addrbuf[INET_ADDRSTRLEN]; /*printf("SERVER: getting connection information about the client\n");*/ if (inet_ntop(AF_INET,&((&cliaddr)->sin_addr),addrbuf,INET_ADDRSTRLEN) == NULL){ /*perror("SERVER: inet_ntop() failed");*/ if (close(clisock) == -1){ /*perror("SERVER: close(client socket) failed");*/ } if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("7 SERVER ERROR\n"); exit(EXIT_FAILURE); } /*printf("SERVER: accepted a connection from the client %s:%d\n",addrbuf,ntohs(cliaddr.sin_port));*/ /* Read coordinate data x1 y1 x2 y2 from the client */ char buffer[BUFFER_SIZE]; bzero(buffer,BUFFER_SIZE); /*printf("SERVER: reading data from the client\n");*/ if (read(clisock,buffer,BUFFER_SIZE) == -1){ //STONESOUP:INTERACTION_POINT /*perror("SERVER: read failed()");*/ if (close(clisock) == -1){ /*perror("SERVER: close(client socket) failed");*/ } if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("8 SERVER ERROR\n"); exit(EXIT_FAILURE); } /* printf("SERVER: read %s from client\n",buffer); printf("SERVER: parsing the data from the client\n"); */ enum INPUT input; point p1,p2; char out[BUFFER_SIZE]; bzero(out,BUFFER_SIZE); if (get_input(buffer,out) == 0){ printf("9 SERVER ERROR\n"); exit(EXIT_FAILURE); } if ((input = parse_input(out,&p1,&p2)) != INPUT_POINTS){ if (close(clisock) == -1){ /*perror("SERVER: close(client socket) failed");*/ } if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } if (input == INPUT_ERROR){ printf("10 SERVER ERROR\n"); exit(EXIT_FAILURE); }else{ /*printf("SERVER: closing the server\n");*/ exit(EXIT_SUCCESS); } } /*printf("SERVER: found points (%d,%d) and (%d,%d)\n",p1.x,p1.y,p2.x,p2.y);*/ /* Compute the slope of the line formed by the two given points */ /*printf("SERVER: computing the slope for (%d,%d) and (%d,%d))\n",p1.x,p1.y,p2.x,p2.y);*/ float m; enum SLOPE slope = compute_slope(p1,p2,&m); bzero(buffer,BUFFER_SIZE); if ( slope == DEFINED_SLOPE ){ /* If the slope is defined, we can use the equation y = mx + b */ /* Compute the y-intercept of the line formed by the two points given the slope and point on the line */ /*printf("SERVER: computing the y-intercept using a slope of %f and the point (%d,%d)\n",m,p1.x,p1.y);*/ float b = compute_y_intercept(m,p1); /* Prepare the data y = mx + b that will be sent to the client */ /*printf("SERVER: creating the equation of the line to send back to the client\n");*/ if (snprintf(buffer,BUFFER_SIZE,"y = (%f)x + %f",m,b) < 0){ /*perror("SERVER: snprintf() failed\n");*/ if (close(clisock) == -1){ /*perror("SERVER: close(client socket) failed");*/ } if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("11 SERVER ERROR\n"); exit(EXIT_FAILURE); } }else{ /* If the slope is undefined, x = p1.x or p2.x (they will be the same in this case */ /*printf("SERVER: slope is undefined so creating the equation of the line (x = x1) to send back to the client\n");*/ if (snprintf(buffer,BUFFER_SIZE,"x = %lu",p1.x) < 0){ /*perror("SERVER: snprintf() failed\n");*/ if (close(clisock) == -1){ /*perror("SERVER: close(client socket) failed");*/ } if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("12 SERVER ERROR\n"); exit(EXIT_FAILURE); } } /* Send the data y = mx + b or x = n to the client */ /*printf("SERVER: writing %s to the client\n",buffer);*/ if (write(clisock,buffer,BUFFER_SIZE) == -1){ /*perror("SERVER: write() failed");*/ if (close(clisock) == -1){ /*perror("SERVER: close(client socket) failed");*/ } if (close(sockfd) == -1){ /*perror("SERVER: close(server socket) failed");*/ } printf("13 SERVER ERROR\n"); exit(EXIT_FAILURE); } /* Closing the socket used to communicate with the client */ /*printf("SERVER: closing the client socket\n");*/ if (close(clisock) == -1){ /*perror("SERVER: close(client socket) failed");*/ if (close(sockfd) !=0){ /*perror("SERVER: close() failed");*/ } printf("14 SERVER ERROR\n"); exit(EXIT_FAILURE); } } return 0; }
void goto_command(const char *arg, struct session *ses) { char A[BUFFER_SIZE], B[BUFFER_SIZE], tmp[BUFFER_SIZE], cond[BUFFER_SIZE]; int a, b, i, j, s; int d[MAX_LOCATIONS], ok[MAX_LOCATIONS], way[MAX_LOCATIONS]; char *path[MAX_LOCATIONS], *locs[MAX_LOCATIONS]; arg=get_arg(arg, A, 0, ses); arg=get_arg(arg, B, 1, ses); if ((!*A)||(!*B)) { tintin_eprintf(ses, "#SYNTAX: #goto <from> <to>"); return; } for (a=0;a<MAX_LOCATIONS;a++) if (ses->locations[a]&&!strcmp(ses->locations[a], A)) break; if (a==MAX_LOCATIONS) { tintin_eprintf(ses, "#Location not found: [%s]", A); return; } for (b=0;b<MAX_LOCATIONS;b++) if (ses->locations[b]&&!strcmp(ses->locations[b], B)) break; if (b==MAX_LOCATIONS) { tintin_eprintf(ses, "#Location not found: [%s]", B); return; } for (i=0;i<MAX_LOCATIONS;i++) { d[i]=INF; ok[i]=0; } d[a]=0; do { s=INF; for (j=0;j<MAX_LOCATIONS;j++) if (!ok[j]&&(d[j]<s)) s=d[i=j]; if (s==INF) { tintin_eprintf(ses, "#No route from %s to %s!", A, B); return; } ok[i]=1; for (struct routenode *r=ses->routes[i];r;r=r->next) if (d[r->dest]>s+r->distance) { if (!*(r->cond)) goto good; substitute_vars(r->cond, tmp); substitute_myvars(tmp, cond, ses); if (eval_expression(cond, ses)) { good: d[r->dest]=s+r->distance; way[r->dest]=i; } } } while (!ok[b]); j=0; for (i=b;i!=a;i=way[i]) d[j++]=i; for (d[i=j]=a;i>0;i--) { locs[i]=mystrdup(ses->locations[d[i]]); for (struct routenode *r=ses->routes[d[i]];r;r=r->next) if (r->dest==d[i-1]) path[i]=mystrdup(r->path); } /* we need to copy all used route data (paths and location names) because of ugly bad users who can use #unroute in the middle of a #go command */ locs[0]=mystrdup(ses->locations[b]); for (i=j;i>0;i--) { if (ses->mesvar[MSG_GOTO]) { tintin_printf(ses, "#going from %s to %s", locs[i], locs[i-1]); } parse_input(path[i], true, ses); } for (i=j;i>=0;i--) SFREE(locs[i]); for (i=j;i>0;i--) SFREE(path[i]); set_variable("loc", B, ses); }