int main() { init_globals(); test1(5); printf("\n\n"); test1(32); printf("\n\n"); test1(35); printf("\n\n"); test2(5); printf("\n\n"); test2(32); printf("\n\n"); test2(35); printf("\n\n"); delete_globals(); return 0; }
int main( void ) { init_arduino( ); init_globals( ); init_devices( ); init_communication_interfaces( ); start_timers( ); DEBUG_PRINTLN( "init complete" ); while( true ) { check_for_incoming_message( ); check_for_faults( ); } }
int main(int argv, char **args) { init_globals(); QApplication app(argv, args); // QDesktopWidget *desktop = app.desktop(); // qDebug() << "Width: " << desktop->screenGeometry(-1).width(); // qDebug() << "Height: " << desktop->screenGeometry(-1).height(); // GTK+ style creates a border around the window. // Cannot find the stylesheet property associated with this, // so force Fusion style to avoid the issue. app.setStyle("Fusion"); EventFilter filter; app.installNativeEventFilter(&filter); Server server; QObject::connect(&filter, &EventFilter::caughtEvent, &server, &Server::clientListChanged); // This creates the QGraphicsView (and also the window) Panel panel; // These are required to position the QGraphicsScene correctly. // This is due to a hardcoded scene margin built into the qt5 libs. // It is overcome here by position the window marginally outside the screen. int horizontalMargin = 1; int verticalMargin = 2; panel.resize(g.panelWidth + horizontalMargin * 2, g.panelHeight + verticalMargin * 2); panel.move(-horizontalMargin, g.screenHeight - g.panelHeight - verticalMargin); panel.show(); QObject::connect(&server, &Server::clientListUpdated, &panel, &Panel::drawPanel); return app.exec(); }
/* this function is intended to encapsulate the basic swupd * initializations for the majority of commands, that is: * - Make sure root is the user running the code * - Initialize log facility * - Get the lock * - initialize mounted directories * - Initialize curl */ int swupd_init(int *lock_fd) { int ret = 0; check_root(); if (!init_globals()) { ret = EINIT_GLOBALS; goto out_fds; } get_mounted_directories(); if (create_required_dirs()) { ret = EREQUIRED_DIRS; goto out_fds; } *lock_fd = p_lockfile(); if (*lock_fd < 0) { ret = ELOCK_FILE; goto out_fds; } if (swupd_curl_init() != 0) { ret = ECURL_INIT; goto out_close_lock; } return ret; out_close_lock: v_lockfile(*lock_fd); out_fds: dump_file_descriptor_leaks(); return ret; }
int test1_12F_mutatee() { globals.passedTest_ = FALSE; if (setupFortranOutput()) { logerror("Error redirecting Fortran component output to log file\n"); } init_globals(); func12_1(); if (cleanupFortranOutput()) { logerror("Error restoring output to stdout\n"); } /* Combine fortran passedTest with C passedTest */ if (globals.passedTest_) { test_passes(testname); return 0; } else { return -1; } }
static int bundle_add() { char *filename = NULL; int f = -1; int ret = 0; if (!init_globals()) { free_globals(); return -1; } init_log_stdout(); verbose = 1; if (asprintf(&filename, "%s/%s", BUNDLES_DIR, bundle) <= 0) { log_stdout("Error: allocating memory, exiting now\n\n"); abort(); } f = open(filename, O_WRONLY | O_CREAT | O_NONBLOCK | O_NOCTTY, MODE_RW_O); if (f < 0) { log_stdout("cannot create bundle file %s exiting now\n\n", filename); ret = EXIT_FAILURE; goto out; } close(f); log_stdout("bundle %s added, trying to install it now\n", filename); verbose = 0; ret = verify_fix(VERIFY_NOPICKY); out: free_globals(); free(filename); free(bundle); return ret; }
int init_key_store(char *thread_id, init_type i_type) { int ret; if(g_key_store != NULL) { return -1; } #ifdef LOG_TO_FILE_INSTEAD_OF_STDOUT freopen("key_values.log", "w", stdout); #endif ret = init_globals(thread_id); if(ret < 0) { return -1; } ret = init_key_store_encrypt(thread_id); if(ret < 0) { return -1; } ret = init_key_storage_memory(thread_id, i_type); if(ret < 0) { return -1; } ret = reset_key_storage("[MAIN THREAD]"); if(ret < 0) { return -1; } #ifdef ENABLE_LOGGING fprintf(stdout, "%s Successfully initialized key storage\n", thread_id); #endif return 0; }
void test_with_empty_headers() { multipartparser parser; #define BOUNDARY "boundary" #define BODY \ "--" BOUNDARY "\r\n" \ "\r\n" \ "This is implicitly typed plain ASCII text.\r\n" \ "It does NOT end with a linebreak." \ "\r\n--" BOUNDARY "--\r\n" init_globals(); multipartparser_init(&parser, BOUNDARY); assert(multipartparser_execute(&parser, &g_callbacks, BODY, strlen(BODY)) == strlen(BODY)); assert(g_body_begin_called); assert(g_parts.size() == 1); assert(g_parts.front().headers.empty()); assert(g_body_end_called); #undef BOUNDARY #undef BODY }
int init(int argc, char *argv[]) { int rc; opal_cmd_line_t cmd_line; /* Setup and parse the command line */ init_globals(); opal_cmd_line_create(&cmd_line, cmd_line_init); mca_base_cmd_line_setup(&cmd_line); if (OPAL_SUCCESS != (rc = opal_cmd_line_parse(&cmd_line, true, argc, argv)) ) { if (OPAL_ERR_SILENT != rc) { fprintf(stderr, "%s: command line error (%s)\n", argv[0], opal_strerror(rc)); } return rc; } /* * Since this process can now handle MCA/GMCA parameters, make sure to * process them. */ mca_base_cmd_line_process_args(&cmd_line, &environ, &environ); }
/*********************************************************************************************** MAIN MENU FOR RETAIL ***********************************************************************************************/ int main (void) { struct tm intim; int Ret_val; double amount; unsigned char str[100] = ""; pthread_t syncT; pthread_attr_t attr; int newprio; struct sched_param param; int ret; //fp = fopen (logFile, "w+"); fp = stdout; fprintf(fp,"Begun main()"); fflush(fp); lk_open (); prn_open (); mscr_open (); lk_dispinit (); lk_dispclr(); strcpy(DATABASE,"/mnt/jffs2/fps.sqlite"); initialize_db (); open_sqlite (DATABASE); strcpy(CONFIG_FILE, get_config("CONFIG_FILE",tmpbuf,"0")); //Need OFFICE ID From config file before init_globals read_config (CONFIG_FILE); strcpy(OFFICE_ID,getVal("office_id")); // Get from config file strcpy(SESSION_ID,""); fprintf(fp,"office_id:",OFFICE_ID); fflush(fp); init_globals(); strcpy(IP,getVal("remote_url")); strcpy(shop_id,getVal("shop")); strcpy(terminal,getVal("terminal")); strcpy(tempFile,"/mnt/jffs2/dat"); strcpy(svr_username,getVal("server_user")); strcpy(svr_password,getVal("server_pwd")); setAuthType(); if(strcmp(toUpper(getVal("show_splash")),"TRUE")==0) { lk_disptext (1, 0, " PDS ", 1); lk_disptext (3, 0, " Govt of AP", 0); lk_disptext (4, 0, " Version:0.9", 0); lk_disptext (5, 0, " Enter to continue", 0); lk_getkey (); lk_dispclr (); } if(strcmp(toUpper(getVal("commMode")),"ETHERNET") == 0) ip_setup (); strcpy(background,getVal("background")); pthread_attr_init(&attr); pthread_attr_setschedpolicy(&attr, SCHED_OTHER); newprio = 1; param.sched_priority = newprio; pthread_attr_setschedparam(&attr,¶m); if(strcmp(background,"true")==0) { fprintf(fp,"Starting a background thread"); fflush(fp); if (pthread_create (&syncT, &attr, syncThread, NULL) != 0) fprintf (stderr, "Error creating the thread"); } while(1) { ret = login(); printFlag = FALSE; if(ret==USER) main_menu(); else if(ret == ADMIN) admin_menu(); else { lk_dispclr(); lk_disptext (2, 0, "Invalid credentials", 0); lk_getkey (); lk_dispclr (); } } prn_close (); // closing printer lk_close (); // closing pinpad mscr_close (); // closing magnetic swipe close_sqlite (); fprintf(fp,"Ended main()"); fflush(fp); return SUCCESS; }
int main(int argc, char *argv[]) { FILE *fp = stdin; fd_set fdset; struct timeval timeout; int ch, i, maxfd = 0, send_counter = 0; struct flags flags; struct payload_list *pl; #ifdef IPSEC_POLICY_IPSEC char *policy = NULL; #endif memset(&flags, 0, sizeof(flags)); openlog("rrenumd", LOG_PID, LOG_DAEMON); /* get options */ while ((ch = getopt(argc, argv, "c:sdf" #ifdef IPSEC #ifdef IPSEC_POLICY_IPSEC "P:" #else /* IPSEC_POLICY_IPSEC */ "AE" #endif /* IPSEC_POLICY_IPSEC */ #endif /* IPSEC */ )) != -1){ switch (ch) { case 'c': if((fp = fopen(optarg, "r")) == NULL) { syslog(LOG_ERR, "<%s> config file %s open failed", __func__, optarg); exit(1); } break; case 's': fp = stdin; break; case 'd': flags.debug = 1; break; case 'f': flags.fg = 1; break; #ifdef IPSEC #ifdef IPSEC_POLICY_IPSEC case 'P': flags.policy = 1; policy = strdup(optarg); break; #else /* IPSEC_POLICY_IPSEC */ case 'A': flags.auth = 1; break; case 'E': flags.encrypt = 1; break; #endif /* IPSEC_POLICY_IPSEC */ #endif /*IPSEC*/ default: show_usage(); } } argc -= optind; argv += optind; /* set log level */ if (flags.debug == 0) (void)setlogmask(LOG_UPTO(LOG_ERR)); if (flags.debug == 1) (void)setlogmask(LOG_UPTO(LOG_INFO)); /* init global variables */ init_globals(); config(&fp); sock6_open(&flags #ifdef IPSEC_POLICY_IPSEC , policy #endif /* IPSEC_POLICY_IPSEC */ ); sock4_open(&flags #ifdef IPSEC_POLICY_IPSEC , policy #endif /* IPSEC_POLICY_IPSEC */ ); if (!flags.fg) daemon(0, 0); FD_ZERO(&fdset); if (with_v6dest) { FD_SET(s6, &fdset); if (s6 > maxfd) maxfd = s6; } if (with_v4dest) { FD_SET(s4, &fdset); if (s4 > maxfd) maxfd = s4; } /* ADHOC: timeout each 30seconds */ memset(&timeout, 0, sizeof(timeout)); /* init temporary payload_list and send_counter*/ pl = pl_head; send_counter = retry + 1; while (1) { struct fd_set select_fd = fdset; /* reinitialize */ if ((i = select(maxfd + 1, &select_fd, NULL, NULL, &timeout)) < 0){ syslog(LOG_ERR, "<%s> select: %s", __func__, strerror(errno)); continue; } if (i == 0) { /* timeout */ if (pl == NULL) exit(0); rrenum_snd_eachdst(pl); send_counter--; timeout.tv_sec = 30; if (send_counter == 0) { timeout.tv_sec = 0; pl = pl->pl_next; send_counter = retry + 1; } } if (FD_ISSET(s4, &select_fd)) rrenum_input(s4); if (FD_ISSET(s6, &select_fd)) rrenum_input(s6); } }
static bool parse_options(int argc, char **argv) { int opt; //set default initial values set_format_string(NULL); while ((opt = getopt_long(argc, argv, "hxdu:P:c:v:sF:p:", prog_opts, NULL)) != -1) { switch (opt) { case '?': case 'h': print_help(argv[0]); exit(EXIT_SUCCESS); case 'd': download_only = true; break; case 'u': if (!optarg) { printf("Invalid --url argument\n\n"); goto err; } if (version_server_urls[0]) { free(version_server_urls[0]); } if (content_server_urls[0]) { free(content_server_urls[0]); } string_or_die(&version_server_urls[0], "%s", optarg); string_or_die(&content_server_urls[0], "%s", optarg); break; case 'P': if (sscanf(optarg, "%ld", &update_server_port) != 1) { printf("Invalid --port argument\n\n"); goto err; } break; case 'c': if (!optarg) { printf("Invalid --contenturl argument\n\n"); goto err; } if (content_server_urls[0]) { free(content_server_urls[0]); } string_or_die(&content_server_urls[0], "%s", optarg); break; case 'v': if (!optarg) { printf("Invalid --versionurl argument\n\n"); goto err; } if (version_server_urls[0]) { free(version_server_urls[0]); } string_or_die(&version_server_urls[0], "%s", optarg); break; case 's': cmd_line_status = true; break; case 'F': if (!optarg || !set_format_string(optarg)) { printf("Invalid --format argument\n\n"); goto err; } break; case 'p': /* default empty path_prefix updates the running OS */ if (!optarg) { printf("Invalid --path argument\n\n"); goto err; } if (path_prefix) { /* multiple -p options */ free(path_prefix); } string_or_die(&path_prefix, "%s", optarg); break; case 'x': force = true; break; default: printf("Unrecognized option\n\n"); goto err; } } if (!init_globals()) { return false; } return true; err: print_help(argv[0]); return false; }
int main(int argc, char *argv[]) { /* MAIN CODE STARTS HERE */ int i, /* j, */ bin; double val, bin_width; STATS stats; char log_name[25]; /* Check for correct number of comand line arguments */ if (argc != 4) { fprintf(stderr, "Missing comand line arguments,\nUSAGE: <program name> <config file> <points file> <wind file>\n\n"); exit(1); } /* Each node opens a file for logging */ sprintf(log_name, "%s", LOG_FILE); fprintf(stderr, "%s\n", log_name); log_file = fopen(log_name, "w+"); if (log_file == NULL) { fprintf(stderr, "Cannot open LOG file=[%s]:[%s]. Exiting.\n", log_name, strerror(errno)); exit(1); } /* Initialize the global variables (see top of file) with inputs from the configuration file. */ if ( init_globals(argv[1]) ) { exit(1); } #ifdef _PRINT fflush(log_file); #endif /*make sure the points file exists*/ in_points= fopen(argv[2], "r"); if (in_points == NULL) { fprintf(stderr, "Cannot open points file=[%s]:[%s]. Exiting.\n", argv[2], strerror(errno)); exit_now(1); } /* Input the data points from a file using the get_points function. */ if (get_points(in_points) ) { exit_now(1); } #ifdef _PRINT fflush(log_file); #endif /*make sure the wind file exists*/ in_wind= fopen(argv[3], "r"); if (in_wind == NULL) { fprintf(stderr, "Cannot open wind file=[%s]:[%s]. Exiting.\n", argv[3], strerror(errno)); exit_now(1); } if (get_wind(in_wind) ) { exit_now(1); } #ifdef _PRINT fflush(log_file); #endif set_global_values(log_file); #ifdef _PRINT fflush(log_file); #endif set_eruption_values(&e, W[0]); for (i = 0; i < num_pts; i++) {/* For each location */ tephra_calc(&e, pt+i, W[0], &stats); } #ifdef _PRINT fprintf(log_file, "Calculated mass...\n"); for (i = 0; i < num_pts; i++) { fprintf(log_file, "[%.0f][%.0f] %g ", (pt+i)->easting, (pt+i)->northing, (pt+i)->calculated_mass) ; fprintf(log_file, "\n"); } fprintf(log_file, "Finished.\n"); fflush(log_file); #endif fprintf(stderr,"\nMin Particle Fall Time = %gs\nMax Particle Fall Time = %gs\n",stats.min_falltime, stats.max_falltime); //printf("Mean_fall_time %15.6e\n",stats. /*phi_bins = (int)((erupt+j)->max_phi - (erupt+j)->min_phi); if (phi_bins < 1) phi_bins = 1; */ bin_width = (e.max_phi - e.min_phi)/PART_STEPS; printf("#EAST NORTH ELEV Kg/m^2 "); for (bin = 0; bin < PART_STEPS; bin++) printf("[%6.5f:%6.5f) ", e.min_phi + bin_width*bin, e.min_phi + bin_width*(bin+1)); printf("\n"); fprintf(stderr, "PART_STEPS=%d bin_width=%g\n", PART_STEPS, bin_width); for (i=0; i < num_pts; i++) { printf("%20.8e %20.8e %20.8e %20.8e ", (pt+i)->easting, (pt+i)->northing, (pt+i)->elevation, (pt+i)->calculated_mass); ///* Print out percent of total */ for (bin=0; bin < PART_STEPS; bin++) { //val = ((pt+i)->calculated_phi[bin]/(pt+i)->calculated_mass); val = (pt+i)->calculated_phi[bin]; //fprintf(stderr, "bin = %g mass = %g ", (pt+i)->phi[bin], (pt+i)->mass ) printf("%20.8e ", val); } printf("\n"); } print_for_stats(0); fprintf(log_file, "Finished.\n"); exit_now(0); return 1; }
int main(int argc, char **argv){ int i; int ctr; int fileCount; int fileEnd; int fileStart; char gzSAM; char *indirSAM; char *depthFile; char *out_prefix; char *gene; char **c_depths; init_globals(); gzSAM = 0; indirSAM = NULL; depthFile = NULL; out_prefix = NULL; gene=NULL; n_sam_e = 0; n_sam_b =0; fileCount = 0; fileEnd = 0; fileStart = 1; c_depths = NULL; for (i=1; i<argc; i++){ /* modes */ if (!strcmp(argv[i], "--prep")) set_runmode(PREP); else if (!strcmp(argv[i], "--read")) set_runmode(READSAM); else if (!strcmp(argv[i], "--call")) set_runmode(CALL); else if (!strcmp(argv[i], "--conc")) set_runmode(CONC); /* compulsory parameters for all modes */ else if (!strcmp(argv[i], "-conf")) set_str(&GENOME_CONF, argv[i+1]); /* compulsory parameters for the PREP mode */ else if (!strcmp(argv[i], "-fasta")) set_str(&GENOME_FASTA, argv[i+1]); else if (!strcmp(argv[i], "-gaps")) set_str(&GENOME_GAPS, argv[i+1]); /* optional parameters for the PREP mode */ else if (!strcmp(argv[i], "-pseudoa")) set_str(&GENOME_PSEUDO , argv[i+1]); else if (!strcmp(argv[i], "-lw_size")) LW_SIZE = atoi(argv[i+1]); else if (!strcmp(argv[i], "-sw_size")) SW_SIZE = atoi(argv[i+1]); else if (!strcmp(argv[i], "-cw_size")) CW_SIZE = atoi(argv[i+1]); else if (!strcmp(argv[i], "-lw_slide")) LW_SLIDE = atoi(argv[i+1]); else if (!strcmp(argv[i], "-sw_slide")) SW_SLIDE = atoi(argv[i+1]); /* compulsory parameters for READ, CALL and CONC modes */ else if (!strcmp(argv[i], "-depth")) set_str(&depthFile, argv[i+1]); /* compulsory paramaters for CONC mode*/ else if (!strcmp(argv[i], "-concdepth")){ fileStart=i+1; fileEnd=i+1; i++; while (i<argc && argv[i][0]!='-') fileEnd=i++; i--; fileCount = fileEnd-fileStart+1; if (fileEnd == fileStart ){ fprintf(stderr, "No files are given.\n"); return 0; } c_depths = getMem( fileCount * sizeof * c_depths); for ( ctr=0; ctr<fileCount; ctr++){ set_str(&c_depths[ctr], argv[ctr+fileStart]); } } /* compulsory parameters for the READ mode */ else if (!strcmp(argv[i], "-samdir")) set_str(&indirSAM, argv[i+1]); /* optional parameters for the SAM mode */ else if (!strcmp(argv[i], "--gz")) gzSAM = 1; /* optional parameters for the SAM mode */ else if (!strcmp(argv[i], "-nsam")){ n_sam_b = atoi(argv[i+1]); n_sam_e = atoi(argv[i+2]); } /* compulsory parameters for the CALL mode */ else if (!strcmp(argv[i], "-o")) set_str(&out_prefix, argv[i+1]); /* optional parameters for the CALL mode */ else if (!strcmp(argv[i], "-cont_win")) CONT_WINDOW = atoi(argv[i+1]); else if (!strcmp(argv[i], "-cut_win")) CUT_WINDOW = atoi(argv[i+1]); else if (!strcmp(argv[i], "--xx")) set_gender(FEMALE); else if (!strcmp(argv[i], "--xy")) set_gender(MALE); else if (!strcmp(argv[i], "--multgc")) MULTGC = 1; else if (!strcmp(argv[i], "-mindup")) MIN_DUP = atoi(argv[i+1]); else if (!strcmp(argv[i], "-gene")) set_str(&gene, argv[i+1]); /* generic stuff */ else if (!strcmp(argv[i], "-v")){ fprintf (stdout, "\nmrCaNaVaR version %s\nLast update: %s\n", VERSION, LAST_UPDATE); return 0; } else if (!strcmp(argv[i], "-h")){ printHelp(argv[0]); return 0; } else if (!strcmp(argv[i], "--verbose")) VERBOSE = 1; else if (!strcmp(argv[i], "--disable-sam-check")) CHECKSAM = 0; } switch(RUNMODE){ case NONE: print_error("No run mode selected.\nSelect mode: --prep, ---read,--call or --conc\n"); break; case PREP: fprintf(stdout, "Mode: Prepare genome...\n"); prep_genome(); break; case READSAM: fprintf(stdout, "Mode: Read SAM ...\n"); read_mapfiles(indirSAM, depthFile, gzSAM); break; case CALL: fprintf(stdout, "Mode: Call copy numbers ...\n"); call_cnv(depthFile, out_prefix,gene); break; case CONC: fprintf(stdout, "Mode: Merge depth files...\n"); conc_depth(c_depths, fileCount, depthFile); break; default: break; } return 0; }
int main(int argc, char **argv){ int status = 0; init_globals(); atexit(cleanup); /* * PROBLEM * We used to call init_signals() only after init_daemon(). But in * that case, when started with -F or -D -D, the signals are * not caught in Linunx and OSX (they are caught in FreeBSD). nbspd and * npemwind die, but leave the pid file and the web server. * [It seems that the signals are not blocked in the main thread as * the code in signal.c should ensure.] * Adding this call here * * status = init_signals(); * * makes OSX and Linux respond well when the daemon is run in the foreground. * If the call is made after the tcl configure(), the problem repeats; * it has to be before the configure() function. * * The problem is that in FreeBSD-7.1, when init_signals() is called here, * then no threads are spawned afterwards. * * The solution was to split init_signals() in two parts, one that * block the signals and the other spawns the thread. I don't fully * understand what in tcl is causing this (Fri Mar 13 11:43:09 AST 2009). */ status = init_signals_block(); if(status == 0){ /* * This will configure it with the default configuration * file, if it exists. * * This note and Tcl... code line is taken from the nbsp source code. * [First initialize the tcl library once and for all. It was not * necessary to call this in unix, but cygwin needs it or EvalFile * seg faults.] */ Tcl_FindExecutable(argv[0]); status = configure(); } if(status == 0) status = parse_args(argc, argv); if(status == 0){ if(g.configfile != NULL){ /* * This will reconfigure it with the user-supplied config file */ status = configure(); } } /* * if [-C] was given, print the configuration and exit. */ if(status == 0){ if(g.option_C == 1){ print_confoptions(); return(0); } } if(status == 0) status = validate_configuration(); /* * user and group are configurable so this must be done after reading * configuration options. */ if(status == 0) status = drop_privs(); if(status == 0) status = init_server_list(); if(status == 0) status = init_directories(); /* * The last configuration step, just before becoming a daemon. */ if(status == 0) status = exec_startscript(); if((status == 0) && (g.f_ndaemon == 0)) status = init_daemon(); set_log_debug(g.f_debug); set_log_verbose(g.f_verbose); if(status == 0) status = init_signals_thread(); /* * This has to be done after daemon() so that the lock file contains the * daemon's pid, not the starting program's. */ if(status == 0) status = init_lock(); /* * There are no shared queues in npemwin, otherwise the initialization * would go here. * * if(status == 0) * status = init_queues(); */ if(status == 0){ if(g.serverprotocol != PROTOCOL_NONE) { g.f_server_enabled = 1; status = init_server(); } } if(status == 0){ if(g.httpd_enable > 0){ status = spawn_httpd_server(); } } if(status == 0){ if(g.bbserver_enable > 0){ status = spawn_bbregistrar(); } } if(status == 0) status = init_emwin_qfiles(); if(status == 0) init_periodic(); /* * If there are initialization errors, ask all threads to quit. */ if(status != 0) set_quit_flag(); while(get_quit_flag() == 0){ status = loop(); } if(status != 0) status = EXIT_FAILURE; return(status); }
/* This function is a fresh new implementation for a bundle * remove without being tied to verify loop, this means * improved speed and space as well as more roubustness and * flexibility. What it does is basically: * * 1) Read MoM and load all submanifests except the one to be * removed and then consolidate them. * 2) Load the removed bundle submanifest. * 3) Order the file list by filename * 4) Deduplicate removed submanifest file list that happens * to be on the MoM (minus bundle to be removed). * 5) iterate over to be removed bundle submanifest file list * performing a unlink(2) for each filename. * 6) Done. */ int remove_bundle(const char *bundle_name) { int lock_fd; int ret = 0; int current_version = CURRENT_OS_VERSION; struct manifest *current_mom, *bundle_manifest; /* Initially we don't support format nor path_prefix * for bundle_rm but eventually that will be added, then * set_format_string() and init_globals() must be pulled out * to the caller to properly initialize in case those opts * passed to the command. */ set_format_string(NULL); if (!init_globals()) { return EINIT_GLOBALS; } ret = swupd_init(&lock_fd); if (ret != 0) { printf("Failed updater initialization, exiting now.\n"); return ret; } /* os-core bundle not allowed to be removed... * although this is going to be caught later because of all files * being marked as 'duplicated' and note removing anything * anyways, better catch here and return success, no extra work to be done. */ if (strcmp(bundle_name, "os-core") == 0) { ret = EBUNDLE_NOT_TRACKED; goto out_free_curl; } if (!is_tracked_bundle(bundle_name)) { ret = EBUNDLE_NOT_TRACKED; goto out_free_curl; } current_version = read_version_from_subvol_file(path_prefix); swupd_curl_set_current_version(current_version); /* first of all, make sure STATE_DIR is there, recreate if necessary*/ ret = create_required_dirs(); if (ret != 0) { printf("State directory %s cannot be recreated, aborting removal\n", STATE_DIR); goto out_free_curl; } ret = load_manifests(current_version, current_version, "MoM", NULL, ¤t_mom); if (ret != 0) { goto out_free_curl; } /* load all tracked bundles into memory */ read_subscriptions_alt(); /* now popout the one to be removed */ ret = unload_tracked_bundle(bundle_name); if (ret != 0) { goto out_free_mom; } subscription_versions_from_MoM(current_mom, 0); /* load all submanifest minus the one to be removed */ recurse_manifest(current_mom, NULL); consolidate_submanifests(current_mom); /* Now that we have the consolidated list of all files, load bundle to be removed submanifest*/ ret = load_bundle_manifest(bundle_name, current_version, &bundle_manifest); if (ret != 0) { goto out_free_mom; } /* deduplication needs file list sorted by filename, do so */ bundle_manifest->files = list_sort(bundle_manifest->files, file_sort_filename); deduplicate_files_from_manifest(&bundle_manifest, current_mom); printf("Deleting bundle files...\n"); remove_files_in_manifest_from_fs(bundle_manifest); printf("Untracking bundle from system...\n"); rm_bundle_file(bundle_name); printf("Success: Bundle removed\n"); free_manifest(bundle_manifest); out_free_mom: free_manifest(current_mom); out_free_curl: if (ret) { printf("Error: Bundle remove failed\n"); } swupd_curl_cleanup(); v_lockfile(lock_fd); dump_file_descriptor_leaks(); return ret; }
RTcmix::RTcmix(float tsr, int tnchans, int bsize, const char *opt1, const char *opt2, const char *opt3) { init_globals(false, NULL); init(tsr, tnchans, bsize, opt1, opt2, opt3); }
RTCORE_API void rtcInit(const char* cfg) { cout << "in rtcInit " << endl; Lock<MutexSys> lock(g_mutex); TRACE(rtcInit); CATCH_BEGIN; if (g_initialized) { g_mutex.unlock(); process_error(RTC_INVALID_OPERATION,"already initialized"); g_mutex.lock(); return; } g_initialized = true; /* reset global state */ initSettings(); if (cfg != NULL) { size_t pos = 0; do { std::string tok = parseIdentifier (cfg,pos); if (tok == "threads" && parseSymbol(cfg,'=',pos)) { g_numThreads = parseInt(cfg,pos); #if defined(__MIC__) if (!(g_numThreads == 1 || (g_numThreads % 4) == 0)) { g_mutex.unlock(); process_error(RTC_INVALID_OPERATION,"Xeon Phi supports only number of threads % 4 == 0, or threads == 1"); g_mutex.lock(); return; } #endif } else if (tok == "isa" && parseSymbol (cfg,'=',pos)) { std::string isa = parseIdentifier (cfg,pos); if (isa == "sse" ) cpu_features = SSE; else if (isa == "sse2") cpu_features = SSE2; else if (isa == "sse3") cpu_features = SSE3; else if (isa == "ssse3") cpu_features = SSSE3; else if (isa == "sse41") cpu_features = SSE41; else if (isa == "sse42") cpu_features = SSE42; else if (isa == "avx") cpu_features = AVX; else if (isa == "avxi") cpu_features = AVXI; else if (isa == "avx2") cpu_features = AVX2; } else if ((tok == "tri_accel" || tok == "accel") && parseSymbol (cfg,'=',pos)) g_tri_accel = parseIdentifier (cfg,pos); else if ((tok == "tri_builder" || tok == "builder") && parseSymbol (cfg,'=',pos)) g_tri_builder = parseIdentifier (cfg,pos); else if ((tok == "tri_traverser" || tok == "traverser") && parseSymbol (cfg,'=',pos)) g_tri_traverser = parseIdentifier (cfg,pos); else if ((tok == "tri_accel_mb" || tok == "accel_mb") && parseSymbol (cfg,'=',pos)) g_tri_accel = parseIdentifier (cfg,pos); else if ((tok == "tri_builder_mb" || tok == "builder_mb") && parseSymbol (cfg,'=',pos)) g_tri_builder = parseIdentifier (cfg,pos); else if ((tok == "tri_traverser_mb" || tok == "traverser_mb") && parseSymbol (cfg,'=',pos)) g_tri_traverser = parseIdentifier (cfg,pos); else if (tok == "hair_accel" && parseSymbol (cfg,'=',pos)) g_hair_accel = parseIdentifier (cfg,pos); else if (tok == "hair_builder" && parseSymbol (cfg,'=',pos)) g_hair_builder = parseIdentifier (cfg,pos); else if (tok == "hair_traverser" && parseSymbol (cfg,'=',pos)) g_hair_traverser = parseIdentifier (cfg,pos); else if (tok == "hair_builder_replication_factor" && parseSymbol (cfg,'=',pos)) g_hair_builder_replication_factor = parseInt (cfg,pos); else if (tok == "verbose" && parseSymbol (cfg,'=',pos)) g_verbose = parseInt (cfg,pos); else if (tok == "benchmark" && parseSymbol (cfg,'=',pos)) g_benchmark = parseInt (cfg,pos); else if (tok == "flags") { g_scene_flags = 0; if (parseSymbol (cfg,'=',pos)) { do { std::string flag = parseIdentifier (cfg,pos); if (flag == "static" ) g_scene_flags |= RTC_SCENE_STATIC; else if (flag == "dynamic") g_scene_flags |= RTC_SCENE_DYNAMIC; else if (flag == "compact") g_scene_flags |= RTC_SCENE_COMPACT; else if (flag == "coherent") g_scene_flags |= RTC_SCENE_COHERENT; else if (flag == "incoherent") g_scene_flags |= RTC_SCENE_INCOHERENT; else if (flag == "high_quality") g_scene_flags |= RTC_SCENE_HIGH_QUALITY; else if (flag == "robust") g_scene_flags |= RTC_SCENE_ROBUST; } while (parseSymbol (cfg,',',pos)); } } } while (findNext (cfg,',',pos)); } if (g_verbose >= 1) { std::cout << "Embree Ray Tracing Kernels " << __EMBREE_VERSION__ << " (" << __DATE__ << ")" << std::endl; std::cout << " Compiler : " << getCompilerName() << std::endl; std::cout << " Platform : " << getPlatformName() << std::endl; std::cout << " CPU : " << stringOfCPUFeatures(getCPUFeatures()) << std::endl; std::cout << " Features : "; #if defined(__USE_RAY_MASK__) std::cout << "raymasks "; #endif #if defined (__BACKFACE_CULLING__) std::cout << "backfaceculling "; #endif #if defined(__INTERSECTION_FILTER__) std::cout << "intersection_filter "; #endif #if defined(__BUFFER_STRIDE__) std::cout << "bufferstride "; #endif std::cout << std::endl; #if defined (__MIC__) #if defined(__BUFFER_STRIDE__) std::cout << " WARNING: enabled 'bufferstride' support will lower BVH build performance" << std::endl; #endif #endif } /* CPU has to support at least SSE2 */ #if !defined (__MIC__) if (!has_feature(SSE2)) { g_mutex.unlock(); process_error(RTC_UNSUPPORTED_CPU,"CPU does not support SSE2"); g_mutex.lock(); return; } #endif g_error = createTls(); g_error_function = NULL; init_globals(); cout << "in rtcInit(), BVH4Register() " << endl; #if !defined(__MIC__) cout << "BVH4Register()" << endl; BVH4Register(); #else cout << "BVH4iRegister() " << endl; BVH4iRegister(); #endif cout << "BVH4MBRegister() " << endl; BVH4MBRegister(); BVH4HairRegister(); #if defined(__TARGET_AVX__) cout << "BVH8Register() " << endl; if (has_feature(AVX)) { BVH8Register(); } #endif InstanceIntersectorsRegister(); //if (g_verbose >= 2) printSettings(); TaskScheduler::create(g_numThreads); cout << " end rtcInit " << endl; CATCH_END; }
int main(int argc, char* argv[]) { // Initialisation argp_parse(&argp, argc, argv, 0, 0, 0); init_globals(); if(! wsinit() ) { fprintf(stderr, "Could not allocate grammar workspace\n"); return 1; } gsl_rng* rng = gsl_rng_alloc( gsl_rng_env_setup() ); if(!rng) { fprintf(stderr, "Could not create rng\n"); return 1; } // Create a set of grammars according to desired initial condition grammar_t grammars[agents]; for(unsigned a=0; a<agents; a++) { if(! (grammars[a] = ginit()) ) { fprintf(stderr, "Could not create grammar\n"); } switch(initial_condition) { case ic_random: randomise_associations(grammars[a], rng); break; case ic_identity: identity_associations(grammars[a]); break; case ic_rook: rook_associations(grammars[a], rng); break; default: fprintf(stderr, "Unknown initial condition\n"); return 1; } renew_pseudo_associations(grammars[a]); } // Print out initial coherence matrix printf("coherence agents=%u round=0\n", agents); for(unsigned a1=0; a1<agents; a1++) { for(unsigned a2=0; a2<agents; a2++) { printf("%g ", coherence(grammars[a1], grammars[a2])); } printf("\n"); } printf("\n"); unsigned interactions_per_round = agents * meanings * signals; for(unsigned t=0;t<rounds*interactions_per_round;t++) { // Update loop starts here // 1. Choose a pair of speakers unsigned a1 = gsl_rng_uniform_int(rng, agents); unsigned a2 = gsl_rng_uniform_int(rng, agents-1); if (a2 >= a1) a2++; // 2. Speaker selects a topic meaning_t m1 = sample_meaning(grammars[a1], rng); // 3. Speaker produces a signal for m signal_t s = produce_signal(grammars[a1], m1, rng); // 4. Listener infers a meaning meaning_t m2 = infer_meaning(grammars[a2], s, rng); // 5. Obtain feedback double fb = feedback > 0.0 ? stochastic_feedback(m1,m2,rng) : deterministic_feedback(m1,m2); // 6. Update grammars vary_association(grammars[a1], m1, s, fb*stepsize ); vary_association(grammars[a2], m2, s, fb*stepsize ); renew_pseudo_associations(grammars[a1]); renew_pseudo_associations(grammars[a2]); // Update loop ends here // Print out the coherence matrix at the end of each rounds if((t+1) % interactions_per_round == 0) { printf("coherence agents=%u round=%u\n", agents, (t+1)/interactions_per_round); for(unsigned a1=0; a1<agents; a1++) { for(unsigned a2=0; a2<agents; a2++) { printf("%g ", coherence(grammars[a1], grammars[a2])); } printf("\n"); } printf("\n"); } } // Print out grammars at the end for(unsigned a=0; a<agents; a++) { printf("grammar agent=%u meanings=%u signals=%u round=%u\n", a, meanings, signals, rounds); for(meaning_t m=0; m<meanings; m++) { for(signal_t s=0;s<signals; s++) { printf("%g ", get_association(grammars[a], m, s)); } printf("\n"); } printf("\n"); } // Print out pseudo grammars at the end for(unsigned a=0; a<agents; a++) { printf("pseudo agent=%u meanings=%u signals=%u round=%u\n", a, meanings, signals, rounds); for(meaning_t m=0; m<meanings; m++) { for(signal_t s=0;s<signals; s++) { printf("%g ", get_pseudo_association(grammars[a], m, s)); } printf("\n"); } printf("\n"); } return 0; }
int main(int argc,char const **argv) { printf("Test 1 - v0.1\n"); printf("libPeers\n"); printf("-----------------\n"); p2p_ctx *ctx; int i,j=kNUM_PEER_TEST; char address[24]; char *tmp_str1; init_globals(); printf("Parse args...\n"); parse_args(argc,(const char **)argv); /* Init a p2pctx instance */ ctx=p2p_init("0.0.0.0",g.port); /* Register new handler for messages */ p2p_reg_message_handle(ctx,handle_message); // p2p_details_get_address(ctx,tmp_str1); // p2p_details_get_port(ctx,); tmp_str1=sock_getaddress(ctx->s); printf("Create p2p_ctx@ %p on %s with port: %d\n",&ctx,tmp_str1,g.port); /* Manualy add peers to try to cennect to */ for(i=0;i<j;i++) { sprintf(address,"localhost:%d",kDEFAULT_PORT+i); p2p_add_peers(ctx,address); } /* Start the server thread */ p2p_start(ctx); char *command_str=malloc(512); do { if(sched_yield()) fprintf(stderr,"sched_yield returned non -1: errno=%d\n",errno); bzero(command_str,512); printf("Command: "); scanf("%s",command_str); if(strcmp(command_str,"quit")==0||strcmp(command_str,"q")==0) { g.done=true; } else if(strcmp(command_str,"s")==0) { printf("- send something\n"); } // sleep(1); printf("\n"); }while(g.done==false); printf("Cleanup...\n"); p2p_free(ctx); printf("Exiting...\n"); return 0; }
// The RTcmix constructor with default SR, NCHANS, and RTBUFSAMPS RTcmix::RTcmix() { init_globals(false, NULL); init(SR, NCHANS, RTBUFSAMPS, NULL, NULL, NULL); }
int search_main(int argc, char **argv) { int ret = 0; int lock_fd; struct manifest *MoM = NULL; if (!parse_options(argc, argv) || create_required_dirs()) { return EXIT_FAILURE; } if (search_type == '0') { /* Default to a system-side search */ search_type = 'e'; } if (!init_globals()) { ret = EINIT_GLOBALS; goto clean_exit; } ret = swupd_init(&lock_fd); if (ret != 0) { printf("Failed swupd initialization, exiting now.\n"); goto clean_exit; } if (!check_network()) { printf("Error: Network issue, unable to proceed with update\n"); ret = EXIT_FAILURE; goto clean_exit; } if (!init) { printf("Searching for '%s'\n\n", search_string); } ret = download_manifests(&MoM); if (ret != 0) { printf("Error: Failed to download manifests\n"); goto clean_exit; } if (init) { printf("Successfully retreived manifests. Exiting\n"); ret = 0; goto clean_exit; } /* Arbitrary upper limit to ensure we aren't getting handed garbage */ if (!display_files && ((strlen(search_string) <= 0) || (strlen(search_string) > NAME_MAX))) { printf("Error - search string invalid\n"); ret = EXIT_FAILURE; goto clean_exit; } do_search(MoM, search_type, search_string); clean_exit: free_manifest(MoM); free_globals(); swupd_curl_cleanup(); return ret; }
// The RTcmix constructor with settable SR, NCHANS; default RTBUFSAMPS RTcmix::RTcmix(float tsr, int tnchans) { init_globals(false, NULL); init(tsr, tnchans, RTBUFSAMPS, NULL, NULL, NULL); }
void do_it(JIT *jit) { init_globals(); Fields *filter_fields = new Fields(); filter_fields->add(filter_filepath); Fields *read_audio_fields = new Fields(); read_audio_fields->add(audio); read_audio_fields->add(audio_length); Fields *segment_fields = new Fields(); segment_fields->add(segment_offset); Fields *fft_fields = new Fields(); fft_fields->add(fft); Fields *ifft_fields = new Fields(); ifft_fields->add(clipped); FilterStageIR *filt = new FilterStageIR(filter, "filter", filter_fields); TransformStageIR *reader = new TransformStageIR(read_audio, "read_audio", filter_fields, read_audio_fields); PresegmentationStageIR *preseg = new PresegmentationStageIR(compute_num_segments, "compute_num_segments", read_audio_fields); SegmentationStageIR *seg = new SegmentationStageIR(segment, compute_num_segments, "segment", "compute_num_segments", read_audio_fields, segment_fields); TransformStageIR *fft_xform = new TransformStageIR(compute_fft, "compute_fft", segment_fields, fft_fields); BucketStageIR *bucketer = new BucketStageIR(bucket_fns, "bucket_fns", fft_fields, OUTER); ComparisonStageIR *ifft_xform = new ComparisonStageIR(compute_ifft, "compute_ifft", fft_fields, ifft_fields); // filt->merge_in(reader); // reader->merge_in(preseg); // seg->merge_in(fft_xform); // fft_xform->merge_in(bucketer); // // can't do filter parallel and tracking // filt->set_parallelizable(true); filt->parallelize(); filt->set_compact(true); // don't do atomic update reader->set_parallelizable(true); reader->parallelize(); bucketer->set_parallelizable(true); bucketer->parallelize(); preseg->set_parallelizable(true); preseg->parallelize(); preseg->set_compact(true); seg->set_parallelizable(true); seg->parallelize(); fft_xform->set_parallelizable(true); fft_xform->parallelize(); ifft_xform->set_parallelizable(true); ifft_xform->parallelize(); // ifft_xform->set_track_progress(true); // ifft_xform->set_num_tracking_splits(3); // ifft_xform->set_time_loop(true); ifft_xform->set_tileable(true); ifft_xform->tile(); PipelineIR *pipeline_full_data = new PipelineIR(); pipeline_full_data->register_stage(filt); pipeline_full_data->register_stage(reader); pipeline_full_data->register_stage(preseg); pipeline_full_data->register_stage(seg); pipeline_full_data->register_stage(fft_xform); pipeline_full_data->register_stage(bucketer); PipelineIR *pipeline_exemplars = pipeline_full_data->duplicate(); // full data has the comparison in it, so the left input becomes the exemplars output pipeline_full_data->register_stage(ifft_xform); // ifft_xform->force_commutative(); // ifft_xform->set_left_input(pipeline_exemplars->get_stages().back()); // pipeline_exemplars->merge(pipeline_full_data); // exemplars will run, then the data, then the comparison pipeline_full_data->build_pipeline(); // pipeline_exemplars->build_pipeline(); pipeline_full_data->dump(); LLVM::LLVMCodeGenerator codegen(jit); codegen.visit(pipeline_full_data->get_pipeline()); // codegen.visit(pipeline_exemplars->get_pipeline()); jit->dump(); #ifdef AOT_COMPILE AOT::aot_compile(jit->get_module().get(), "MF.o"); #else jit->add_module(); std::vector<Element *> elements = init_filepaths(); std::chrono::time_point<std::chrono::system_clock> start = utils_get_time(); IR::cleanup(); MType::cleanup(); run1(jit, elements, filter_filepath, audio, audio_length, segment_offset, fft, clipped); // run2(jit, elements, elements, filter_filepath, audio, audio_length, segment_offset, fft, clipped); std::chrono::time_point<std::chrono::system_clock> end = utils_get_time(); utils_print_time_duration(start, end); #endif fftwf_destroy_plan(*fft_plan); fftwf_destroy_plan(*ifft_plan); fftwf_free(fft_plan); fftwf_free(ifft_plan); output_file.close(); delete(filter_filepath); delete(audio); delete(audio_length); delete(segment_offset); delete(fft); delete(clipped); }
void init_stuff() { int i; int seed; chdir(DATA_DIR); #ifndef WINDOWS setlocale(LC_NUMERIC,"en_US"); #endif init_translatables(); //create_error_mutex(); init_globals(); init_crc_tables(); init_zip_archives(); cache_system_init(MAX_CACHE_SYSTEM); init_texture_cache(); init_vars(); read_config(); file_check_datadir(); #ifdef LOAD_XML //Well, the current version of the map editor doesn't support having a datadir - will add that later ;-) load_translatables(); #endif #ifdef LINUX #ifdef GTK2 init_filters(); #else file_selector = create_fileselection(); #endif #endif //LINUX init_gl(); window_resize(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // glDepthFunc(GL_LEQUAL); glEnable(GL_TEXTURE_2D); glShadeModel(GL_SMOOTH); glFrontFace(GL_CCW); glCullFace(GL_BACK); glEnable(GL_NORMALIZE); glClearColor( 0.0, 0.0, 0.0, 0.0 ); glClearStencil(0); seed = time (NULL); srand (seed); init_texture_cache(); init_particles (); init_e3d_cache(); init_2d_obj_cache(); for(i=0; i<256; i++) tile_list[i]=0; for (i = 0; i < MAX_LIGHTS; i++) lights_list[i] = NULL; new_map(256,256); load_all_tiles(); //lights setup build_global_light_table(); build_sun_pos_table(); reset_material(); init_lights(); //disable_local_lights(); //clear_error_log(); // Setup the new eye candy system #ifdef EYE_CANDY ec_init(); #endif //EYE_CANDY init_gl_extensions(); if(have_multitexture) #ifdef NEW_TEXTURES ground_detail_text = load_texture_cached("./textures/ground_detail.bmp", tt_mesh); #else /* NEW_TEXTURES */ ground_detail_text = load_texture_cache ("./textures/ground_detail.bmp",255); #endif /* NEW_TEXTURES */ //load the fonts texture init_fonts(); #ifdef NEW_TEXTURES icons_text=load_texture_cached("./textures/gamebuttons.bmp", tt_gui); buttons_text=load_texture_cached("./textures/buttons.bmp", tt_gui); #else /* NEW_TEXTURES */ icons_text=load_texture_cache("./textures/gamebuttons.bmp",0); buttons_text=load_texture_cache("./textures/buttons.bmp",0); #endif /* NEW_TEXTURES */ //get the application home dir have_multitexture=0;//debug only #ifndef LINUX GetCurrentDirectory(sizeof(exec_path),exec_path); #else exec_path[0]='.';exec_path[1]='/';exec_path[2]=0; #endif init_browser(); if(SDL_InitSubSystem(SDL_INIT_TIMER)<0) { char str[120]; snprintf(str, sizeof(str), "Couldn't initialize the timer: %s\n", SDL_GetError()); log_error(__FILE__, __LINE__, str); SDL_Quit(); exit(1); } SDL_SetTimer (1000/(18*4), my_timer); SDL_EnableUNICODE(1); //we might want to do this later. // creating windows display_browser(); toggle_window(browser_win); display_o3dow(); toggle_window(o3dow_win); display_replace_window(); toggle_window(replace_window_win); display_edit_window(); toggle_window(edit_window_win); create_particles_window (); }
int main(int argc, char ** argv) { init_globals(); char c; char action = 0; char automate = 0; int database = 1; int compression = 1; int num_files = 0; int save_to_file = 0; int itable = 0; char* filename = "dummy.bin"; char* auto_filename = "dummy.bin"; char* outfile_name = "dummy.bin"; num_loaded_indices = 0; char *help = "usage: %s [-h] [-s] [-l] [-d database] [-c compression] [-a file] [-o filename] \n\n" "-h\tShow list of parameters.\n\n" "-s\tSave indices to file: filename\n\n" "-l\tLoad indices from file: filename\n\n" "-d\tChoose test database.\n\n" "-i\tChoose individual index table\n\n" "-a\tAutomated loader: filename\n\n" "-o\tOutfile name\n\n" "[1]\tSemmedDB\n" "[2]\tPubmed (mesh only)\n" "[3]\tPubmed (mesh+supp)\n\n" "-c\tCompression type.\n\n" "[1]\tUA\n" "[2]\tBCA\n" "[3]\tBB\n" "[4]\tHuffman\n" "[5]\tOptimal compression\n\n"; while ((c = getopt(argc, argv, "hs:l:d:c:i:a:o:j")) != -1) { switch (c) { case 'h': cout << "\n\n" << help << "\n\n"; exit(0); break; case 's': action = 's'; if (optarg) { filename = optarg; } else { cout << "error: filename required!\n"; exit(0); } break; case 'l': action = 'l'; if (optarg) { filename = optarg; } else { cout << "error: filename required!\n"; exit(0); } break; case 'd': if (optarg) { database = atoi(optarg); } break; case 'c': if (optarg) { compression = atoi(optarg); } break; case 'i': if (optarg) { itable = atoi(optarg); action = 'i'; } break; case 'a': automate = 'y'; if (optarg) { auto_filename = optarg; } else { cout << "error: filename required!\n"; exit(0); } break; case 'o': if (optarg) { outfile_name = optarg; } else { cout << "error: filename required!\n"; exit(0); } break; case 'j': action = 'j'; } } if (automate == 'y') { load_index<uint32_t>(idx, filename); cout << "\n...Indices have been loaded...\n"; cout << "\n...Automated results will be sent to 'output.txt'\n"; automatic_tests(auto_filename, outfile_name); } else { switch(action) { case 'l': { load_index<uint32_t>(idx, filename); cout << "\n...Indices have been loaded...\n"; save_index<uint32_t>(idx, "temp.bin"); char testing = 'y'; while (testing == 'y') { string library_file; cout << "Please enter the name of the library file you are loading (don't include the .so extension; path is assumed to be current dir): \n"; cin >> library_file; string result_domain_string; cout << "Please specify the index ID for the result domain: \n"; cin >> result_domain_string; int result_domain = atoi(result_domain_string.c_str()); char result_data_type; cout << "Please specify one of these result data types: (d)ouble, (i)nt \n"; cin >> result_data_type; if (result_data_type == 'd') { handle_input<double>(library_file, result_domain); } else if (result_data_type == 'i') { handle_input<int>(library_file, result_domain); } cout << "\nLoad another file(y/n)?\n"; cin >> testing; } break; } case 's': { int result = load<int, uint32_t>(database, compression); if (result) { cout << "Indices loaded properly\n"; save_index<uint32_t>(idx, filename); } else { cerr << "Error: load function did not terminate normally\n\n"; } break; } case 'i': { load_individual_table<int, uint32_t>(itable, database, compression); break; } case 'j': { int result = 1; if (result == 0) { cout << "Server finished normally\n"; } else { cout << "Error on socket server call\n"; } break; } default: { int result = load<int, uint32_t>(database, compression); if (result) { cout << "\n...Indices have been loaded..."; char testing = 'y'; while (testing == 'y') { string library_file; cout << "Please enter the name of the library file you are loading (don't include the .so extension; path is assumed to be current dir): \n"; cin >> library_file; string result_domain_string; cout << "Please specify the index ID for the result domain: \n"; cin >> result_domain_string; int result_domain = atoi(result_domain_string.c_str()); char result_data_type; cout << "Please specify one of these result data types: (d)ouble, (i)nt \n"; cin >> result_data_type; cin >> result_data_type; if (result_data_type == 'd') { handle_input<double>(library_file, result_domain); } else if (result_data_type == 'i') { handle_input<int>(library_file, result_domain); } cout << "\nLoad another file(y/n)?\n"; cin >> testing; } } else { cerr << "Error: load function did not terminate normally\n\n"; } break; } } }
/* Bundle install one ore more bundles passed in bundles * param as a null terminated array of strings */ int install_bundles(char **bundles) { int lock_fd; int ret = 0; int current_version; struct manifest *mom; struct list *iter; struct sub *sub; struct file *file; /* step 1: initialize swupd and get current version from OS */ if (!init_globals()) { return EINIT_GLOBALS; } ret = swupd_init(&lock_fd); if (ret != 0) { printf("Failed updater initialization, exiting now.\n"); return ret; } current_version = read_version_from_subvol_file(path_prefix); swupd_curl_set_current_version(current_version); /* first of all, make sure STATE_DIR is there, recreate if necessary*/ ret = create_required_dirs(); if (ret != 0) { printf("State directory %s cannot be recreated, aborting installation\n", STATE_DIR); goto clean_and_exit; } ret = load_manifests(current_version, current_version, "MoM", NULL, &mom); if (ret != 0) { printf("Cannot load official manifest MoM for version %i\n", current_version); ret = EMOM_NOTFOUND; goto clean_and_exit; } /* step 2: check bundle args are valid if so populate subs struct */ int i; for (i = 0; *bundles; ++bundles) { if (is_tracked_bundle(*bundles)) { printf("%s bundle already installed, skipping it\n", *bundles); continue; } if (!manifest_has_component(mom, *bundles)) { printf("%s bundle name is invalid, skipping it...\n", *bundles); continue; } if (component_subscribed(*bundles)) { continue; } create_and_append_subscription(*bundles); i++; printf("Added bundle %s for installation\n", *bundles); } if (i == 0) { printf("There are no pending bundles to install, exiting now\n"); ret = EBUNDLE_INSTALL; goto clean_manifest_and_exit; } subscription_versions_from_MoM(mom, 0); recurse_manifest(mom, NULL); consolidate_submanifests(mom); /* step 3: download neccessary packs */ ret = rm_staging_dir_contents("download"); printf("Downloading required packs...\n"); ret = download_subscribed_packs(0, current_version, true); if (ret != 0) { printf("pack downloads failed, cannot proceed with the installation, exiting.\n"); goto clean_subs_and_exit; } /* step 4: Install all bundle(s) files into the fs */ printf("Installing bundle(s) files...\n"); iter = list_head(mom->files); while (iter) { file = iter->data; iter = iter->next; if (file->is_deleted || file->do_not_update || ignore(file)) { continue; } ret = do_staging(file); if (ret == 0) { rename_staged_file_to_final(file); } } sync(); /* step 5: create bundle(s) subscription entries to track them * * Strictly speaking each manifest has an entry to write its own bundle filename * and thus tracking automagically, here just making sure. */ iter = list_head(subs); while (iter) { sub = iter->data; iter = iter->next; printf("Tracking %s bundle on the system\n", sub->component); ret = track_bundle_in_system(sub->component); if (ret != 0) { printf("Cannot track %s bundle on the system\n", sub->component); } } /* Run any scripts that are needed to complete update */ run_scripts(); ret = 0; printf("Bundle(s) installation done.\n"); clean_subs_and_exit: free_subscriptions(); clean_manifest_and_exit: free_manifest(mom); clean_and_exit: swupd_curl_cleanup(); v_lockfile(lock_fd); dump_file_descriptor_leaks(); free_globals(); return ret; }
int main(int argc, char *argv[]) { void* itr_buf; void* otr_buf; Trace* itrace; Trace* otrace; rtf99 itr_rtf99, otr_rtf99; Shade5 itr_shade5, otr_shade5; Shade6x32 itr_shade6x32, otr_shade6x32; Shade6x64 itr_shade6x64, otr_shade6x64; Master itr_master, otr_master; RSTF_Union itr_rstf_union, otr_rstf_union; init_globals(argv); parse_args(argc, argv); // make input trace buffer itr_buf = calloc(BUFFER_SIZE, gbl.fromsize); if (itr_buf == NULL) { fprintf(stderr, "Could not allocate memory for itr_buf[] in main().\n"); exit(2); } // make output trace buffer, if conversion specified if (gbl.totype != NONE) { otr_buf = calloc(BUFFER_SIZE, gbl.tosize); if (otr_buf == NULL) { fprintf(stderr, "Could not allocate memory for otr_buf[] in main().\n"); exit(2); } } switch (gbl.fromtype) { case RTF99: itrace = &itr_rtf99; break; case SHADE5: itrace = &itr_shade5; break; case SHADE6x32: itrace = &itr_shade6x32; break; case SHADE6x64: itrace = &itr_shade6x64; break; case MASTER64: itrace = &itr_master; break; case RST: itrace = &itr_rstf_union; break; case NONE: usage(argv[0]); exit(1); default: fprintf(stderr, switch_error_string, "fromtype", "main()", gbl.fromtype); exit(2); } switch (gbl.totype) { case RTF99: otrace = &otr_rtf99; break; case SHADE5: otrace = &otr_shade5; break; case SHADE6x32: otrace = &otr_shade6x32; break; case SHADE6x64: otrace = &otr_shade6x64; break; case MASTER64: otrace = &otr_master; break; case RST: otrace = &otr_rstf_union; break; case NONE: otrace = NULL; break; default: fprintf(stderr, switch_error_string, "totype", "main()", gbl.totype); exit(2); } process_trace(itrace, otrace, itr_buf, otr_buf); return 0; } // main()
int main(int argc,char const **argv) { stor_t *d; char* name=malloc(128); int return_val=0; ipc_t ctx; fprintf(stderr,"-----------------\n"); fprintf(stderr,"simpleblocksd - v%s\n",VERSION_STRING); fprintf(stderr,"-----------------\n"); /* Setup program globals */ init_signals(); init_globals(); fprintf(stderr,"Parse args...\n"); parse_args(argc,(const char **)argv); /* Create IPC communication context */ fprintf(stderr,"Setup IPC...\n"); ipc_init(&ctx,"simpleblocksd"); /* Check to see if file exists */ // fprintf(stderr,"Create disk...\n"); // if(access(g.disk_dir,F_OK)==-1) // { // if(g.create==true) // { // // alocate_file(g.disk_dir,g.size); // } // else // { // fprintf(stderr,"File not found: %s\n",g.disk_dir); // fprintf(stderr,"-c --create flag not set.\n"); // return_val=1; // } // } // // d=load_disk_path(g.disk_dir,g.create); // if(d==NULL) // { // fprintf(stderr,"Can't open directory!\n"); // return_val=2; // } // errno=0; shmb_t *block=ctx.block; uint32_t sleep_ticks=kSLEEP_TICKS_DEFAULT; int result=0; #ifdef kATUOEXIT_TIME time_t start_t,end_t; time(&start_t); #endif fprintf(stderr,"-----------------\n"); fprintf(stderr,"Ready...\n"); while(!g.done) { errno=0; sched_yield(); #ifdef kATUOEXIT_TIME time(&end_t); g.done=!(difftime(end_t,start_t)<kATUOEXIT_TIME); #endif result=sem_trywait(ctx.block_sem); if(result==0) { if(ctx.block_epoc!=block->epoc) { if(block->head.type==eEmpty) { fprintf(stderr,"Empty header\n"); sleep_ticks=kSLEEP_TICKS_SLOW; } else if(block->head.type==eStatus) { sleep_ticks=kSLEEP_TICKS_DEFAULT; // fprintf(stderr,"block->type=%d\n",block->head.type); fprintf(stderr,"eStatus\n"); } else if(block->head.type==eDiskStatus) { sleep_ticks=kSLEEP_TICKS_DEFAULT; // fprintf(stderr,"block->type=%d\n",block->head.type); fprintf(stderr,"eDiskStatus\n"); } else if(block->head.type==eBlockRead) { sleep_ticks=kSLEEP_TICKS_DEFAULT; // fprintf(stderr,"block->type=%d\n",block->head.type); fprintf(stderr,"eBlockRead\n"); } else if(block->head.type==eBlockWrite) { sleep_ticks=kSLEEP_TICKS_DEFAULT; // fprintf(stderr,"block->type=%d\n",block->head.type); fprintf(stderr,"eBlockWrite\n"); } else if(block->head.type==eBlockStatus) { sleep_ticks=kSLEEP_TICKS_DEFAULT; // fprintf(stderr,"block->type=%d\n",block->head.type); fprintf(stderr,"eBlockStatus\n"); } else if(block->head.type==eAdmin) { // fprintf(stderr,"block->head.type = !valid\n"); fprintf(stderr,"eAdmin\n"); g.done=true; } else printf("Block epoc(%08x)-> Message type: %02x\n",ctx.block_epoc,block->head.type); ctx.block_epoc=block->epoc; } sem_post(ctx.block_sem); } else { fprintf(stderr,"result: %d Errno=%d \"%s\"\n",result,errno,strerror(errno)); sleep_ticks=kSLEEP_TICKS_SLOW; } usleep(sleep_ticks); } /* Cleanup */ fprintf(stderr,"\n"); fprintf(stderr,"Cleanup...\n"); fprintf(stderr,"Freeing cache...\n"); fprintf(stderr,"Closing disk...\n"); // stor_free(d); fprintf(stderr,"Closing IPC...\n"); ipc_destroy(&ctx); fprintf(stderr,"Exiting...\n"); free(name); return return_val; }
int dcmtoatr(FILE *fin, FILE *fout, const char *input, char *output ) { int archivetype; /* Block type for first block */ int blocktype; /* Current block type */ int tmp; /* Temporary for read without clobber on eof */ init_globals( fin, fout ); Aprint( "Converting %s to %s", input, output ); if( !fin || !fout ) { Aprint( "Programming error - NULL file specified for conversion" ); return 0; } archivetype = blocktype = fgetc(fin); if( archivetype == EOF ) { show_file_error( fin ); return 0; } switch(blocktype) { case 0xF9: case 0xFA: break; default: Aprint("0x%02X is not a known header block at start of input file",blocktype); return 0; } rewind(fin); while( 1 ) { if (feof(fin)) { fflush(stdout); /* Possible buffered I/O confusion fix */ if ((!last) && (blocktype == 0x45) && (archivetype == 0xF9)) { Aprint("Multi-part archive error."); Aprint("To process these files, you must first combine the files into a single file."); Aprint("COPY /B file1.dcm+file2.dcm+file3.dcm newfile.dcm from the DOS prompt"); } else { Aprint("EOF before end block, input file likely corrupt"); } return 0; } if (working) { if (soffset() != ftell(fout)) { Aprint("Output desyncronized, possibly corrupt dcm file. fin=%lu fout=%lu != %lu cursec=%u secsize=%u", ftell(fin),ftell(fout),soffset(),cursec,secsize); return 0; } } tmp = fgetc(fin); /* blocktype is needed on EOF error--don't corrupt it */ if( tmp == EOF ) { show_file_error( fin ); return 0; } blocktype = tmp; switch(blocktype) { case 0xF9: case 0xFA: /* New block */ if( decode_FA() == 0 ) return 0; break; case 0x45: /* End block */ working=0; if (last) return 1; /* Normal exit */ break; case 0x41: case 0xC1: if( decode_C1() == 0 ) return 0; break; case 0x43: case 0xC3: if( decode_C3() == 0 ) return 0; break; case 0x44: case 0xC4: if( decode_C4() == 0 ) return 0; break; case 0x46: case 0xC6: if( decode_C6() == 0 ) return 0; break; case 0x47: case 0xC7: if( decode_C7() == 0 ) return 0; break; default: Aprint("0x%02X is not a known block type. File may be corrupt.",blocktype); return 0; } /* end case */ if ((blocktype != 0x45) && (blocktype != 0xFA) && (blocktype != 0xF9)) { if (!(blocktype & 0x80)) { cursec=read_atari16(fin); if( fseek(fout, soffset(), SEEK_SET) != 0 ) { Aprint( "Failed a seek in output file, cannot continue" ); return 0; } } else { cursec++; if(cursec==4 && secsize!=128) fseek(fout,(secsize-128)*3,SEEK_CUR); } } } return 0; /* Should never be executed */ }