void ReplicatorStateMachine::initialize( ) { dprintf( D_ALWAYS, "ReplicatorStateMachine::initialize started\n" ); reinitialize( ); // register commands that the service responds to registerCommand(HAD_BEFORE_PASSIVE_STATE); registerCommand(HAD_AFTER_ELECTION_STATE); registerCommand(HAD_AFTER_LEADER_STATE); registerCommand(HAD_IN_LEADER_STATE); registerCommand(REPLICATION_LEADER_VERSION); registerCommand(REPLICATION_TRANSFER_FILE); registerCommand(REPLICATION_NEWLY_JOINED_VERSION); registerCommand(REPLICATION_GIVING_UP_VERSION); registerCommand(REPLICATION_SOLICIT_VERSION); registerCommand(REPLICATION_SOLICIT_VERSION_REPLY); }
Common::Error SwordEngine::go() { _control->checkForOldSaveGames(); setTotalPlayTime(0); uint16 startPos = ConfMan.getInt("boot_param"); _control->readSavegameDescriptions(); if (startPos) { _logic->startPositions(startPos); } else { int saveSlot = ConfMan.getInt("save_slot"); // Savegames are numbered starting from 1 in the dialog window, // but their filenames are numbered starting from 0. if (saveSlot >= 0 && _control->savegamesExist() && _control->restoreGameFromFile(saveSlot)) { _control->doRestore(); } else if (_control->savegamesExist()) { _systemVars.controlPanelMode = CP_NEWGAME; if (_control->runPanel() == CONTROL_GAME_RESTORED) _control->doRestore(); else if (!shouldQuit()) _logic->startPositions(0); } else { // no savegames, start new game. _logic->startPositions(0); } } _systemVars.controlPanelMode = CP_NORMAL; while (!shouldQuit()) { uint8 action = mainLoop(); if (!shouldQuit()) { // the mainloop was left, we have to reinitialize. reinitialize(); if (action == CONTROL_GAME_RESTORED) _control->doRestore(); else if (action == CONTROL_RESTART_GAME) _logic->startPositions(1); _systemVars.forceRestart = false; _systemVars.controlPanelMode = CP_NORMAL; } } return Common::kNoError; }
/** \brief External interface for the simplifier. A client will invoke operator()(s, r, p) to simplify s. The result is stored in r. When proof generation is enabled, a proof for the equivalence (or equisatisfiability) of s and r is stored in p. When proof generation is disabled, this method stores the "undefined proof" object in p. */ void simplifier::operator()(expr * s, expr_ref & r, proof_ref & p) { m_need_reset = true; reinitialize(); expr * s_orig = s; expr * old_s; expr * result; proof * result_proof; switch (m.proof_mode()) { case PGM_DISABLED: // proof generation is disabled. reduce_core(s); // after executing reduce_core, the result of the simplification is in the cache get_cached(s, result, result_proof); r = result; p = m.mk_undef_proof(); break; case PGM_COARSE: // coarse proofs... in this case, we do not produce a step by step (fine grain) proof to show the equivalence (or equisatisfiability) of s an r. m_subst_proofs.reset(); // m_subst_proofs is an auxiliary vector that is used to justify substitutions. See comment on method get_subst. reduce_core(s); get_cached(s, result, result_proof); r = result; if (result == s) p = m.mk_reflexivity(s); else { remove_duplicates(m_subst_proofs); p = m.mk_rewrite_star(s, result, m_subst_proofs.size(), m_subst_proofs.c_ptr()); } break; case PGM_FINE: // fine grain proofs... in this mode, every proof step (or most of them) is described. m_proofs.reset(); old_s = 0; // keep simplyfing until no further simplifications are possible. while (s != old_s) { TRACE("simplifier", tout << "simplification pass... " << s->get_id() << "\n";); TRACE("simplifier_loop", tout << mk_ll_pp(s, m) << "\n";); reduce_core(s); get_cached(s, result, result_proof); SASSERT(is_rewrite_proof(s, result, result_proof)); if (result_proof != 0) { m_proofs.push_back(result_proof); } old_s = s; s = result; }
// update the session list and rebuild the menu void KateSessionMenu::initialize() { if ( initialized() ) { return; } m_sessions.clear(); int id = 0; // no session - exec 'kate' insertItem( SmallIconSet("kate"), i18n("Start Kate (no arguments)"), id++ ); // new session - prompt for a name and exec 'kate --start NAME' insertItem( SmallIconSet("new"), i18n("New Kate Session"), id++ ); // new anonymous session, 'kate --start ""' insertItem( SmallIconSet("new"), i18n("New Anonymous Session"), id++ ); insertSeparator(); QStringList list = KGlobal::dirs()->findAllResources( "data", "kate/sessions/*.katesession", false, true); for (QStringList::ConstIterator it = list.begin(); it != list.end(); ++it) { KSimpleConfig config( *it, true ); config.setGroup( "General" ); m_sessions.append( config.readEntry( "Name" ) ); } m_sessions.sort(); for ( QStringList::ConstIterator it1 = m_sessions.begin(); it1 != m_sessions.end(); ++it1 ) { insertItem( *it1, id++ ); } // means for updating, to let the user manually update if he/she added new sessions. insertSeparator(); insertItem( SmallIconSet("reload"), i18n("Reload Session List"), this, SLOT(reinitialize()) ); }
ID3D11Texture2D* DesktopDuplication::acquireNextFrame(DXGI_OUTDUPL_FRAME_INFO& frameInfoOut) { IDXGIResource* frameResource; hr = outputDuplication->AcquireNextFrame(acquireTimeout, &frameInfoOut, &frameResource); if (hr != S_OK) { reinitialize(); // Second chance to recover adapter failure. std::cout << "Next frame acquisition failed: " << hr << ". Reinitializing DXGI subsystems..." << std::endl; CHECKED(hr, outputDuplication->AcquireNextFrame(acquireTimeout, &frameInfoOut, &frameResource)); } ID3D11Texture2D* frameTex; CHECKED(hr, frameResource->QueryInterface(__uuidof(ID3D11Texture2D), reinterpret_cast<void **>(&frameTex))); frameResource->Release(); ID3D11Texture2D* frameStagingTex = copyToStaging(frameTex); frameTex->Release(); CHECKED(hr, outputDuplication->ReleaseFrame()); return frameStagingTex; }
int AudioController::control(af_instance *af, int cmd, void *arg) { auto ac = priv(af); auto d = ac->d; switch(cmd){ case AF_CONTROL_REINIT: return ac->reinitialize(static_cast<mp_audio*>(arg)); case AF_CONTROL_SET_VOLUME: d->amp = *((float*)arg); d->dirty |= Amp; return AF_OK; case AF_CONTROL_GET_VOLUME: *((float*)arg) = d->amp; return AF_OK; case AF_CONTROL_SET_PLAYBACK_SPEED: d->scale = *(double*)arg; d->dirty |= Scale; return d->tempoScalerActivated; case AF_CONTROL_SET_FORMAT: d->fmt_conv = *(int*)arg; if (!isSupported(d->fmt_conv)) d->fmt_conv = AF_FORMAT_UNKNOWN; return !!d->fmt_conv; case AF_CONTROL_SET_RESAMPLE_RATE: d->outrate = *(int *)arg; d->dirty |= Resample; return AF_OK; case AF_CONTROL_SET_CHANNELS: d->layout = ChannelLayoutMap::toLayout(*(mp_chmap*)arg); return AF_OK; case AF_CONTROL_RESET: if (d->swr) while (swr_drop_output(d->swr, 1000) > 0) ; return AF_OK; default: return AF_UNKNOWN; } }
static void *cpu_thread(void *dummyptr) { #ifndef NDEBUG // Spamsung Galaxy Y running Gingerbread triggers this, wTf?! ASSERT_ON_CPU_THREAD(); #endif LOG("cpu_thread : initialized..."); struct timespec deltat = { 0 }; struct timespec disk_motor_time = { 0 }; struct timespec t0 = { 0 }; // the target timer struct timespec ti = { 0 }; // actual before time sample struct timespec tj = { 0 }; // actual after time sample bool negative = false; long drift_adj_nsecs = 0; // generic drift adjustment between target and actual int debugging_cycles = 0; unsigned long dbg_ticks = 0; #if DEBUG_TIMING int speaker_neg_feedback = 0; int speaker_pos_feedback = 0; unsigned long dbg_cycles_executed = 0; #endif audio_init(); speaker_init(); MB_Initialize(); run_args.emul_reinitialize = 1; cpu_runloop: do { LOG("CPUTHREAD %lu LOCKING FOR MAYBE INITIALIZING AUDIO ...", (unsigned long)cpu_thread_id); pthread_mutex_lock(&interface_mutex); if (emul_reinitialize_audio) { emul_reinitialize_audio = false; speaker_destroy(); extern void MB_SoftDestroy(void); MB_SoftDestroy(); audio_shutdown(); audio_init(); speaker_init(); extern void MB_SoftInitialize(void); MB_SoftInitialize(); } pthread_mutex_unlock(&interface_mutex); LOG("UNLOCKING FOR MAYBE INITIALIZING AUDIO ..."); if (run_args.emul_reinitialize) { reinitialize(); } LOG("cpu_thread : begin main loop ..."); clock_gettime(CLOCK_MONOTONIC, &t0); do { ////SCOPE_TRACE_CPU("CPU mainloop"); // -LOCK----------------------------------------------------------------------------------------- SAMPLE ti if (UNLIKELY(emul_pause_audio)) { emul_pause_audio = false; audio_pause(); } pthread_mutex_lock(&interface_mutex); if (UNLIKELY(emul_resume_audio)) { emul_resume_audio = false; audio_resume(); } if (UNLIKELY(emul_video_dirty)) { emul_video_dirty = false; video_setDirty(A2_DIRTY_FLAG); } clock_gettime(CLOCK_MONOTONIC, &ti); deltat = timespec_diff(t0, ti, &negative); if (deltat.tv_sec) { if (!is_fullspeed) { TIMING_LOG("NOTE : serious divergence from target time ..."); } t0 = ti; deltat = timespec_diff(t0, ti, &negative); } t0 = timespec_add(t0, EXECUTION_PERIOD_NSECS); // expected interval drift_adj_nsecs = negative ? ~deltat.tv_nsec : deltat.tv_nsec; // set up increment & decrement counters run_args.cpu65_cycles_to_execute = (cycles_persec_target / 1000); // cycles_persec_target * EXECUTION_PERIOD_NSECS / NANOSECONDS_PER_SECOND if (!is_fullspeed) { run_args.cpu65_cycles_to_execute += cycles_speaker_feedback; } if (run_args.cpu65_cycles_to_execute < 0) { run_args.cpu65_cycles_to_execute = 0; } MB_StartOfCpuExecute(); if (is_debugging) { debugging_cycles = run_args.cpu65_cycles_to_execute; } do { if (is_debugging) { run_args.cpu65_cycles_to_execute = 1; } run_args.cpu65_cycle_count = 0; cycles_checkpoint_count = 0; cpu65_run(&run_args); // run emulation for cpu65_cycles_to_execute cycles ... #if DEBUG_TIMING dbg_cycles_executed += run_args.cpu65_cycle_count; #endif if (is_debugging) { debugging_cycles -= run_args.cpu65_cycle_count; timing_checkpointCycles(); if (c_debugger_should_break() || (debugging_cycles <= 0)) { int err = 0; if ((err = pthread_cond_signal(&dbg_thread_cond))) { LOG("pthread_cond_signal : %d", err); } if ((err = pthread_cond_wait(&cpu_thread_cond, &interface_mutex))) { LOG("pthread_cond_wait : %d", err); } if (debugging_cycles <= 0) { break; } } if (run_args.emul_reinitialize) { pthread_mutex_unlock(&interface_mutex); goto cpu_runloop; } } } while (is_debugging); MB_UpdateCycles(); // TODO : modularize MB and other peripheral card cycles/interrupts ... speaker_flush(); // play audio TRACE_CPU_BEGIN("advance scanner"); video_scannerUpdate(); TRACE_CPU_END(); clock_gettime(CLOCK_MONOTONIC, &tj); pthread_mutex_unlock(&interface_mutex); // -UNLOCK--------------------------------------------------------------------------------------- SAMPLE tj if (timing_shouldAutoAdjustSpeed() && !is_fullspeed) { disk_motor_time = timespec_diff(disk6.motor_time, tj, &negative); if (UNLIKELY(negative)) { LOG("WHOA... time went backwards #1! Did you just cross a timezone?"); disk_motor_time.tv_sec = 1; } if (!speaker_isActive() && !video_isDirty(A2_DIRTY_FLAG) && (disk6.disk[disk6.drive].file_name != NULL) && !disk6.motor_off && (disk_motor_time.tv_sec || disk_motor_time.tv_nsec > DISK_MOTOR_QUIET_NSECS) ) { TIMING_LOG("auto switching to full speed"); _timing_initialize(CPU_SCALE_FASTEST); } } if (!is_fullspeed) { deltat = timespec_diff(ti, tj, &negative); if (UNLIKELY(negative)) { LOG("WHOA... time went backwards #2! Did you just cross a timezone?"); deltat.tv_sec = 1; } long sleepfor = 0; if (LIKELY(!deltat.tv_sec)) { sleepfor = EXECUTION_PERIOD_NSECS - drift_adj_nsecs - deltat.tv_nsec; } if (sleepfor <= 0) { // lagging ... static time_t throttle_warning = 0; if (t0.tv_sec - throttle_warning > 0) { TIMING_LOG("not sleeping to catch up ... %ld . %ld", deltat.tv_sec, deltat.tv_nsec); throttle_warning = t0.tv_sec; } } else { deltat.tv_sec = 0; deltat.tv_nsec = sleepfor; ////TRACE_CPU_BEGIN("sleep"); nanosleep(&deltat, NULL); ////TRACE_CPU_END(); } #if DEBUG_TIMING // collect timing statistics if (speaker_neg_feedback > cycles_speaker_feedback) { speaker_neg_feedback = cycles_speaker_feedback; } if (speaker_pos_feedback < cycles_speaker_feedback) { speaker_pos_feedback = cycles_speaker_feedback; } if ((dbg_ticks % NANOSECONDS_PER_SECOND) == 0) { TIMING_LOG("tick:(%ld.%ld) real:(%ld.%ld) cycles exe: %d ... speaker feedback: %d/%d", t0.tv_sec, t0.tv_nsec, ti.tv_sec, ti.tv_nsec, dbg_cycles_executed, speaker_neg_feedback, speaker_pos_feedback); dbg_cycles_executed = 0; speaker_neg_feedback = 0; speaker_pos_feedback = 0; } #endif if ((dbg_ticks % NANOSECONDS_PER_SECOND) == 0) { dbg_ticks = 0; } } if (timing_shouldAutoAdjustSpeed() && is_fullspeed) { disk_motor_time = timespec_diff(disk6.motor_time, tj, &negative); if (UNLIKELY(negative)) { LOG("WHOA... time went backwards #3! Did you just cross a timezone?"); disk_motor_time.tv_sec = 1; } if (speaker_isActive() || video_isDirty(A2_DIRTY_FLAG) || (disk6.motor_off && (disk_motor_time.tv_sec || disk_motor_time.tv_nsec > DISK_MOTOR_QUIET_NSECS)) ) { double speed = alt_speed_enabled ? cpu_altscale_factor : cpu_scale_factor; if (speed <= CPU_SCALE_FASTEST_PIVOT) { TIMING_LOG("auto switching to configured speed"); _timing_initialize(speed); } } } if (UNLIKELY(run_args.emul_reinitialize)) { break; } if (UNLIKELY(emul_reinitialize_audio)) { break; } if (UNLIKELY(cpu_shutting_down)) { break; } } while (1); if (UNLIKELY(cpu_shutting_down)) { break; } } while (1); speaker_destroy(); MB_Destroy(); audio_shutdown(); cpu_thread_id = 0; cpu_pause(); disk6_eject(0); disk6_eject(1); return NULL; }
int main(int argc, char *argv[]) { struct commandline cmd; #ifdef AFS_NT40_ENV /* initialize CPP with the correct pre-processor for Windows */ CPP = getenv("RXGEN_CPPCMD"); if (!CPP) CPP = "cl /EP /C /nologo"; #endif /* AFS_NT40_ENV */ #ifdef AFS_AIX32_ENV /* * The following signal action for AIX is necessary so that in case of a * crash (i.e. core is generated) we can include the user's data section * in the core dump. Unfortunately, by default, only a partial core is * generated which, in many cases, isn't too useful. */ struct sigaction nsa; sigemptyset(&nsa.sa_mask); nsa.sa_handler = SIG_DFL; nsa.sa_flags = SA_FULLDUMP; sigaction(SIGSEGV, &nsa, NULL); #endif reinitialize(); if (!parseargs(argc, argv, &cmd)) { f_print(stderr, "usage: %s infile\n", cmdname); f_print(stderr, " %s [-c | -h | -l | -m | -C | -S | -r | -b | -k | -R | -p | -d | -z | -u] [-Pprefix] [-Idir] [-o outfile] [infile]\n", cmdname); f_print(stderr, " %s [-s udp|tcp]* [-o outfile] [infile]\n", cmdname); exit(1); } OutFileFlag = cmd.outfile; if (OutFileFlag) strcpy(OutFile, cmd.outfile); if (cmd.cflag) { OutFileFlag = NULL; c_output(cmd.infile, "-DRPC_XDR", !EXTEND, cmd.outfile, 0); } else if (cmd.hflag) { h_output(cmd.infile, "-DRPC_HDR", !EXTEND, cmd.outfile, 0); } else if (cmd.lflag) { l_output(cmd.infile, "-DRPC_CLNT", !EXTEND, cmd.outfile); } else if (cmd.sflag || cmd.mflag) { s_output(argc, argv, cmd.infile, "-DRPC_SVC", !EXTEND, cmd.outfile, cmd.mflag); } else if (cmd.Cflag) { OutFileFlag = NULL; C_output(cmd.infile, "-DRPC_CLIENT", !EXTEND, cmd.outfile, 1); } else if (cmd.Sflag) { OutFileFlag = NULL; S_output(cmd.infile, "-DRPC_SERVER", !EXTEND, cmd.outfile, 1); } else { if (OutFileFlag && (strrchr(OutFile, '.') == NULL)) strcat(OutFile, "."); if (cmd.rflag) { C_output((OutFileFlag ? OutFile : cmd.infile), "-DRPC_CLIENT", EXTEND, ".cs.c", 1); reinitialize(); S_output((OutFileFlag ? OutFile : cmd.infile), "-DRPC_SERVER", EXTEND, ".ss.c", 1); reinitialize(); } else { reinitialize(); c_output((OutFileFlag ? OutFile : cmd.infile), "-DRPC_XDR", EXTEND, ".xdr.c", 0); reinitialize(); h_output((OutFileFlag ? OutFile : cmd.infile), "-DRPC_HDR", EXTEND, ".h", 0); reinitialize(); C_output((OutFileFlag ? OutFile : cmd.infile), "-DRPC_CLIENT", EXTEND, ".cs.c", 1); reinitialize(); S_output((OutFileFlag ? OutFile : cmd.infile), "-DRPC_SERVER", EXTEND, ".ss.c", 1); reinitialize(); } } if (fin && pclose_fin) { /* the cpp command we called returned a non-zero exit status */ if (pclose(fin)) { crash(); } } exit(0); }
///@brief initialize ADC0 with 64 prescalar //ADC clock needs to be between 50kHz and 200kHz //Assume 8Mhz F_OSC //8MHz/64 = 125kHz ANALOG::ANALOG(){ channel = 0; prescalar = ADC_DIV64; reinitialize(); }
int less_main(int argc, char **argv) { int keypress; INIT_G(); /* TODO: -x: do not interpret backspace, -xx: tab also */ /* -xxx: newline also */ /* -w N: assume width N (-xxx -w 32: hex viewer of sorts) */ getopt32(argv, "EMmN~I" IF_FEATURE_LESS_DASHCMD("S")); argc -= optind; argv += optind; num_files = argc; files = argv; /* Another popular pager, most, detects when stdout * is not a tty and turns into cat. This makes sense. */ if (!isatty(STDOUT_FILENO)) return bb_cat(argv); if (!num_files) { if (isatty(STDIN_FILENO)) { /* Just "less"? No args and no redirection? */ bb_error_msg("missing filename"); bb_show_usage(); } } else { filename = xstrdup(files[0]); } if (option_mask32 & FLAG_TILDE) empty_line_marker = ""; kbd_fd = open(CURRENT_TTY, O_RDONLY); if (kbd_fd < 0) return bb_cat(argv); ndelay_on(kbd_fd); tcgetattr(kbd_fd, &term_orig); term_less = term_orig; term_less.c_lflag &= ~(ICANON | ECHO); term_less.c_iflag &= ~(IXON | ICRNL); /*term_less.c_oflag &= ~ONLCR;*/ term_less.c_cc[VMIN] = 1; term_less.c_cc[VTIME] = 0; get_terminal_width_height(kbd_fd, &width, &max_displayed_line); /* 20: two tabstops + 4 */ if (width < 20 || max_displayed_line < 3) return bb_cat(argv); max_displayed_line -= 2; /* We want to restore term_orig on exit */ bb_signals(BB_FATAL_SIGS, sig_catcher); #if ENABLE_FEATURE_LESS_WINCH signal(SIGWINCH, sigwinch_handler); #endif buffer = xmalloc((max_displayed_line+1) * sizeof(char *)); reinitialize(); while (1) { #if ENABLE_FEATURE_LESS_WINCH while (WINCH_COUNTER) { again: winch_counter--; get_terminal_width_height(kbd_fd, &width, &max_displayed_line); /* 20: two tabstops + 4 */ if (width < 20) width = 20; if (max_displayed_line < 3) max_displayed_line = 3; max_displayed_line -= 2; free(buffer); buffer = xmalloc((max_displayed_line+1) * sizeof(char *)); /* Avoid re-wrap and/or redraw if we already know * we need to do it again. These ops are expensive */ if (WINCH_COUNTER) goto again; re_wrap(); if (WINCH_COUNTER) goto again; buffer_fill_and_print(); /* This took some time. Loop back and check, * were there another SIGWINCH? */ } #endif keypress = less_getch(-1); /* -1: do not position cursor */ keypress_process(keypress); } }
static size_t processNextInotifyEvent(int *inotifyFd, char *buf, int bufSize, int firstTry) { char fullPath[PATH_MAX]; struct inotify_event *ev; size_t evLen; int evCacheSlot; ev = (struct inotify_event *) buf; displayInotifyEvent(ev); if (ev->wd != -1 && !(ev->mask & IN_IGNORED)) { /* IN_Q_OVERFLOW has (ev->wd == -1) */ /* Skip IN_IGNORED, since it will come after an event that has already zapped the corresponding cache entry */ /* Cache consistency check; see the discussion of "intra-tree" rename() events */ evCacheSlot = findWatchChecked(ev->wd); if (evCacheSlot == -1) { /* Cache reached an inconsistent state */ *inotifyFd = reinitialize(*inotifyFd); /* Discard all remaining events in current read() buffer */ return INOTIFY_READ_BUF_LEN; } } evLen = sizeof(struct inotify_event) + ev->len; if ((ev->mask & IN_ISDIR) && (ev->mask & (IN_CREATE | IN_MOVED_TO))) { /* A new subdirectory was created, or a subdirectory was renamed into the tree; create watches for it, and all of its subdirectories. */ snprintf(fullPath, sizeof(fullPath), "%s/%s", wlCache[evCacheSlot].path, ev->name); logMessage(VB_BASIC, "Directory creation on wd %d: %s\n", ev->wd, fullPath); /* We only watch the new subtree if it has not already been cached. This deals with a race condition: * On the one hand, the following steps might occur: 1. The "child" directory is created. 2. The "grandchild" directory is created 3. We receive an IN_CREATE event for the creation of the "child" and create a watch and a cache entry for it. 4. To handle the possibility that step 2 came before step 3, we recursively walk through the descendants of the "child" directory, adding any subdirectories to the cache. * On the other hand, the following steps might occur: 1. The "child" directory is created. 3. We receive an IN_CREATE event for the creation of the "child" and create a watch and a cache entry for it. 3. The "grandchild" directory is created 4. During the recursive walk through the descendants of the "child" directory, we cache the "grandchild" and add a watch for it. 5. We receive the IN_CREATE event for the creation of the "grandchild". At this point, we should NOT create a cache entry and watch for the "grandchild" because they already exist. (Creating the watch for the second time is harmless, but adding a second cache for the grandchild would leave the cache in a confused state.) */ if (!pathnameInCache(fullPath)) watchSubtree(*inotifyFd, fullPath); } else if (ev->mask & IN_DELETE_SELF) { /* A directory was deleted. Remove the corresponding item from the cache. */ logMessage(VB_BASIC, "Clearing watchlist item %d (%s)\n", ev->wd, wlCache[evCacheSlot].path); if (isRootDirPath(wlCache[evCacheSlot].path)) zapRootDirPath(wlCache[evCacheSlot].path); markCacheSlotEmpty(evCacheSlot); /* No need to remove the watch; that happens automatically */ } else if ((ev->mask & (IN_MOVED_FROM | IN_ISDIR)) == (IN_MOVED_FROM | IN_ISDIR)) { /* We have a "moved from" event. To know how to deal with it, we need to determine whether there is a following "moved to" event with a matching cookie value (i.e., an "intra-tree" rename() where the source and destination are inside our monitored trees). If there is not, then we are dealing with a rename() out of our monitored tree(s). We assume that if this is an "intra-tree" rename() event, then the "moved to" event is the next event in the buffer returned by the current read(). (If we are already at the last event in this buffer, then we ask our caller to read a bit more, in the hope of getting the following IN_MOVED_TO event in the next read().) In most cases, the assumption holds. However, where multiple processes are manipulating the tree, we can can get event sequences such as the following: IN_MOVED_FROM (rename(x) by process A) IN_MOVED_FROM (rename(y) by process B) IN_MOVED_TO (rename(y) by process B) IN_MOVED_TO (rename(x) by process A) In principle, there may be arbitrarily complex variations on the above theme. Our assumption that related IN_MOVED_FROM and IN_MOVED_TO events are consecutive is broken by such scenarios. We could try to resolve this issue by extending the window we use to search for IN_MOVED_TO events beyond the next item in the queue. But this must be done heuristically (e.g., limiting the window to N events or to events read within X milliseconds), because sometimes we will have an unmatched IN_MOVED_FROM events that result from out-of-tree renames. The heuristic approach is therefore unavoidably racy: there is always a chance that we will fail to match up an IN_MOVED_FROM+IN_MOVED_TO event pair. So, this program takes the simple approach of assuming that an IN_MOVED_FROM+IN_MOVED_TO pair occupy consecutive events in the buffer returned by read(). When that assumption is wrong (and we therefore fail to recognize an intra-tree rename() event), then the rename will be treated as separate "moved from" and "moved to" events, with the result that some watch items and cache entries are zapped and re-created. This causes the watch descriptors in our cache to become inconsistent with the watch descriptors in as yet unread events, because the watches are re-created with different watch descriptor numbers. Once such an inconsistency occurs, then, at some later point, we will do a lookup for a watch descriptor returned by inotify, and find that it is not in our cache. When that happens, we reinitialize our cache with a fresh set of watch descriptors and re-create the inotify file descriptor, in order to bring our cache back into consistency with the filesystem. An alternative would be to cache the cookies of the (recent) IN_MOVED_FROM events for which which we did not find a matching IN_MOVED_TO event, and rebuild our watch cache when we find an IN_MOVED_TO event whose cookie matches one of the cached cookies. Yet another approach when we detect an out-of-tree rename would be to reinitialize the cache and create a new inotify file descriptor. (TODO: consider the fact that for a rename event, there won't be other events for the object between IN_MOVED_FROM and IN_MOVED_TO.) Rebuilding the watch cache is expensive if the monitored tree is large. So, there is a trade-off between how much effort we want to go to to avoid cache rebuilds versus how much effort we want to devote to matching up IN_MOVED_FROM+IN_MOVED_TO event pairs. At the one extreme we would do no search ahead for IN_MOVED_TO, with the result that every rename() potentially could trigger a cache rebuild. Limiting the search window to just the following event is a compromise that catches the vast majority of intra-tree renames and triggers relatively few cache rebuilds. */ struct inotify_event *nextEv; nextEv = (struct inotify_event *) (buf + evLen); if (((char *) nextEv < buf + bufSize) && (nextEv->mask & IN_MOVED_TO) && (nextEv->cookie == ev->cookie)) { int nextEvCacheSlot; /* We have a rename() event. We need to fix up the cached pathnames for the corresponding directory and all of its subdirectories. */ nextEvCacheSlot = findWatchChecked(nextEv->wd); if (nextEvCacheSlot == -1) { /* Cache reached an inconsistent state */ *inotifyFd = reinitialize(*inotifyFd); /* Discard all remaining events in current read() buffer */ return INOTIFY_READ_BUF_LEN; } rewriteCachedPaths(wlCache[evCacheSlot].path, ev->name, wlCache[nextEvCacheSlot].path, nextEv->name); /* We have also processed the next (IN_MOVED_TO) event, so skip over it */ evLen += sizeof(struct inotify_event) + nextEv->len; } else if (((char *) nextEv < buf + bufSize) || !firstTry) { /* We got a "moved from" event without an accompanying "moved to" event. The directory has been moved outside the tree we are monitoring. We need to remove the watches and zap the cache entries for the moved directory and all of its subdirectories. */ logMessage(VB_NOISY, "MOVED_OUT: %p %p\n", wlCache[evCacheSlot].path, ev->name); logMessage(VB_NOISY, "firstTry = %d; remaining bytes = %d\n", firstTry, buf + bufSize - (char *) nextEv); snprintf(fullPath, sizeof(fullPath), "%s/%s", wlCache[evCacheSlot].path, ev->name); if (zapSubtree(*inotifyFd, fullPath) == -1) { /* Cache reached an inconsistent state */ *inotifyFd = reinitialize(*inotifyFd); /* Discard all remaining events in current read() buffer */ return INOTIFY_READ_BUF_LEN; } } else { logMessage(VB_NOISY, "HANGING IN_MOVED_FROM\n"); return -1; /* Tell our caller to do another read() */ } } else if (ev->mask & IN_Q_OVERFLOW) { static int overflowCnt = 0; overflowCnt++; logMessage(0, "Queue overflow (%d) (inotifyReadCnt = %d)\n", overflowCnt, inotifyReadCnt); /* When the queue overflows, some events are lost, at which point we've lost any chance of keeping our cache consistent with the state of the filesystem. So, discard this inotify file descriptor and create a new one, and zap and rebuild the cache. */ *inotifyFd = reinitialize(*inotifyFd); /* Discard all remaining events in current read() buffer */ evLen = INOTIFY_READ_BUF_LEN; } else if (ev->mask & IN_UNMOUNT) { /* When a filesystem is unmounted, each of the watches on the is dropped, and an unmount and an ignore event are generated. There's nothing left for us to monitor, so we just zap the corresponding cache entry. */ logMessage(0, "Filesystem unmounted: %s\n", wlCache[evCacheSlot].path); markCacheSlotEmpty(evCacheSlot); /* No need to remove the watch; that happens automatically */ } else if (ev->mask & IN_MOVE_SELF && isRootDirPath(wlCache[evCacheSlot].path)) { /* If the root path moves to a new location in the same filesystem, then all cached pathnames become invalid, and we have no direct way of knowing the new name of the root path. We could in theory find the new name by caching the i-node of the root path on start-up and then trying to find a pathname that corresponds to that i-node. Instead, we'll keep things simple, and just cease monitoring it. */ logMessage(0, "Root path moved: %s\n", wlCache[evCacheSlot].path); zapRootDirPath(wlCache[evCacheSlot].path); if (zapSubtree(*inotifyFd, wlCache[evCacheSlot].path) == -1) { /* Cache reached an inconsistent state */ *inotifyFd = reinitialize(*inotifyFd); /* Discard all remaining events in current read() buffer */ return INOTIFY_READ_BUF_LEN; } } if (checkCache) checkCacheConsistency(); if (dumpCache) dumpCacheToLog(); return evLen; }
static void executeCommand(int *inotifyFd) { const int MAX_LINE = 100; ssize_t numRead; char line[MAX_LINE], arg[MAX_LINE]; char cmd; int j, cnt, ns, failures; struct stat sb; FILE *fp; numRead = read(STDIN_FILENO, line, MAX_LINE); if (numRead <= 0) { printf("bye!\n"); exit(EXIT_FAILURE); } line[numRead - 1] = '\0'; if (strlen(line) == 0) return; ns = sscanf(line, "%c %s\n", &cmd, arg); switch (cmd) { case 'a': /* Add/refresh a subtree */ cnt = zapSubtree(*inotifyFd, arg); if (cnt == 0) { logMessage(VB_BASIC, "Adding new subtree: %s\n", arg); } else { logMessage(VB_BASIC, "Zapped: %s, %d entries\n", arg, cnt); } watchSubtree(*inotifyFd, arg); break; case 'c': /* Check that all cached pathnames exist */ case 'C': cnt = 0; failures = 0; for (j = 0; j < cacheSize; j++) { if (wlCache[j].wd >= 0) { if (lstat(wlCache[j].path, &sb) == -1) { if (cmd == 'c') logMessage(VB_BASIC, "stat: [slot = %d; wd = %d] %s: %s\n", j, wlCache[j].wd, wlCache[j].path, strerror(errno)); failures++; } else if (!S_ISDIR(sb.st_mode)) { if (cmd == 'c') logMessage(0, "%s is not a directory\n", wlCache[j].path); exit(EXIT_FAILURE); } else { if (cmd == 'c') logMessage(VB_NOISY, "OK: [slot = %d; wd = %d] %s\n", j, wlCache[j].wd, wlCache[j].path); cnt++; } } } logMessage(0, "Successfully verified %d entries\n", cnt); logMessage(0, "Failures: %d\n", failures); break; case 'l': /* List entries in the cache */ cnt = 0; for (j = 0; j < cacheSize; j++) { if (wlCache[j].wd >= 0) { logMessage(0, "%d: %d %s\n", j, wlCache[j].wd, wlCache[j].path); cnt++; } } logMessage(VB_BASIC, "Total entries: %d\n", cnt); break; case 'q': /* Quit */ exit(EXIT_SUCCESS); case 'v': /* Set log verbosity level */ if (ns == 2) verboseMask = atoi(arg); else { verboseMask = !verboseMask; printf("%s\n", verboseMask ? "on" : "off"); } break; case 'd': /* Toggle cache dumping */ dumpCache = !dumpCache; printf("%s\n", dumpCache ? "on" : "off"); break; case 'x': /* Set toggle checking */ checkCache = !checkCache; printf("%s\n", checkCache ? "on" : "off"); break; case 'w': /* Write directory list to file */ /* We can compare the output from the below against the output from "find DIR -type d" to check whether the contents of the cache are consistent with the state of the filesystem */ fp = fopen(arg, "w+"); if (fp == NULL) perror("fopen"); for (j = 0; j < cacheSize; j++) if (wlCache[j].wd >= 0) fprintf(fp, "%s\n", wlCache[j].path); fclose(fp); break; case 'z': /* Stop watching a subtree, and zap its cache entries */ cnt = zapSubtree(*inotifyFd, arg); logMessage(VB_BASIC, "Zapped: %s, %d entries\n", arg, cnt); break; case '0': /* Rebuild cache */ close(*inotifyFd); *inotifyFd = reinitialize(-1); break; default: printf("Unrecognized command: %c\n", cmd); printf("Commands:\n"); printf("0 Rebuild cache\n"); printf("a path Add/refresh pathname watches and cache\n"); printf("c Verify cached pathnames\n"); printf("d Toggle cache dumping\n"); printf("l List cached pathnames\n"); printf("q Quit\n"); printf("v [n] Toggle/set verbose level for messages to stderr\n"); printf(" 0 = no messages\n"); printf(" 1 = basic messages\n"); printf(" 2 = verbose messages\n"); printf(" 3 = basic and verbose messages\n"); printf("w file Write directory list to file\n"); printf("x Toggle cache checking\n"); printf("z path Zap pathname and watches from cache\n"); break; } }
void winshow() { if(damagecount==100 && win!=1 && timec!=1) { switch(color_track){ case 1: iShowBMP(0,0,"imagess//pliss_0_dam.bmp");break; case 2: iShowBMP(0,0,"imagess//pliss_1_dam.bmp");break; case 3: iShowBMP(0,0,"imagess//pliss_2_dam.bmp");break; case 4: iShowBMP(0,0,"imagess//pliss_3_dam.bmp");break; case 5: iShowBMP(0,0,"imagess//pliss_4_dam.bmp");break; default: iShowBMP(0,0,"imagess//pliss_0_dam.bmp");break; } } if(damagecount_c==100&& win!=1 && timec!=1) { switch(color_track){ case 5: iShowBMP(0,0,"imagess//pliss_5_dam.bmp");break; case 1: iShowBMP(0,0,"imagess//pliss_1_dam.bmp");break; case 2: iShowBMP(0,0,"imagess//pliss_2_dam.bmp");break; case 3: iShowBMP(0,0,"imagess//pliss_3_dam.bmp");break; case 4: iShowBMP(0,0,"imagess//pliss_4_dam.bmp");break; default: iShowBMP(0,0,"imagess//pliss_1_dam.bmp");break; } } if(damagecount==100&&damagecount_c==100 && win!=1 && timec!=1) { iShowBMP(0,0,"imagess//LOAD1.bmp"); } if(win==1 && timec!=1) { declare_win(); } if(timec==1 && win!=1 ) { iShowBMP(0,0,"imagess//pliss_time.bmp"); } if(damagecount==100||damagecount_c==100|| win==1 || timec==1 && asif || draw==1) { iShowBMP(0,0,"imagess//SHOWHIGHSCORE.bmp"); win=0; timec=0; collision=0; collision_c=0; reinitialize(); mark=1; //flag=0; //exit(1); } }
// Метод тестирования валидности формулы в виде latex-строки. bool CNotationTester::Test( const std::string& src, const std::set<std::string>& _knownVars ) { reinitialize(); CNotationBuilder builder( src ); std::stack< std::pair<std::string, int> > notation = builder.GetReverseNotation(); knownVars = _knownVars; tokens = builder.GetTokens(); while( !notation.empty() ) { currentNotation = notation.top(); notation.pop(); CTexToken currToken = CTexToken::ConvertToken( currentNotation.first ); switch( currToken.GetType() ) { case TT_Number: numbersStack.push( currToken ); break; case TT_Variable: numbersStack.push( currToken ); break; case TT_BoolOp: case TT_ComparisonOp: case TT_BinOp: case TT_Frac: case TT_ComplexSqrt: testBinaryOperation( currToken ); break; case TT_Pow: // Особенность написания аггрегирующих операторов sum/mul if( !notation.empty() && IsAggregationFunction( notation.top().first ) ) { break; } testBinaryOperation( currToken ); break; case TT_UnaryOp: case TT_Cos: case TT_Sin: case TT_Tan: case TT_Ctan: case TT_SimpleSqrt: testUnaryOperation( currToken ); break; case TT_Assign: // Допускается определение переменных только в функциях аггрегаторах. // Если не выполняется следующее условие, значит мы не определяем переменную в аггрегаторе и это ошибка. if( notation.empty() || notation.top().first != "_" ) { // Ошибка - некорретктное использование = throw CErrorCatcher( "Assign error", tokens, notation.top().second ); } testAssignOperation(); break; case TT_Sum: case TT_Mul: testAggregationOperation( currToken ); break; case TT_LowIndex: // Индексация была пока никак не обрабатывается. break; default: assert( false ); } } if( numbersStack.size() == 1 && numbersStack.top().GetType() == TT_Variable && knownVars.find( numbersStack.top().GetString() ) == knownVars.end() ) { throw CErrorCatcher( "Unknown variable " + numbersStack.top().GetString(), tokens, currentNotation.second ); } else if( numbersStack.size() != 1 || ( numbersStack.top().GetType() != TT_Computable && numbersStack.top().GetType() != TT_Number && numbersStack.top().GetType() != TT_Variable ) ) { // Ошибка, итоговой результат несвязен, либо не является вычислимым. - Здесь ошибочно все выражение, точнее выделить ошибку сложно. throw CErrorCatcher( "Error", tokens, -1 ); } return true; }
///@brief initialize AD converter on Atmega168 for ///@param ch ADC channel ///@param pscalar Prescalar ANALOG::ANALOG(uint8_t ch, uint8_t pscalar){ channel = ch; prescalar = pscalar; reinitialize(); }
void SIDDSensorModel::initializeFromISD(const csm::Nitf21Isd& isd, size_t imageIndex) { try { // Check for the SIDD DES associated with imageIndex and parse it // DES's are always in the same order as the images, so we just have to // find the Nth DES xml::lite::Document* siddXML = NULL; xml::lite::MinidomParser domParser; size_t numSIDD = 0; const std::vector< csm::Des>& desList(isd.fileDess()); for (size_t ii = 0; ii < desList.size(); ++ii) { DataType dataType = getDataType(desList[ii]); if (dataType != DataType::DERIVED) { continue; } const std::string& desData(desList[ii].data()); if (!desData.empty()) { try { io::StringStream stream; stream.write(desData.c_str(), desData.length()); domParser.clear(); domParser.parse(stream); if (domParser.getDocument()->getRootElement()->getLocalName() == "SIDD") { if (numSIDD == imageIndex) { siddXML = domParser.getDocument(); break; } ++numSIDD; } } catch(const except::Exception& ) { // Couldn't parse DES as xml -- it's not a sidd so skip it } } } if (siddXML == NULL) { const std::string message = (numSIDD == 0) ? "Not a SIDD" : "Found " + str::toString(numSIDD) + " SIDD XMLs but requested image index " + str::toString(imageIndex); throw csm::Error(csm::Error::SENSOR_MODEL_NOT_CONSTRUCTIBLE, message, "SIDDSensorModel::SIDDSensorModel"); } // get xml as string for sensor model state io::StringStream stringStream; siddXML->getRootElement()->print(stringStream); mSensorModelState = NAME + std::string(" ") + stringStream.stream().str(); six::XMLControlRegistry xmlRegistry; xmlRegistry.addCreator(six::DataType::DERIVED, new six::XMLControlCreatorT<six::sidd::DerivedXMLControl>()); logging::NullLogger logger; std::auto_ptr<six::XMLControl> control( xmlRegistry.newXMLControl(six::DataType::DERIVED, &logger)); mData.reset(reinterpret_cast<six::sidd::DerivedData*>(control->fromXML( siddXML, mSchemaDirs))); reinitialize(); } catch (const except::Exception& ex) { throw csm::Error(csm::Error::SENSOR_MODEL_NOT_CONSTRUCTIBLE, ex.getMessage(), "SIDDSensorModel::initializeFromISD"); } }
ASYNC RemoteMenu::FilesAdded(const KURL &directory) { if (directory.protocol()=="remote") reinitialize(); }
ASYNC RemoteMenu::FilesRenamed(const KURL &src, const KURL &dest) { if (src.protocol()=="remote" || dest.protocol()=="remote") reinitialize(); }
int main(int argc, const char **argv) { struct commandline cmd; memset(&cmd, 0, sizeof (struct commandline)); clear_args(); if (!parseargs(argc, argv, &cmd)) usage(); /* * Only the client and server side stubs are likely to be customized, * so in that case only, check if the outfile exists, and if so, * print an error message and exit. */ if (cmd.Ssflag || cmd.Scflag || cmd.makefileflag) checkfiles(cmd.infile, cmd.outfile); else checkfiles(cmd.infile, NULL); if (cmd.cflag) { c_output(cmd.infile, "-DRPC_XDR", DONT_EXTEND, cmd.outfile); } else if (cmd.hflag) { h_output(cmd.infile, "-DRPC_HDR", DONT_EXTEND, cmd.outfile, cmd.hflag); } else if (cmd.lflag) { l_output(cmd.infile, "-DRPC_CLNT", DONT_EXTEND, cmd.outfile); } else if (cmd.sflag || cmd.mflag || (cmd.nflag)) { s_output(argc, argv, cmd.infile, "-DRPC_SVC", DONT_EXTEND, cmd.outfile, cmd.mflag, cmd.nflag); } else if (cmd.tflag) { t_output(cmd.infile, "-DRPC_TBL", DONT_EXTEND, cmd.outfile); } else if (cmd.Ssflag) { svc_output(cmd.infile, "-DRPC_SERVER", DONT_EXTEND, cmd.outfile); } else if (cmd.Scflag) { clnt_output(cmd.infile, "-DRPC_CLIENT", DONT_EXTEND, cmd.outfile); } else if (cmd.makefileflag) { mkfile_output(&cmd); } else { /* the rescans are required, since cpp may effect input */ c_output(cmd.infile, "-DRPC_XDR", EXTEND, "_xdr.c"); reinitialize(); h_output(cmd.infile, "-DRPC_HDR", EXTEND, ".h", cmd.hflag); reinitialize(); l_output(cmd.infile, "-DRPC_CLNT", EXTEND, "_clnt.c"); reinitialize(); if (inetdflag || !tirpcflag) s_output(allc, allv, cmd.infile, "-DRPC_SVC", EXTEND, "_svc.c", cmd.mflag, cmd.nflag); else s_output(allnc, allnv, cmd.infile, "-DRPC_SVC", EXTEND, "_svc.c", cmd.mflag, cmd.nflag); if (tblflag) { reinitialize(); t_output(cmd.infile, "-DRPC_TBL", EXTEND, "_tbl.i"); } if (allfiles) { reinitialize(); svc_output(cmd.infile, "-DRPC_SERVER", EXTEND, "_server.c"); reinitialize(); clnt_output(cmd.infile, "-DRPC_CLIENT", EXTEND, "_client.c"); } if (allfiles || (cmd.makefileflag == 1)){ reinitialize(); mkfile_output(&cmd); } } exit(nonfatalerrors); /* NOTREACHED */ }
int main(int argc, char **argv) { struct commandline cmd; (void) memset((char *) &cmd, 0, sizeof(struct commandline)); clear_args(); if (!parseargs(argc, argv, &cmd)) usage(); if (cmd.cflag || cmd.hflag || cmd.lflag || cmd.tflag || cmd.sflag || cmd.mflag || cmd.nflag || cmd.Ssflag || cmd.Scflag) { checkfiles(cmd.infile, cmd.outfile); } else checkfiles(cmd.infile, NULL); if (cmd.cflag) { c_output(cmd.infile, "-DRPC_XDR", DONT_EXTEND, cmd.outfile); } else if (cmd.hflag) { h_output(cmd.infile, "-DRPC_HDR", DONT_EXTEND, cmd.outfile); } else if (cmd.lflag) { l_output(cmd.infile, "-DRPC_CLNT", DONT_EXTEND, cmd.outfile); } else if (cmd.sflag || cmd.mflag || (cmd.nflag)) { s_output(argc, argv, cmd.infile, "-DRPC_SVC", DONT_EXTEND, cmd.outfile, cmd.mflag, cmd.nflag); } else if (cmd.tflag) { t_output(cmd.infile, "-DRPC_TBL", DONT_EXTEND, cmd.outfile); } else if (cmd.Ssflag) { svc_output(cmd.infile, "-DRPC_SERVER", DONT_EXTEND, cmd.outfile); } else if (cmd.Scflag) { clnt_output(cmd.infile, "-DRPC_CLIENT", DONT_EXTEND, cmd.outfile); } else { /* the rescans are required, since cpp may effect input */ c_output(cmd.infile, "-DRPC_XDR", EXTEND, "_xdr.c"); reinitialize(); h_output(cmd.infile, "-DRPC_HDR", EXTEND, ".h"); reinitialize(); l_output(cmd.infile, "-DRPC_CLNT", EXTEND, "_clnt.c"); reinitialize(); if (inetdflag || !tirpcflag) s_output(allc, allv, cmd.infile, "-DRPC_SVC", EXTEND, "_svc.c", cmd.mflag, cmd.nflag); else s_output(allnc, allnv, cmd.infile, "-DRPC_SVC", EXTEND, "_svc.c", cmd.mflag, cmd.nflag); if (tblflag) { reinitialize(); t_output(cmd.infile, "-DRPC_TBL", EXTEND, "_tbl.i"); } if (allfiles) { reinitialize(); svc_output(cmd.infile, "-DRPC_SERVER", EXTEND, "_server.c"); } if (allfiles) { reinitialize(); clnt_output(cmd.infile, "-DRPC_CLIENT", EXTEND, "_client.c"); } } exit(nonfatalerrors); /* NOTREACHED */ }
/*! \brief Reset the iterator (it restart from the beginning) * */ inline void reset() { act = 0; // initialize the first iterator reinitialize(boxes.get(0).getKP1,boxes.get(0).getKP2); }
void FPScreenMirror::setOffsetScale(float x, float y) { offsetScaleX = x; offsetScaleY = y; reinitialize(); }
void stepNetwork(void) { int i, k, pi, pi2, nbytes, newfd; char remoteIP[INET6_ADDRSTRLEN]; struct sockaddr_storage remoteaddr; socklen_t addrlen; struct timeval tv; if(getDeathMessage(sendbuf)) { for(k = 0; k < conf.maxPlayers; ++k) { if(connection[k].socket && !connection[k].bot) { snd(connection[k].socket, "\r\n"); snd(connection[k].socket, sendbuf); snd(connection[k].socket, "\r\n> "); } } } tv.tv_sec = 0; tv.tv_usec = 1; readfds = master; if(select(fdmax + 1, &readfds, NULL, NULL, &tv) == -1) { print_error("select"); exit(5); } for(i = 0; i <= fdmax; ++i) { if(FD_ISSET(i, &readfds)) { if(i == listener) { addrlen = sizeof remoteaddr; newfd = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen); if(newfd == -1) { print_error("accept"); } else { getnameinfo((struct sockaddr *)&remoteaddr, addrlen, remoteIP, sizeof remoteIP, NULL, 0, NI_NUMERICHOST | NI_NUMERICSERV); for(k = 0; k < conf.maxPlayers; ++k) { if(connection[k].socket == 0) { connection[k].socket = newfd; playerJoin(k); updateName(k, "Anonymous"); allSendPlayerPos(k); break; } } if(k == conf.maxPlayers) { close(newfd); printf("new connection from %s on socket %d refused: max connections\n", remoteIP, newfd); } else { FD_SET(newfd, &master); if(newfd > fdmax) { fdmax = newfd; } printf("new connection from %s on socket %d accepted\n", remoteIP, newfd); snd(newfd, WELCOME); } } } else { if((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) { if(nbytes == 0) { printf("socket %d hung up\n", i); } else { print_error("recv"); } for(k = 0; k < conf.maxPlayers; ++k) { if(connection[k].socket == i) { disconnectPlayer(k); allSendPlayerLeave(k); break; } } close(i); FD_CLR(i, &master); } else { pi = -1; for(k = 0; k < conf.maxPlayers; ++k) { if(connection[k].socket == i) { pi = k; break; } } for(k = 0; k < nbytes && pi >= 0; ++k) { unsigned char c = buf[k]; if(c != '\r' && c != '\n') { if(isprint(c) && connection[pi].msgbufindex < 128 - 2) { connection[pi].msgbuf[connection[pi].msgbufindex++] = c; } } else { if(connection[pi].msgbufindex == 0) { continue; } connection[pi].msgbuf[connection[pi].msgbufindex] = '\0'; connection[pi].msgbuf[connection[pi].msgbufindex + 1] = '\0'; connection[pi].msgbufindex = 0; if(connection[pi].echo) { snd(i, connection[pi].msgbuf); snd(i, "\r\n"); } if(!overdrive)printf("%16s (%d): \"%s\"\n", getPlayer(pi)->name, pi, connection[pi].msgbuf); switch(connection[pi].msgbuf[0]) { case 'n': { updateName(pi, connection[pi].msgbuf + 2); break; } case 'v': { updateVelocity(pi, atof(connection[pi].msgbuf + 2)); break; } case 'z': { updateZoom(atof(connection[pi].msgbuf + 2)); break; } case 'c': { clearTraces(pi); break; } case 'o': { overdrive = !overdrive; break; } case 'b': { connection[pi].bot = !connection[pi].bot; if(connection[pi].bot) { sendOwnId(i, pi); for(pi2 = 0; pi2 < conf.maxPlayers; ++pi2) { if(connection[pi2].socket) { sendPlayerPos(i, pi2); } } } break; } case 'f': { toggleFps(); break; } case 'i': { if(strcmp("init", connection[pi].msgbuf) == 0) { reinitialize(); } break; } case 'x': { if(strcmp("xit", connection[pi].msgbuf) == 0) { exit(0); } break; } case 'e': { connection[pi].echo = !connection[pi].echo; break; } case 'q': { disconnectPlayer(pi); allSendPlayerLeave(pi); break; } case 'r': { validateOld(pi); break; } default: { updateAngle(pi, atof(connection[pi].msgbuf)); break; } } if(connection[pi].socket && !connection[pi].bot) { snd(i, "> "); } } } } } } } for(k = 0; k < conf.maxPlayers; ++k) { if(getPlayer(k)->active && getPlayer(k)->timeoutcnt > 2) { disconnectPlayer(k); allSendPlayerLeave(k); } } }
bool FPScreenMirror::process() { if (!initialized) { reinitialize(); return false; } if (!captureWindowHDC || !currentProcessHWND) { return false; } /* if (keyboardWidth < 1 || keyboardHeight < 1) { return false; } */ PerformanceStart(); // get window bitmap as Mat screenshotMat RECT targetRect; GetWindowRect(currentProcessHWND, &targetRect); int clientWidth = targetRect.right - targetRect.left; // -offsetLeft - offsetRight; int clientHeight = targetRect.bottom - targetRect.top; // -offsetTop - offsetBottom; if ((targetRect.left < 0 && targetRect.top < 0 && targetRect.right < 0 && targetRect.bottom < 0) || clientWidth < 0 || clientHeight < 0) { PerformanceStop(); return false; } Mat* screenshotRaw = ImageFilterMat::hdc2mat(captureWindowHDC, 0, 0, clientWidth, clientHeight); if (screenshotRaw == NULL) { PerformanceStop(); delete screenshotRaw; return false; } Mat4b screenshotMat = (Mat4b)*screenshotRaw; cv::Rect cropRect(cutLeft, cutTop, screenshotMat.cols - cutLeft - cutRight, screenshotMat.rows - cutTop - cutBottom); screenshotMat = Mat(screenshotMat, cropRect); blur(screenshotMat, screenshotMat, cv::Size(20, 20)); resize(screenshotMat, screenshotMat, cv::Size(targetWidth, targetHeight), 2, 2, INTER_CUBIC); // ImageFilterMat::incSaturation(screenshotMat, 50, (float)0.7); LEDController::getInstance()->initializeFrame(); Mat4b keyboardMat = Mat4b(*keyboardFx); // draw Keyboard vector<CorsairLedPosition>::iterator it = allKeys.begin(); it = allKeys.begin(); for (; it != allKeys.end(); ) { cv::Rect keyRect( (int)floor((float)(it->left*keyboardZoomFactor + offsetLeft)*uiZoom * offsetScaleX), (int)floor((float)(it->top*keyboardZoomFactor + offsetTop)*uiZoom* offsetScaleY), (int)floor((float)it->width*keyboardZoomFactor*uiZoom * offsetScaleX), (int)floor((float)it->height*keyboardZoomFactor*uiZoom* offsetScaleY)); int overScanX = (int)keyRect.x - overscan; if (overScanX < 0) overScanX = 0; int overScanY = (int)keyRect.y - overscan; if (overScanY < 0) overScanY = 0; int overScanW = (int)keyRect.width + overscan * 2; if (overScanX + overScanW > keyboardMat.cols) overScanW = keyboardMat.cols - overScanX; int overScanH = (int)keyRect.height + overscan * 2; if (overScanY + overScanH > keyboardMat.rows) overScanH = keyboardMat.rows - overScanY; cv::Rect colorDetectionRect(overScanX, overScanY, overScanW, overScanH); try { Mat4b keyMat = Mat(screenshotMat, colorDetectionRect); resize(keyMat, keyMat, cv::Size(1, 1), 0, 0, INTER_CUBIC); Vec4b color = keyMat.at<Vec4b>(0, 0); LEDController::getInstance()->setKey(it->ledId, color[2], color[1], color[0]); cv::rectangle(keyboardMat, keyRect, Scalar(color[0], color[1], color[2], 255), CV_FILLED, 8, 0); cv::rectangle(keyboardMat, keyRect, Scalar(255, 255, 255, 128), 1, 8, 0); // cv::rectangle(keyboardMat, colorDetectionRect, Scalar(0, 0, 255, 128), 1, 8, 0); } catch (...) { // ups... } ++it; } LEDController::getInstance()->updateFrame(); // copy background to UI getBackgroundMat()->copyTo(drawUI); // ImageFilterMat::addAlphaMask(&screenshotMat, mask); ImageFilterMat::overlayImage(&drawUI, &screenshotMat, cv::Point(targetX, targetY)); resize(keyboardMat, keyboardMat, cv::Size(targetWidth, targetHeight)); ImageFilterMat::overlayImage(&drawUI, &keyboardMat, cv::Point(targetX, targetY)); PerformanceDraw(getBackgroundMat()->cols - 130, 20); drawToWindow(&drawUI); // throwing away pointer, so opencv releases memory delete screenshotRaw; PerformanceStop(); return true; }
int main(int argc, char *argv[]) { fd_set rfds; int opt; int inotifyFd; /* Parse command-line options */ verboseMask = 0; checkCache = 0; dumpCache = 0; stopFile = NULL; abortOnCacheProblem = 0; while ((opt = getopt(argc, argv, "a:dxl:v:b:")) != -1) { switch (opt) { case 'a': abortOnCacheProblem = 1; stopFile = optarg; break; case 'x': checkCache = 1; break; case 'd': dumpCache = 1; break; case 'v': verboseMask = atoi(optarg); break; case 'b': readBufferSize = atoi(optarg); break; case 'l': logfp = fopen(optarg, "w+"); if (logfp == NULL) errExit("fopen"); setbuf(logfp, NULL); break; default: usageError(argv[0]); } } if (optind >= argc) usageError(argv[0]); /* Save a copy of the directories on the command line */ copyRootDirPaths(&argv[optind]); /* Create an inotify instance and populate it with entries for directory named on command line */ inotifyFd = reinitialize(-1); /* Loop to handle inotify events and keyboard commands */ printf("%s> ", argv[0]); fflush(stdout); for (;;) { FD_ZERO(&rfds); FD_SET(STDIN_FILENO, &rfds); FD_SET(inotifyFd, &rfds); if (select(inotifyFd + 1, &rfds, NULL, NULL, NULL) == -1) errExit("select"); if (FD_ISSET(STDIN_FILENO, &rfds)) { executeCommand(&inotifyFd); printf("%s> ", argv[0]); fflush(stdout); } if (FD_ISSET(inotifyFd, &rfds)) processInotifyEvents(&inotifyFd); } exit(EXIT_SUCCESS); }
DMetalWavefunction::Amplitude::Amplitude (const boost::shared_ptr<const DMetalWavefunction> &wf_, const PositionArguments &r_) : Wavefunction::Amplitude(wf_, r_), m_partial_update_step(0) { reinitialize(); }
void KonquerorProfilesMenu::slotAboutToShow() { reinitialize(); KPanelMenu::slotAboutToShow(); }
void DMetalWavefunction::Amplitude::reset_ (const PositionArguments &r_) { r = r_; reinitialize(); }
/*! When the current interaction changes. */ void MPWindow::onInteractionChanged(Interaction* interaction) { BaseInteraction* baseinteraction = static_cast<BaseInteraction*>(interaction); connect(this, SIGNAL(interactionReinitialize()), baseinteraction, SLOT(reinitialize())); }
static void *cpu_thread(void *dummyptr) { assert(pthread_self() == cpu_thread_id); LOG("cpu_thread : initialized..."); struct timespec deltat; #if !MOBILE_DEVICE struct timespec disk_motor_time; #endif struct timespec t0; // the target timer struct timespec ti, tj; // actual time samples bool negative = false; long drift_adj_nsecs = 0; // generic drift adjustment between target and actual int debugging_cycles0 = 0; int debugging_cycles = 0; #if DEBUG_TIMING unsigned long dbg_ticks = 0; int speaker_neg_feedback = 0; int speaker_pos_feedback = 0; unsigned int dbg_cycles_executed = 0; #endif do { #ifdef AUDIO_ENABLED LOG("CPUTHREAD %lu LOCKING FOR MAYBE INITIALIZING AUDIO ...", cpu_thread_id); pthread_mutex_lock(&interface_mutex); if (emul_reinitialize_audio) { emul_reinitialize_audio = false; speaker_destroy(); MB_Destroy(); audio_shutdown(); audio_init(); speaker_init(); MB_Initialize(); } pthread_mutex_unlock(&interface_mutex); LOG("UNLOCKING FOR MAYBE INITIALIZING AUDIO ..."); #endif if (emul_reinitialize) { reinitialize(); } LOG("cpu_thread : begin main loop ..."); clock_gettime(CLOCK_MONOTONIC, &t0); do { SCOPE_TRACE_CPU("CPU mainloop"); // -LOCK----------------------------------------------------------------------------------------- SAMPLE ti #ifdef AUDIO_ENABLED if (UNLIKELY(emul_pause_audio)) { emul_pause_audio = false; audio_pause(); } #endif pthread_mutex_lock(&interface_mutex); #ifdef AUDIO_ENABLED if (UNLIKELY(emul_resume_audio)) { emul_resume_audio = false; audio_resume(); } #endif clock_gettime(CLOCK_MONOTONIC, &ti); deltat = timespec_diff(t0, ti, &negative); if (deltat.tv_sec) { if (!is_fullspeed) { TIMING_LOG("NOTE : serious divergence from target time ..."); } t0 = ti; deltat = timespec_diff(t0, ti, &negative); } t0 = timespec_add(t0, EXECUTION_PERIOD_NSECS); // expected interval drift_adj_nsecs = negative ? ~deltat.tv_nsec : deltat.tv_nsec; // set up increment & decrement counters cpu65_cycles_to_execute = (cycles_persec_target / 1000); // cycles_persec_target * EXECUTION_PERIOD_NSECS / NANOSECONDS_PER_SECOND if (!is_fullspeed) { cpu65_cycles_to_execute += cycles_speaker_feedback; } if (cpu65_cycles_to_execute < 0) { cpu65_cycles_to_execute = 0; } #ifdef AUDIO_ENABLED MB_StartOfCpuExecute(); #endif if (is_debugging) { debugging_cycles0 = cpu65_cycles_to_execute; debugging_cycles = cpu65_cycles_to_execute; } do { if (is_debugging) { cpu65_cycles_to_execute = 1; } cpu65_cycle_count = 0; cycles_checkpoint_count = 0; cpu65_run(); // run emulation for cpu65_cycles_to_execute cycles ... if (is_debugging) { debugging_cycles -= cpu65_cycle_count; if (c_debugger_should_break() || (debugging_cycles <= 0)) { int err = 0; if ((err = pthread_cond_signal(&dbg_thread_cond))) { ERRLOG("pthread_cond_signal : %d", err); } if ((err = pthread_cond_wait(&cpu_thread_cond, &interface_mutex))) { ERRLOG("pthread_cond_wait : %d", err); } if (debugging_cycles <= 0) { cpu65_cycle_count = debugging_cycles0 - debugging_cycles/*<=0*/; break; } } } if (emul_reinitialize) { reinitialize(); } } while (is_debugging); #if DEBUG_TIMING dbg_cycles_executed += cpu65_cycle_count; #endif g_dwCyclesThisFrame += cpu65_cycle_count; #ifdef AUDIO_ENABLED MB_UpdateCycles(); // update 6522s (NOTE: do this before updating cycles_count_total) #endif timing_checkpoint_cycles(); #if CPU_TRACING cpu65_trace_checkpoint(); #endif #ifdef AUDIO_ENABLED speaker_flush(); // play audio #endif if (g_dwCyclesThisFrame >= dwClksPerFrame) { g_dwCyclesThisFrame -= dwClksPerFrame; #ifdef AUDIO_ENABLED MB_EndOfVideoFrame(); #endif } clock_gettime(CLOCK_MONOTONIC, &tj); pthread_mutex_unlock(&interface_mutex); // -UNLOCK--------------------------------------------------------------------------------------- SAMPLE tj #if !MOBILE_DEVICE if (timing_shouldAutoAdjustSpeed()) { disk_motor_time = timespec_diff(disk6.motor_time, tj, &negative); assert(!negative); if (!is_fullspeed && #ifdef AUDIO_ENABLED !speaker_isActive() && #endif !video_isDirty() && (!disk6.motor_off && (disk_motor_time.tv_sec || disk_motor_time.tv_nsec > DISK_MOTOR_QUIET_NSECS)) ) { TIMING_LOG("auto switching to full speed"); _timing_initialize(CPU_SCALE_FASTEST); } } #endif if (!is_fullspeed) { deltat = timespec_diff(ti, tj, &negative); assert(!negative); long sleepfor = 0; if (!deltat.tv_sec) { sleepfor = EXECUTION_PERIOD_NSECS - drift_adj_nsecs - deltat.tv_nsec; } if (sleepfor <= 0) { // lagging ... static time_t throttle_warning = 0; if (t0.tv_sec - throttle_warning > 0) { TIMING_LOG("not sleeping to catch up ... %ld . %ld", deltat.tv_sec, deltat.tv_nsec); throttle_warning = t0.tv_sec; } } else { deltat.tv_sec = 0; deltat.tv_nsec = sleepfor; TRACE_CPU_BEGIN("sleep"); nanosleep(&deltat, NULL); TRACE_CPU_END(); } #if DEBUG_TIMING // collect timing statistics if (speaker_neg_feedback > cycles_speaker_feedback) { speaker_neg_feedback = cycles_speaker_feedback; } if (speaker_pos_feedback < cycles_speaker_feedback) { speaker_pos_feedback = cycles_speaker_feedback; } dbg_ticks += EXECUTION_PERIOD_NSECS; if ((dbg_ticks % NANOSECONDS_PER_SECOND) == 0) { TIMING_LOG("tick:(%ld.%ld) real:(%ld.%ld) cycles exe: %d ... speaker feedback: %d/%d", t0.tv_sec, t0.tv_nsec, ti.tv_sec, ti.tv_nsec, dbg_cycles_executed, speaker_neg_feedback, speaker_pos_feedback); dbg_cycles_executed = 0; dbg_ticks = 0; speaker_neg_feedback = 0; speaker_pos_feedback = 0; } #endif } #if !MOBILE_DEVICE if (timing_shouldAutoAdjustSpeed()) { if (is_fullspeed && ( #ifdef AUDIO_ENABLED speaker_isActive() || #endif video_isDirty() || (disk6.motor_off && (disk_motor_time.tv_sec || disk_motor_time.tv_nsec > DISK_MOTOR_QUIET_NSECS))) ) { double speed = alt_speed_enabled ? cpu_altscale_factor : cpu_scale_factor; if (speed < CPU_SCALE_FASTEST) { TIMING_LOG("auto switching to configured speed"); _timing_initialize(speed); } } } #endif if (UNLIKELY(emul_reinitialize)) { break; } #ifdef AUDIO_ENABLED if (UNLIKELY(emul_reinitialize_audio)) { break; } #endif if (UNLIKELY(cpu_shutting_down)) { break; } } while (1); if (UNLIKELY(cpu_shutting_down)) { break; } } while (1); #ifdef AUDIO_ENABLED speaker_destroy(); MB_Destroy(); audio_shutdown(); #endif return NULL; }