xptr_t st_write_split_state(struct st_tmp_trie * new_state) { struct state_descriptor dsc; struct st_page_header newpg; xptr_t parent_state = new_state->old_state; char * buf = new_state->buf2; size_t buflen = new_state->len2; int lower_edge = new_state->hint_edge; char * state = (char *) XADDR(parent_state); READ_PAGE(parent_state); state = read_state(state, &dsc); int n = dsc.edge_count; xptr_t * candidates = (xptr_t *) malloc(sizeof(xptr_t) * n); xptr_t c; xptr_t result; for (int i = 0; i < n; ++i) { struct state_descriptor tmp; read_state(state + dsc.pointers[i], &tmp); if ((tmp.flags & STATE_LONG_JUMP) > 0) { candidates[i] = tmp.long_jump; } else { candidates[i] = XNULL; } } c = select_candidate(candidates, n, buflen + sizeof(sptr_t)); //it's important to search candidate basing on full size of changes not only on string length. free(candidates); if (c == XNULL) { // U_ASSERT(false); st_markup_page(&newpg, 1, true); memcpy((char *) XADDR(newpg.page) + newpg.trie_offset, buf, buflen); newpg.data_end = newpg.trie_offset + buflen; st_write_page_header(&newpg); } else { c = GET_PAGE_ADDRESS(c); char * page_start = (char *) XADDR(c); st_read_page_header(c, &newpg); WRITE_PAGE(c); /* Add new trie to the end of the trie array */ newpg.trie_count++; memmove_ABd(page_start + newpg.trie_offset, page_start + newpg.data_end, sizeof(sptr_t)); newpg.tries[newpg.trie_count - 1] = newpg.data_end - newpg.trie_offset; newpg.data_end += sizeof(sptr_t); newpg.trie_offset += sizeof(sptr_t); memcpy(page_start + newpg.data_end, buf, buflen); newpg.data_end += buflen; st_write_page_header(&newpg); } result = newpg.page + newpg.trie_offset - sizeof(sptr_t); return result; }
// the loop routine runs over and over again forever: void loop() { //digitalClockDisplay(hour(), minute()); time_2 = millis(); last_st = key_state; read_state(); st = key_state; if (st != last_st) { process_state(); process_display(); time_1 = millis(); } else if (menu_state == Menu0_MainMenu) { process_display(); // If Menu0, update display event without key_State } time = time_2 - time_1; time = time / 1000; if (time >= 10) { turnOffDisplay(); resetKeyState(); //pinMode(LCDBacklight_pin, OUTPUT); //DisplayLCD_State = false; } else { turnOnDisplay(); //pinMode(LCDBacklight_pin, INPUT); //DisplayLCD_State = true; } Alarm.delay(90); // wait one second between clock display }
static int build_segments(char * source, sptr_t * pointers, char * buffer, struct trie_segment_t * segments, int n) { int total_length = 0; sptr_t len; char * c = buffer; struct state_descriptor dsc; for (int i = 0; i < n; i++) { sptr_t offset = pointers[i]; char * state = source + offset; read_state(state, &dsc); if ((dsc.flags & STATE_LONG_JUMP) > 0) { len = 0; segments[i].p = 0; segments[i].long_jump_pointer = dsc.long_jump; segments[i].valid_index = -1; } else { len = st_move_state_tree(c, state, 0); segments[i].p = (sptr_t) (c - buffer); segments[i].long_jump_pointer = XNULL; segments[i].valid_index = 0; } total_length += (segments[i].len = len); c += len; segments[i].parent_offset = 0; } U_ASSERT(total_length <= PAGE_SIZE); return total_length; }
/* uuid_create -- generator a UUID */ int uuid_create(uuid_t * uuid) { uuid_time_t timestamp, last_time; unsigned16 clockseq; uuid_node_t node; uuid_node_t last_node; int f; /* acquire system wide lock so we're alone */ LOCK; /* get current time */ get_current_time(×tamp); /* get node ID */ get_ieee_node_identifier(&node); /* get saved state from NV storage */ f = read_state(&clockseq, &last_time, &last_node); /* if no NV state, or if clock went backwards, or node ID changed (e.g., net card swap) change clockseq */ if (!f || memcmp(&node, &last_node, sizeof(uuid_node_t))) clockseq = true_random(); else if (timestamp < last_time) clockseq++; /* stuff fields into the UUID */ format_uuid_v1(uuid, clockseq, timestamp, node); /* save the state for next time */ write_state(clockseq, timestamp, node); UNLOCK; return(1); };
static sptr_t find_parent_state(struct st_path * path, xptr_t page, xptr_t * parent_state) { struct st_static_state_data * pp = NULL, * state = path->states; struct state_descriptor dsc; int count = path->state_count; *parent_state = XNULL; while (count > 0 && state->page->page != page) { pp = state; ++state; --count; } if (count > 0 && pp != NULL) { xptr_t parent_page = pp->p; READ_PAGE(pp->p); read_state((char *) XADDR(pp->p), &dsc); for (int i = 0; i < dsc.edge_count; i++) { char * state = dsc.p + dsc.len + dsc.pointers[i]; xptr_t * x = (xptr_t *) (state + 1); if ((((*(flags_t *) state) & STATE_LONG_JUMP) > 0) && SAME_PAGE(page, *x)) { *parent_state = parent_page + (state - (char *) XADDR(parent_page)); return pp->page->free_space; } } } return 0; }
int main(int argc, char* argv[]) { std::vector<std::string> args(argv, argv+argc); std::string url; size_t iterations = 1000; try { url = args.at(1); if (args.size() > 2) iterations = atoi(args.at(2).c_str()); } catch (std::exception& e) { std::cerr << "exception: " << e.what() << std::endl; std::cerr << "usage: " << args.at(0) << " url iterations" << std::endl; return 1; } curl_init(); CURL* curl = curl_easy_init(); if (!curl) { logError("curl_easy_init"); return 1; } setopt(curl, CURLOPT_URL, url.c_str()); setopt(curl, CURLOPT_TIMEOUT, 5L); setopt(curl, CURLOPT_CONNECTTIMEOUT, 5L); setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); setopt(curl, CURLOPT_HEADER, 1L); setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0); char send_data[] = "words, words, words"; for (size_t i = 0; i < iterations; i++) { ReadState read_state(send_data, strlen(send_data)); setopt(curl, CURLOPT_POST, 1L); setopt(curl, CURLOPT_READFUNCTION, read_callback); setopt(curl, CURLOPT_READDATA, &read_state); setopt(curl, CURLOPT_POSTFIELDSIZE, read_state.remains); bool sent = false; for (size_t i = 0; i < 3; i++) { if (perform(curl)) { std::cout << "^"; sent = true; break; } std::cout << "."; } if (!sent) { std::cout << "!"; } } curl_easy_cleanup(curl); curl_cleanup(); return 0; }
int main(void) { write_state(); read_state(); printf("\n"); printf("State properly reset, generated random numbers are correct\n\n"); exit(0); }
void test() { /* Matrix: * 0 1 0 * 0 | 0 * 1 & 1 * 0 1 0 */ printf("Test: Sblock Matrix\n"); write_lut(LUT_SELF, 0); write_lut(LUT_AND4, 1); write_lut(LUT_OR, 2); write_type(0,1,1, 2); write_type(0,2,1, 1); write_state(0,0,1, 1); write_state(0,2,0, 1); write_state(0,2,2, 1); write_state(0,3,1, 1); swap_cell_storage(); config(); step(1); readback(); swap_cell_storage(); read_state(0,0,1); read_state(0,1,1); read_state(0,2,1); read_state(0,3,1); step(1); readback(); swap_cell_storage(); read_state(0,0,1); read_state(0,1,1); read_state(0,2,1); read_state(0,3,1); assert_uint32(1, get_state()); assert_uint32(1, get_state()); assert_uint32(0, get_state()); assert_uint32(1, get_state()); assert_uint32(1, get_state()); assert_uint32(1, get_state()); assert_uint32(1, get_state()); assert_uint32(1, get_state()); }
update_state_t get_state(void) { update_state_t state; if (read_state((char *)STATE_KEY, &state) != SERVER_OK) { ERROR("Cannot read stored update state.\n"); return STATE_ERROR; } TRACE("Read state=%c from persistent storage.\n", state); return is_state_valid(state) ? state : STATE_ERROR; }
int main( int UNUSED( argc ), char ** UNUSED( argv ) ) { while(1) { state_t state; int rc = read_state( &state, 1 ); if( rc < 0 ) break; if( rc == 0 ) continue; printf( "%f %f %f " /* body accelerations */ "%f %f %f " /* body rotational rates */ "%f %f %f " /* NED positions */ "%f %f %f " /* NED euler angles */ "%f %f %f " /* NED velocities */ "%f %f " /* Rotor mass moments */ "\n", state.ax, state.ay, state.az, state.p, state.q, state.r, state.x, state.y, state.z, state.phi, state.theta, state.psi, state.vx, state.vy, state.vz, state.mx, state.my ); } return 0; }
static gboolean update_timeout(gpointer data) { GbbPowerMonitor *monitor = data; GbbPowerState state; read_state(monitor, &state); if (!gbb_power_state_equal(&monitor->current_state, &state)) { monitor->current_state = state; g_signal_emit(monitor, signals[CHANGED], 0); } return G_SOURCE_CONTINUE; }
GbbPowerMonitor * gbb_power_monitor_new(void) { GbbPowerMonitor *monitor = g_object_new(GBB_TYPE_POWER_MONITOR, NULL); GError *error = NULL; if (!find_power_supplies(monitor, NULL, &error)) g_error("%s\n", error->message); read_state(monitor, &monitor->current_state); monitor->update_timeout = g_timeout_add(UPDATE_FREQUENCY, update_timeout, monitor); return monitor; }
int main( int argc, char **argv ) { // VARIABLES FOR INPUT char str[ MAX_LINE_LENGTH +1 ] ; ssize_t nchars; state_t state; // state_t is defined by the PSVN API. It is the type used for individual states. // VARIABLES FOR ITERATING THROUGH state's SUCCESSORS state_t child; ruleid_iterator_t iter; // ruleid_terator_t is the type defined by the PSVN API successor/predecessor iterators. int ruleid ; // an iterator returns a number identifying a rule int childCount; // READ A LINE OF INPUT FROM stdin printf("Please enter a state followed by ENTER: "); if ( fgets(str, sizeof str, stdin) == NULL ) { printf("Error: empty input line.\n"); return 0; } // CONVERT THE STRING TO A STATE nchars = read_state( str, &state ); if (nchars <= 0) { printf("Error: invalid state entered.\n"); return 0; } printf("The state you entered is: "); print_state( stdout, &state ); printf("\n"); // LOOP THOUGH THE CHILDREN ONE BY ONE childCount = 0; init_fwd_iter( &iter, &state ); // initialize the child iterator while( ( ruleid = next_ruleid( &iter ) ) >= 0 ) { // while( -1 >= 0 ) { apply_fwd_rule( ruleid, &state, &child ); ++childCount; printf("child %d. ",childCount); print_state( stdout, &child ); //printf(" %s (cost %d)\n",get_fwd_rule_label(ruleid),get_fwd_rule_cost(ruleid)); printf(" %s (cost %d), goal=%d\n",get_fwd_rule_label(ruleid),get_fwd_rule_cost(ruleid),is_goal(&child)); } // end while... no more children if (childCount == 0) { printf("Your state has no children.\n"); } return 0; } // end main
void resetAll() { if (LOG) printf(" starting reset\n"); currentGeneration = 0; write_state(sta_file_selector, 10); write_state(sta_file_variator, 8); if (LOG) printf(" variator, selector states 8, 10\n"); while(1){ if (read_state(sta_file_variator) != 9) { write_state(sta_file_variator, 8); }; if (read_state(sta_file_selector) != 11) { write_state(sta_file_selector, 10); }; if (read_state(sta_file_variator) == 9 && read_state(sta_file_selector) == 11) { updateVariatorSeed(); write_state(ini_file_variator,0); // make ini file ready for writing write_state(sta_file_variator, 0); if (LOG) printf(" variator state 0\n"); if (LOG) printf(" currentGeneration = %d \n",currentGeneration); break; }; wait(poll); } while(1) { if (read_state(sta_file_variator) == 1) { copyInitialPop(); write_state(arc_file_selector,0); // make arc file ready for write write_state(sel_file_selector,0); // make sel file ready for write write_state(sta_file_selector, 1); if (LOG) printf(" ini_pop done; selector state 1\n"); break; }; wait(poll); } while(1) { if (read_state(sta_file_selector) == 2) { copyArchiveSelected(); appendOutput(); write_state(var_file_variator,0); // make var file ready for write write_state(sta_file_variator, 2); if (LOG) printf(" selection done; variator state 2\n"); break; }; wait(poll); } return; }
/** Returns the linear size of the state at <p> */ inline static sptr_t st_get_local_state_length(const char * p, bool include_subtree) { size_t size; struct state_descriptor dsc; p = read_state(p, &dsc); size = dsc.len; if (((dsc.flags & STATE_LONG_JUMP) == 0) && include_subtree && (dsc.edge_count > 0)) { sptr_t max_ptr = dsc.pointers[0]; for (int i = 0; i < dsc.edge_count; i++) { if (max_ptr < dsc.pointers[i]) { max_ptr = dsc.pointers[i]; } } size += max_ptr + st_get_local_state_length(p + max_ptr, true); } return size; }
static char * st_fix_parent_pointers(xptr_t parent_state, xptr_t split_page, char * trie_array_base) { struct st_page_header ph; struct state_descriptor dsc; st_read_page_header(parent_state, &ph); char * base = (char*) XADDR(ph.page) + ph.trie_offset; char * state = base; char * next_state; char * end = (char*) XADDR(ph.page) + ph.data_end; while (state < end) { next_state = read_state(state, &dsc); if ((dsc.long_jump != XNULL) && (GET_PAGE_ADDRESS(dsc.long_jump) == split_page)) { tries[((char *) XADDR(dsc.long_jump) - trie_array_base) / sizeof(sptr_t)].parent_offset = state - base; } state = next_state; } return base; }
int main() { logfile.open("ai++.log", std::ios_base::out | std::ios_base::trunc); if (!logfile.is_open()) { std::cerr << "ai: cannot open log. terminating." << std::endl; return 1; } RawBoard board; uint8_t state; AI ai; while (true) { read_board(std::cin, board); read_state(std::cin, state); AnalyzeResult result = ai.actuate(board); if (std::get<1>(result)) { std::cout << (uint8_t)std::get<0>(result) << std::flush; } else { std::cerr << "ai: no further options. terminating." << std::endl; return 0; } } }
void Nes_Mapper::load_state( mapper_state_t const& in ) { default_reset_state(); read_state( in ); apply_mapping(); }
int main(int argc, char *argv[]) { fcs_dbm_variant_type_t local_variant = FCS_DBM_VARIANT_2FC_FREECELL; const long delta_limit = 100000; const int max_num_elements_in_cache = 8000000; const char *filename = argv[1]; FILE *const fh = fopen(filename, "r"); if (fh == NULL) { fc_solve_err("Could not open file '%s' for input.\n", filename); } const fcs_user_state_str_t user_state = read_state(fh); fcs_state_keyval_pair_t init_state_pair; fc_solve_initial_user_state_to_c( user_state.s, &init_state_pair, FREECELLS_NUM, STACKS_NUM, 1, NULL); fcs_dbm_solver_instance_t instance; instance_init( &instance, local_variant, &init_state_pair, max_num_elements_in_cache); #define LOG_FILENAME "fc-solve-pseudo-dfs.log.txt" { FILE *const last_line_fh = popen(("tail -1 " LOG_FILENAME), "r"); if (last_line_fh) { long count_num_processed; if (fscanf(last_line_fh, "At %ld iterations Coords=[", &count_num_processed) == 1) { instance__load_coords_from_fh(&instance, last_line_fh); /* * instance__inspect_new_state increments count_num_processed * so let's set it after loading the coordinates. * */ instance.count_num_processed = count_num_processed; } } pclose(last_line_fh); } instance.max_count_num_processed = instance.count_num_processed + delta_limit; while (instance.max_count_num_processed % delta_limit != 0) { instance.max_count_num_processed += delta_limit - (instance.max_count_num_processed % delta_limit); } while (instance.should_terminate == DONT_TERMINATE) { instance_run(&instance); FILE *const log_fh = fopen(LOG_FILENAME, "at"); instance__print_coords_to_log(&instance, log_fh); fclose(log_fh); instance.max_count_num_processed = instance.count_num_processed + delta_limit; } if (instance.should_terminate == SOLUTION_FOUND_TERMINATE) { printf("%s\n", "Solution was found."); } else { printf("%s\n", "I could not solve it."); } instance_free(&instance); return 0; }
int main(int argc, char **argv) { // time the program struct timeval sysTimeStart, sysTimeEnd; gettimeofday(&sysTimeStart, NULL); mkdir("bplus", 0777); int i; // open file count information file_count_t *fc = read_file_count(); // keep track of roots bplus_roots_t bpr; // users { printf("\n"); printf("Making user B+ tree with %d users\n", fc->users); // time this section struct timeval startSysTimeSub, endSysTimeSub; gettimeofday(&startSysTimeSub, NULL); // create root int_node_t root; root.next = -1; root.previous = -1; root.tableType = TABLE_TYPE_USER; root.nodeType = NODE_TYPE_LEAF; root.count = 0; root.firstFile = -1; write_node(0, &root); int rootFileNum = 0; for (i = 0; i < fc->users; i++) { user_t *user = read_user(i); rootFileNum = insert_node(rootFileNum, TABLE_TYPE_USER, user->stateId, i); free_user(user); } bpr.user = rootFileNum; // end timing this section gettimeofday(&endSysTimeSub, NULL); float totalTime = (endSysTimeSub.tv_sec - startSysTimeSub.tv_sec) + (endSysTimeSub.tv_usec - startSysTimeSub.tv_usec) / 1000000.0f; printf("B+ tree creation time: %f seconds\n", totalTime); } // cities { printf("\n"); printf("Making city B+ tree with %d cities\n", fc->cities); // time this section struct timeval startSysTimeSub, endSysTimeSub; gettimeofday(&startSysTimeSub, NULL); // create root int_node_t root; root.next = -1; root.previous = -1; root.tableType = TABLE_TYPE_CITY; root.nodeType = NODE_TYPE_LEAF; root.count = 0; root.firstFile = -1; write_node(0, &root); int rootFileNum = 0; for (i = 0; i < fc->cities; i++) { city_t *city = read_city(i); rootFileNum = insert_node(rootFileNum, TABLE_TYPE_CITY, city->stateId, i); free_city(city); } bpr.city = rootFileNum; // end timing this section gettimeofday(&endSysTimeSub, NULL); float totalTime = (endSysTimeSub.tv_sec - startSysTimeSub.tv_sec) + (endSysTimeSub.tv_usec - startSysTimeSub.tv_usec) / 1000000.0f; printf("B+ tree creation time: %f seconds\n", totalTime); } //states { printf("\n"); printf("Making state B+ tree with %d states\n", fc->states); // time this section struct timeval startSysTimeSub, endSysTimeSub; gettimeofday(&startSysTimeSub, NULL); // create root int_node_t root; root.next = -1; root.previous = -1; root.tableType = TABLE_TYPE_STATE; root.nodeType = NODE_TYPE_LEAF; root.count = 0; root.firstFile = -1; write_node(0, &root); int rootFileNum = 0; for (i = 0; i < fc->states; i++) { state_t *state = read_state(i); rootFileNum = insert_node(rootFileNum, TABLE_TYPE_STATE, (int) hash_state(state), i); free_state(state); } bpr.state = rootFileNum; // end timing this section gettimeofday(&endSysTimeSub, NULL); float totalTime = (endSysTimeSub.tv_sec - startSysTimeSub.tv_sec) + (endSysTimeSub.tv_usec - startSysTimeSub.tv_usec) / 1000000.0f; printf("B+ tree creation time: %f seconds\n", totalTime); } // messages { printf("\n"); printf("Making message B+ tree with %d messages\n", fc->messages); // time this section struct timeval startSysTimeSub, endSysTimeSub; gettimeofday(&startSysTimeSub, NULL); // create root int_node_t root; root.next = -1; root.previous = -1; root.tableType = TABLE_TYPE_MESSAGE; root.nodeType = NODE_TYPE_LEAF; root.count = 0; root.firstFile = -1; write_node(0, &root); int rootFileNum = 0; for (i = 0; i < fc->messages; i++) { message_t *message = read_message(i); rootFileNum = insert_node(rootFileNum, TABLE_TYPE_MESSAGE, message->timestampId, i); free_message(message); } bpr.message = rootFileNum; // end timing this section gettimeofday(&endSysTimeSub, NULL); float totalTime = (endSysTimeSub.tv_sec - startSysTimeSub.tv_sec) + (endSysTimeSub.tv_usec - startSysTimeSub.tv_usec) / 1000000.0f; printf("B+ tree creation time: %f seconds\n", totalTime); } // timestamps { printf("\n"); printf("Making timestamp B+ tree with %d timestamps\n", fc->timestamps); // time this section struct timeval startSysTimeSub, endSysTimeSub; gettimeofday(&startSysTimeSub, NULL); // create root int_node_t root; root.next = -1; root.previous = -1; root.tableType = TABLE_TYPE_TIMESTAMP; root.nodeType = NODE_TYPE_LEAF; root.count = 0; root.firstFile = -1; write_node(0, &root); int rootFileNum = 0; for (i = 0; i < fc->timestamps; i++) { timestamp_t *timestamp = read_timestamp(i); rootFileNum = insert_node(rootFileNum, TABLE_TYPE_TIMESTAMP, (int) hash_timestamp(timestamp), i); free_timestamp(timestamp); } bpr.timestamp = rootFileNum; // end timing this section gettimeofday(&endSysTimeSub, NULL); float totalTime = (endSysTimeSub.tv_sec - startSysTimeSub.tv_sec) + (endSysTimeSub.tv_usec - startSysTimeSub.tv_usec) / 1000000.0f; printf("B+ tree creation time: %f seconds\n", totalTime); } // datestamps { printf("\n"); printf("Making datestamp B+ tree with %d datestamps\n", fc->datestamps); // time this section struct timeval startSysTimeSub, endSysTimeSub; gettimeofday(&startSysTimeSub, NULL); // create root int_node_t root; root.next = -1; root.previous = -1; root.tableType = TABLE_TYPE_DATESTAMP; root.nodeType = NODE_TYPE_LEAF; root.count = 0; root.firstFile = -1; write_node(0, &root); int rootFileNum = 0; for (i = 0; i < fc->datestamps; i++) { datestamp_t *datestamp = read_datestamp(i); rootFileNum = insert_node(rootFileNum, TABLE_TYPE_DATESTAMP, (int) hash_datestamp(datestamp), i); free_datestamp(datestamp); } bpr.datestamp = rootFileNum; // end timing this section gettimeofday(&endSysTimeSub, NULL); float totalTime = (endSysTimeSub.tv_sec - startSysTimeSub.tv_sec) + (endSysTimeSub.tv_usec - startSysTimeSub.tv_usec) / 1000000.0f; printf("B+ tree creation time: %f seconds\n", totalTime); } free_file_count(fc); printf("\n"); print_bplus_roots(&bpr); write_bplus_roots(&bpr); // end timing the program gettimeofday(&sysTimeEnd, NULL); float totalTime = (sysTimeEnd.tv_sec - sysTimeStart.tv_sec) + (sysTimeEnd.tv_usec - sysTimeStart.tv_usec) / 1000000.0f; printf("Process time %f seconds\n", totalTime); return 0; }
static xptr_t st_split_promote_root(struct st_page_header * root_page_hdr, int parent_free_space, xptr_t parent_position, int cpage) { struct state_descriptor dsc; xptr_t rtp = XNULL, ltp = XNULL; int total_length; int break_point; int n; int root_length; READ_PAGE(root_page_hdr->page); read_state(get_root_state(root_page_hdr), &dsc); n = dsc.edge_count; total_length = build_segments(dsc.p + dsc.len, dsc.pointers, source, tries, n); for (int i = 0; i < n; i++) { tries[i].id = i; } root_length = dsc.len + n * (sizeof(xptr_t) + sizeof(flags_t)); if (root_length <= parent_free_space) { char * buf = root_buffer; struct st_tmp_trie trie = {}; struct st_page_header * pghdr = root_page_hdr; memcpy(buf, dsc.p, dsc.len); ltp = root_page_hdr->page; st_read_page_header(GET_PAGE_ADDRESS(parent_position), pghdr); trie.state = (char *) XADDR(parent_position) - (char *) XADDR(pghdr->page) - pghdr->trie_offset; trie.state_len = sizeof(xptr_t) + sizeof(flags_t); trie.buf = buf; trie.len = root_length; trie.buf2 = NULL; st_new_state_write(pghdr, &trie); READ_PAGE(parent_position); read_state((char *) XADDR(parent_position), &dsc); } else { // TODO: PROMOTE ROOT! U_ASSERT(cpage==0); parent_position = root_page_hdr->page; root_page_hdr->data_end = root_page_hdr->trie_offset + root_length; } break_point = write_segments(tries, n, total_length, <p, &rtp, source); WRITE_PAGE(root_page_hdr->page); (* (flags_t *) dsc.p) |= STATE_SPLIT_POINT; for (int i = 0; i < n; i++) { dsc.pointers[tries[i].id] = i * (sizeof(xptr_t) + sizeof(flags_t)); } write_jump_list(&dsc, tries, ltp, 0, break_point); if (rtp != XNULL) { write_jump_list(&dsc, tries, rtp, break_point, n); } st_write_page_header(root_page_hdr); return ltp; }
int main(int argc, char *argv[]) { int current_state = 0; int monitor_state = 1; /* polling variator (0) or selector (1) */ int variator_terminated = 0; int selector_terminated = 0; if (argc == 8) { sscanf(argv[1], "%s", parnamebase_variator); sscanf(argv[2], "%s", filenamebase_variator); sscanf(argv[3], "%s", parnamebase_selector); sscanf(argv[4], "%s", filenamebase_selector); sscanf(argv[5], "%s", parnamebase_monitor); sscanf(argv[6], "%s", filenamebase_monitor); sscanf(argv[7], "%lf", &poll); assert(poll >= 0); } else { printf("Monitor - wrong number of arguments:\n"); printf("monitor varPar varBase selPar selBase monPar monBase poll\n"); return (1); } /* generate file names based on 'filenamebase'*/ sprintf(var_file_variator, "%svar", filenamebase_variator); sprintf(sel_file_variator, "%ssel", filenamebase_variator); sprintf(cfg_file_variator, "%scfg", filenamebase_variator); sprintf(ini_file_variator, "%sini", filenamebase_variator); sprintf(arc_file_variator, "%sarc", filenamebase_variator); sprintf(sta_file_variator, "%ssta", filenamebase_variator); sprintf(var_file_selector, "%svar", filenamebase_selector); sprintf(sel_file_selector, "%ssel", filenamebase_selector); sprintf(cfg_file_selector, "%scfg", filenamebase_selector); sprintf(ini_file_selector, "%sini", filenamebase_selector); sprintf(arc_file_selector, "%sarc", filenamebase_selector); sprintf(sta_file_selector, "%ssta", filenamebase_selector); /* initialize common parameters */ alpha = 0; mu = 0; lambda = 0; dimension = 0; /* read and check common parameters (they should be equal)*/ read_common_parameters(cfg_file_variator); read_common_parameters(cfg_file_selector); /* read monitor parameters */ read_local_parameters(); /* seed random generator */ srand(seed); /* print information file of monitor */ printInformation(); for (currentRun = 0 ; currentRun < numberOfRuns; currentRun++ ) { if (LOG) printf("currentRun = %d \n",currentRun); resetAll(); for (currentGeneration = 1 ; currentGeneration <= numberOfGenerations; currentGeneration++ ) { if (LOG) printf(" currentGeneration = %d \n",currentGeneration); while(1) { if (read_state(sta_file_variator) == 3) { copyVariate(); write_state(sta_file_selector,3); if (LOG) printf(" variation done; selector state 3\n"); break; } wait(poll); } while(1) { if (read_state(sta_file_selector) == 2) { copyArchiveSelected(); appendOutput(); write_state(sta_file_variator, 2); if (LOG) printf(" selection done; variator state 2\n"); break; }; wait(poll); } } } if (LOG) printf("selector state 6 (kill)\n"); write_state(sta_file_selector, 6); while(1) { if (read_state(sta_file_selector) == 7) { if (LOG) printf("selector killed\n"); break; } wait(poll); } while(1) { if (read_state(sta_file_variator) == 3) { if (LOG) printf("variator state 4 (kill)\n"); write_state(sta_file_variator, 4); break; } wait(poll); } while(1) { if (read_state(sta_file_variator) == 5) { if (LOG) printf("variator killed\n"); break; } wait(poll); } if (LOG) printf("kill myself\n"); return (0); }
int main(int argc, char *argv[]) { char map[20],path1[30],path2[30]; int dir; int i,j; int ghost_p1[4][2],pacman1_x,pacman1_y,ghost_p2[4][2],pacman2_x,pacman2_y; FILE *fp; if(argc!=4) { printf("\nUsage: <executable> <map> <bot1> <bot2>"); exit(1); } strcpy(map,argv[1]); strcpy(bot1,argv[2]); strcpy(bot2,argv[3]); printf("\n%s Vs %s\n",bot1,bot2); read_state(map); //map_state1 /* printf("\nmapstate1\n"); for (i=0;i<map_row;i++) { for(j=0;j<map_col;j++) { printf("%c ",map_state1[i][j]); } printf("\n"); }*/ /*create directories for each bot*/ mkdir(bot1,0777); mkdir(bot2,0777); write_state_file(); get_current_positions(ghost_p1, &pacman1_x,&pacman1_y,ghost_p2, &pacman2_x,&pacman2_y); /*store initial ghost positions*/ for(i=0;i<4;i++) { init_ghost_p1[i][0]=ghost_p1[i][0]; init_ghost_p2[i][0]=ghost_p2[i][0]; } write_trace(ghost_p1,pacman1_x,pacman1_y,ghost_p2,pacman2_x,pacman2_y,0,0); compile_bot(); //compile bots //execute 10*w*h times for(i=0;i<10*map_col*3;i++) { //printf("%d ",i); system("./aa_bot"); system("./bb_bot"); change_state(ghost_p1,pacman1_x,pacman1_y,ghost_p2, pacman2_x,pacman2_y);//to change the state according to move.txt in bot folders write_state_file(); get_current_positions(ghost_p1, &pacman1_x,&pacman1_y,ghost_p2, &pacman2_x,&pacman2_y); write_trace(ghost_p1,pacman1_x,pacman1_y,ghost_p2,pacman2_x,pacman2_y,score1,score2); } }
/** * The function passed to created threads. * * NOTE: is_empty(queue) is called a lot: It should be noted that we * must make sure it's only called when we have the queue lock! * * 1. Lock the task queue. We're using a condition lock, so we'll * give up the lock until there is a task to run OR the tpDestroy * function sent a broadcast to all threads that they should clean * up. * 2. Wait for the signal (task inserted, or tp being destroyed). * 3. Now that the queue is locked, check the destruction state. This * state should be valid because a. the change from ALIVE to * something else is a one-way change, b. even if the following * happened: * - Task added * - Thread got out of the WHILE loop * - CONTEXT SWITCH * - Main thread (pool creator) called tp_destroy, state changed * - CONTEXT SWITCH * - Back to our thread, got to the switch() statement and found * out we're dying * This is the desired behaviour (Piazza @281) - we do not need to * make sure tasks added before calls to tpDestroy will be executed * if tpDestroy is called in DO_RUN mode, even if all threads were * available when the task was added. * 4. If we're ALIVE, that means pool->queue IS NOT EMPTY (otherwise we * would still be in the while loop, because you can't change DO_RUN * or DO_ALL back to ALIVE so there's no danger we left the while() * loop because of state!=ALIVE but got to state==ALIVE in the * switch), so we can just dequeue a task and run it (remember to * unlock before running!). * 5. If we're DO_ALL, it's like ALIVE but first check if there's * something to run (unlike the ALIVE state, we don't know for sure). * If there is, run it; otherwise, exit (no more tasks will come). * 6. If we're DO_RUN, exit. Don't take another task, leave them to rot. * 7. Rinse and repeat */ void* thread_func(void* void_tp) { int pid = TID(); // Some useful variables State state; Task* t; ThreadPool* tp = (ThreadPool*)void_tp; #if HW3_DEBUG // Initialize tp->tids pthread_t self = pthread_self(); int thread_i; for (thread_i=0; thread_i<tp->N; ++thread_i) if (pthread_equal(tp->threads[thread_i],self)) { tp->tids[thread_i]=pid; break; } #endif PRINT("Thread %d started it's function\n",pid); // Main thread task while(1) { // Get the initial state and the task lock, when we need it (task to do or we're dying) // IMPORTANT: LOCK THE TASK LOCK BEFORE READING THE STATE! // Otherwise, we can see this situation: // - T1 reads the state, it's ALIVE // - CS-->main thread // - Main thread calls tpDestroy // - Main thread broadcasts, starts waiting for all threads // - CS-->T1 // - T1 locks the task lock (remember: state==ALIVE) // - The task queue is empty and state==ALIVE so T1 will wait for a signal that will never come. // Hence, DO NOT do this: // 1. state = read_state(tp); // 2. pthread_mutex_lock(&tp->task_lock); // But do it the other way round: pthread_mutex_lock(&tp->task_lock); // This is OK because during INIT, we don't lock the task queue (after its creation) state = read_state(tp); PRINT("Thread %d locked the task queue\n",pid); while (osIsQueueEmpty(tp->tasks) && state == ALIVE) { // Wait for a task OR the destruction of the pool PRINT("Thread %d started waiting for a signal\n",pid); pthread_cond_wait(&tp->queue_not_empty_or_dying,&tp->task_lock); // Either one gives a signal state = read_state(tp); PRINT("Thread %d got the signal and locked the lock\n",pid); } PRINT("Thread %d got out of the while() loop, state==%s\n",pid,state_string(read_state(tp))); switch(state) { case ALIVE: // If we're not dying, take a task and do it. t = (Task*)osDequeue(tp->tasks); pthread_mutex_unlock(&tp->task_lock); PRINT("Thread %d doing it's task\n",pid); t->func(t->param); free(t); break; case DO_ALL: // If we're dying, but we should clean up the queue: if (!osIsQueueEmpty(tp->tasks)) { // THIS TEST IS NOT USELESS! We may have got here t = (Task*)osDequeue(tp->tasks); // via a broadcast() call from tp_destroy and the pthread_mutex_unlock(&tp->task_lock); // state may be DO_ALL but is_empty() may be true... PRINT("Thread %d doing it's task\n",pid); // Thus, the while() loop terminated and we got here. t->func(t->param); free(t); } else { // If we're here, there are no more tasks to dequeue! pthread_mutex_unlock(&tp->task_lock); // As we're being destroyed anyway, exit. PRINT("Thread %d unlocked the lock and returning\n",pid); return NULL; } break; case DO_RUN: // If we're dying and no more tasks should be done, pthread_mutex_unlock(&tp->task_lock); // just exit before dequeuing anything... PRINT("Thread %d unlocked the lock and returning\n",pid); return NULL; break; } } }
void gb_restore_state(FILE * fd, const byte *buf) { const int tbl_ram[]={1,1,1,4,16,8}; // 0と1は保険 const int has_bat[]={0,0,0,1,0,0,1,0,0,1,0,0,1,1,0,1,1,0,0,1,0,0,0,0,0,0,0,1,0,1,1,0}; // 0x20以下 int gb_type,dmy; read_state(fd, &gb_type, sizeof(int)); rom_get_info()->gb_type=gb_type; if (gb_type<=2){ read_state(fd, cpu_get_ram(),0x2000); // ram read_state(fd, cpu_get_vram(),0x2000); // vram read_state(fd, get_sram(),tbl_ram[rom_get_info()->ram_size]*0x2000); // sram read_state(fd, cpu_get_oam(),0xA0); read_state(fd, cpu_get_stack(),0x80); int page,ram_page; read_state(fd, &page, sizeof(int)); // rom_page read_state(fd, &ram_page, sizeof(int)); // ram_page mbc_set_page(page,ram_page); read_state(fd, cpu_get_c_regs(),sizeof(struct cpu_regs)); // cpu_reg cpu_set_c_regs(); read_state(fd, (void *)&g_regs,sizeof(struct gb_regs)); // sys_reg int halt; read_state(fd, &halt,sizeof(int)); *cpu_get_halt()=((halt)?true:false); read_state(fd, &dmy,sizeof(int)); int mbc_dat; read_state(fd, &mbc_dat,sizeof(int)); // MBC mbc_set_state(mbc_dat); int ext_is; read_state(fd, &ext_is,sizeof(int)); mbc_set_ext_is(ext_is?true:false); // ver 1.1 追加 byte tmp[256],tester[100]; // read_state(fd, tmp, 100); // とりあえず調べてみる // _memset(tester,0,100); // if (_memcmp(tmp,tester,100)!=0){ // apu 部分 // sceIoLseek(fd, -100, 1); read_state(fd, apu_get_stat_cpu(),sizeof(struct apu_stat)); read_state(fd, apu_get_mem(),0x30); read_state(fd, apu_get_stat_gen(),sizeof(struct apu_stat)); // } byte resurved[256]; read_state(fd, resurved, 256);//将来のために確保 // RIN拡張 if(gb_type==2 && sgb_mode){ int dmy; read_state(fd, &dmy, sizeof(int)); read_state(fd, &bit_received, sizeof(int)); read_state(fd, &bits_received, sizeof(int)); read_state(fd, &packets_received, sizeof(int)); read_state(fd, &sgb_state, sizeof(int)); read_state(fd, &sgb_index, sizeof(int)); read_state(fd, &sgb_multiplayer, sizeof(int)); read_state(fd, &sgb_fourplayers, sizeof(int)); read_state(fd, &sgb_nextcontrol, sizeof(int)); read_state(fd, &sgb_readingcontrol, sizeof(int)); read_state(fd, &sgb_mask, sizeof(int)); read_state(fd, sgb_palette, sizeof(unsigned short)*8*16); read_state(fd, sgb_palette_memory, sizeof(unsigned short)*512*4); read_state(fd, sgb_buffer, 7*16); read_state(fd, sgb_ATF, 18*20); read_state(fd, sgb_ATF_list, 45*20*18); /* read_state(fd, sgb_border, 2048); read_state(fd, sgb_borderchar, 32*256); read_state(fd, border_tmp, sizeof(border_tmp)); int i, j, n=0; for (i=0; i<224; i++){ for (j=0; j<256; j++){ if (i>=40 && i<=183 && j==48) j=208; sgb_border_buffer[i*256+j] = border_tmp[n++]; } } */ } } else if (gb_type>=3){ // GB Colour / GBA read_state(fd, cpu_get_ram(),0x2000*4); // ram read_state(fd, cpu_get_vram(),0x2000*2); // vram read_state(fd, get_sram(),tbl_ram[rom_get_info()->ram_size]*0x2000); // sram read_state(fd, cpu_get_oam(),0xA0); read_state(fd, cpu_get_stack(),0x80); int cpu_dat[16]; int page,ram_page; read_state(fd, &page, sizeof(int)); // rom_page read_state(fd, &ram_page, sizeof(int)); // ram_page mbc_set_page(page,ram_page); page=(mbc_get_rom()-get_rom())/0x4000; ram_page=(mbc_get_sram()-get_sram())/0x2000; read_state(fd, cpu_dat+0,sizeof(int));//int_page read_state(fd, cpu_dat+1,sizeof(int));//vram_page int dmy; read_state(fd, cpu_get_c_regs(),sizeof(struct cpu_regs)); // cpu_reg cpu_set_c_regs(); read_state(fd, &g_regs,sizeof(struct gb_regs));//sys_reg read_state(fd, &cg_regs,sizeof(struct gbc_regs));//col_reg read_state(fd, lcd_get_pal_addr(),sizeof(word)*(8*4*2));//palette int halt; read_state(fd, &halt,sizeof(int)); *cpu_get_halt()=(halt?true:false); read_state(fd, &dmy,sizeof(int)); // 元の版ではシリアル通信通信満了までのクロック数 int mbc_dat; read_state(fd, &mbc_dat,sizeof(int)); // MBC mbc_set_state(mbc_dat); int ext_is; read_state(fd, &ext_is,sizeof(int)); mbc_set_ext_is(ext_is?true:false); //その他諸々 read_state(fd, cpu_dat+2,sizeof(int)); read_state(fd, cpu_dat+3,sizeof(int)); read_state(fd, cpu_dat+4,sizeof(int)); read_state(fd, cpu_dat+5,sizeof(int)); read_state(fd, cpu_dat+6,sizeof(int)); read_state(fd, cpu_dat+7,sizeof(int)); cpu_restore_state(cpu_dat); // ver 1.1 追加 byte tmp[256],tester[100]; read_state(fd, apu_get_stat_cpu(),sizeof(struct apu_stat)); read_state(fd, apu_get_mem(),0x30); read_state(fd, apu_get_stat_gen(),sizeof(struct apu_stat)); read_state(fd, tmp,1); // } byte resurved[256]; read_state(fd, resurved,256);//将来のために確保 } cheat_create_cheat_map(); }
int main( int argc, char **argv ) { // VARIABLES FOR INPUT char str[ MAX_LINE_LENGTH +1 ] ; ssize_t nchars; state_t state; // state_t is defined by the PSVN API. It is the type used for individual states. PriorityQueue<state_t> open; //state_map_t *map = new_state_map();//****** // VARIABLES FOR ITERATING THROUGH state's SUCCESSORS state_t child; ruleid_iterator_t iter; // ruleid_terator_t is the type defined by the PSVN API successor/predecessor iterators. int ruleid ; // an iterator returns a number identifying a rule int64_t totalNodes; // READ A LINE OF INPUT FROM stdin printf("Please enter a state followed by ENTER: "); if ( fgets(str, sizeof str, stdin) == NULL ) { printf("Error: empty input line.\n"); return 0; } // CONVERT THE STRING TO A STATE nchars = read_state( str, &state ); if (nchars <= 0) { printf("Error: invalid state entered.\n"); return 0; } printf("The state you entered is: "); print_state( stdout, &state ); printf("\n"); List StateList = List(); // state_map_add( map, &state, 0 );//******dont know if its a must open.Add(0,0,state); StateList.add(&state); StateList.change_color(&state,1);// Gray // StateList.change_distance(&state,0); totalNodes = 0; int d = 0; /* Search */ while ( !open.Empty() ) { // g.n d = open.CurrentPriority(); printf("D: %d\n",d); state = open.Top(); open.Pop(); totalNodes++; /* DDD */ if (StateList.get_color(&state)==0 || (StateList.get_distance(&state)>(d-1))){ StateList.change_distance(&state,d); if (is_goal(&state)==1){ //PRINT STUFF printf("Estado: "); print_state( stdout, &state); printf(" Estados Generados: %"PRId64" , costo: %d",totalNodes,StateList.get_distance(&state)); return 1;//SUCCES } /* expand node */ init_fwd_iter(&iter, &state); while((ruleid = next_ruleid(&iter)) >= 0){ apply_fwd_rule(ruleid,&state,&child);//'child' is a succesor state_t of 'state' StateList.add(&child); StateList.change_color(&child, 1);//Gray const int child_d = d + get_fwd_rule_cost(ruleid); StateList.change_distance( &child , child_d ); open.Add( child_d , child_d , child ); } StateList.change_color(&state,2); //Black } } printf("FAIL!"); return 2; //FAIL }
int main(int argc, char **argv) { // time the program struct timeval sysTimeStart, sysTimeEnd; gettimeofday(&sysTimeStart, NULL); // counters, etc. int first, mid, last, i, nebraskaUserCount = 0, nebraskaStateId; char nebraskaStr[] = "Nebraska"; // get file counts file_count_t *fc = read_file_count(); int userCount = fc->users; int stateCount = fc->states; free_file_count(fc); // binary search states to get Nebraska's ID first = 0; last = stateCount - 1; nebraskaStateId = -1; while (first <= last && nebraskaStateId == -1) { mid = (first + last) / 2; state_t *state = read_state(mid); if (strcmp(state->name, nebraskaStr) == 0) { nebraskaStateId = state->stateId; } else if (strcmp(state->name, nebraskaStr) < 0) { first = mid + 1; } else { last = mid - 1; } free_state(state); } // note, if we didn't find Nebraska, nebraskaStateId = -1 first = 0; last = userCount - 1; while(first <= last) { mid = (first + last) / 2; user_t *user = read_user(mid); if (user->stateId == nebraskaStateId) { nebraskaUserCount++; last = first - 1; } else if(user->stateId < nebraskaStateId) { first = mid + 1; } else { last = mid - 1; } free_user(user); } for(i = mid + 1; i < userCount; i++) { user_t *user = read_user(i); if (user->stateId == nebraskaStateId) { nebraskaUserCount++; } else { i = userCount; } free_user(user); } for(i = mid - 1; i >= 0; i--) { user_t *user = read_user(i); if (user->stateId == nebraskaStateId) { nebraskaUserCount++; } else { i = -1; } free_user(user); } printf("Found %d users from %s (state id %d)\n", nebraskaUserCount, nebraskaStr, nebraskaStateId); // end timing the program gettimeofday(&sysTimeEnd, NULL); float totalTime = (sysTimeEnd.tv_sec - sysTimeStart.tv_sec) + (sysTimeEnd.tv_usec - sysTimeStart.tv_usec) / 1000000.0f; printf("Process time %f seconds\n", totalTime); return 0; }