JpegFrameLoader::~JpegFrameLoader() { finish(); }
static int fail_socks(void) { static const struct { enum ne_sock_sversion version; enum socks_failure failure; const char *expect; const char *username, *password; } ts[] = { { NE_SOCK_SOCKSV5, fail_init_vers, "Invalid version in proxy response", NULL, NULL }, { NE_SOCK_SOCKSV5, fail_init_trunc, "Could not read initial response from proxy: Connection closed", NULL, NULL }, { NE_SOCK_SOCKSV5, fail_init_close, "Could not read initial response from proxy: Connection closed", NULL, NULL }, { NE_SOCK_SOCKSV5, fail_no_auth, "No acceptable authentication method", NULL, NULL }, { NE_SOCK_SOCKSV5, fail_bogus_auth, "Unexpected authentication method chosen", NULL, NULL }, { NE_SOCK_SOCKSV5, fail_auth_close, "Could not read login reply: Connection closed", "foo", "bar" }, { NE_SOCK_SOCKSV5, fail_auth_denied, "Authentication failed", "foo", "bar" } }; unsigned n; for (n = 0; n < sizeof(ts)/sizeof(ts[n]); n++) { ne_socket *sock; struct socks_server arg = {0}; int ret; arg.version = ts[n].version; arg.failure = ts[n].failure; arg.expect_port = 5555; arg.expect_addr = ne_iaddr_make(ne_iaddr_ipv4, raw_127); arg.username = ts[n].username; arg.password = ts[n].password; CALL(begin_socks(&sock, &arg, echo_server, NULL)); ret = ne_sock_proxy(sock, ts[n].version, arg.expect_addr, NULL, arg.expect_port, ts[n].username, ts[n].password); ONV(ret == 0, ("proxy connect #%u succeeded, expected failure '%s'", n, ts[n].expect)); if (ret != 0 && strstr(ne_sock_error(sock), ts[n].expect) == NULL) { t_warning("proxy connect #%u got unexpected failure '%s', wanted '%s'", n, ne_sock_error(sock), ts[n].expect); } ne_iaddr_free(arg.expect_addr); CALL(finish(sock, 0)); } return OK; }
void Bink::processData() { if (getTimeToNextFrame() > 0) return; if (_curFrame >= _frames.size()) { finish(); return; } VideoFrame &frame = _frames[_curFrame]; if (!_bink->seek(frame.offset)) throw Common::Exception(Common::kSeekError); uint32 frameSize = frame.size; for (uint32 i = 0; i < _audioTracks.size(); i++) { AudioTrack &audio = _audioTracks[i]; uint32 audioPacketLength = _bink->readUint32LE(); frameSize -= 4; if (frameSize < audioPacketLength) throw Common::Exception("Audio packet too big for the frame"); if (audioPacketLength >= 4) { uint32 audioPacketStart = _bink->pos(); uint32 audioPacketEnd = _bink->pos() + audioPacketLength; if (i == _audioTrack) { // Only play one audio track // Number of samples in bytes audio.sampleCount = _bink->readUint32LE() / (2 * audio.channels); audio.bits = new Common::BitStream32LELSB(new Common::SeekableSubReadStream(_bink, audioPacketStart + 4, audioPacketEnd), true); audioPacket(audio); delete audio.bits; audio.bits = 0; } _bink->seek(audioPacketEnd); frameSize -= audioPacketLength; } } uint32 videoPacketStart = _bink->pos(); uint32 videoPacketEnd = _bink->pos() + frameSize; frame.bits = new Common::BitStream32LELSB(new Common::SeekableSubReadStream(_bink, videoPacketStart, videoPacketEnd), true); videoPacket(frame); delete frame.bits; frame.bits = 0; _needCopy = true; _curFrame++; }
FLManager::~FLManager() { finish(); }
void ossimOpjCompressor::create(std::ostream* os, ossimScalarType scalar, ossim_uint32 bands, const ossimIrect& imageRect, const ossimIpt& tileSize, bool jp2) { static const char MODULE[] = "ossimOpjCompressor::create"; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_WARN) << MODULE << " entered...\n"; } #if 0 /* Please leave for debug. (drb) */ cout << "levels: " << m_levels << "\nreversible: " << m_reversible << "\nthreads: " << m_threads << "\nscalar: " << scalar << "\nbands: " << bands << "\nimageRect: " << imageRect << "\ntileSize: " << tileSize << "\njp2: " << jp2 << endl; #endif // In case we were reused. finish(); if ( !os ) { std::string errMsg = MODULE; errMsg += " ERROR: Null stream passed to method!"; throw ossimException(errMsg); } if ( !os->good() ) { std::string errMsg = MODULE; errMsg += " ERROR: Stream state has error!"; throw ossimException(errMsg); } if ( ossim::getActualBitsPerPixel(scalar) > 31 ) { // Data is not reversible. if ( m_reversible ) { std::string errMsg = MODULE; errMsg += " ERROR: Reversible processing not possible with 32 bit data!"; throw ossimException(errMsg); } } // Store for tile clip. m_imageRect = imageRect; m_stream = createOpjStream( os ); if ( !m_stream ) { std::string errMsg = MODULE; errMsg += " ERROR: OPJ stream creation failed!"; throw ossimException(errMsg); } // Requests the insertion of TLM (tile-part-length) marker. // setTlmTileCount(tilesToWrite); // Set up stream: initOpjCodingParams( jp2, tileSize, imageRect ); if ( !m_params ) { std::string errMsg = MODULE; errMsg += " ERROR: coding parameters creation failed!"; throw ossimException(errMsg); } m_codec = createOpjCodec( jp2 ); if ( !m_codec ) { std::string errMsg = MODULE; errMsg += " ERROR: code creation failed!"; throw ossimException(errMsg); } // Set rates rates/distorsion // parameters->cp_disto_alloc = 1; // ossim::print( cout, *m_params ); if (m_alpha) { if ( (bands != 1) && (bands != 3) ) { m_alpha = false; if ( traceDebug() ) { ossimNotify(ossimNotifyLevel_WARN) << "Alpha channel being unset! Can only be used with " << "one or three band data.\n" << "Source image bands: " << bands << "\n"; } } } // Create an image without allocating memory(for tile based). m_image = createOpjImage( scalar, bands, imageRect ); if ( !m_image ) { std::string errMsg = MODULE; errMsg += " ERROR: Unsupported input image type!"; throw ossimException(errMsg); } if ( !opj_setup_encoder( m_codec, m_params, m_image) ) { std::string errMsg = MODULE; errMsg += " ERROR: opj_setup_encoder failed!"; throw ossimException(errMsg); } // openJp2Codestream(); if ( traceDebug() ) { ossim::print( ossimNotify(ossimNotifyLevel_DEBUG), *m_params ); ossimNotify(ossimNotifyLevel_DEBUG) << MODULE << " exiting...\n"; } }
Engine::~Engine(){ finish(); sys->destroy(); }
~LeakCheckBase() { if (enable) finish(); }
static int test_q( struct act_q *q, tw_pe *me, void (*finish)(tw_pe *, tw_event *, char *)) { int ready, i, n; #if ROSS_MEMORY char *tmp; #endif if (!q->cur) return 0; if (MPI_Testsome( q->cur, q->req_list, &ready, q->idx_list, q->status_list) != MPI_SUCCESS) { tw_error( TW_LOC, "MPI_testsome failed with %u items in %s", q->cur, q->name); } if (1 > ready) return 0; for (i = 0; i < ready; i++) { tw_event *e; n = q->idx_list[i]; e = q->event_list[n]; q->event_list[n] = NULL; #if ROSS_MEMORY finish(me, e, q->buffers[n]); #else finish(me, e, NULL); #endif } /* Collapse the lists to remove any holes we left. */ for (i = 0, n = 0; i < q->cur; i++) { if (q->event_list[i]) { if (i != n) { // swap the event pointers q->event_list[n] = q->event_list[i]; // copy the request handles memcpy( &q->req_list[n], &q->req_list[i], sizeof(q->req_list[0])); #if ROSS_MEMORY // swap the buffers tmp = q->buffers[n]; q->buffers[n] = q->buffers[i]; q->buffers[i] = tmp; #endif } // endif (i != n) n++; } // endif (q->event_list[i]) } q->cur -= ready; return 1; }
int block(int check) { register Cojob_t* cojob; register Joblist_t* job; Rule_t* r; int n; int clear = 0; int resume = 0; if (!state.coshell || !copending(state.coshell)) { if (jobs.intermediate) { /* * mark the jobs that must be generated */ n = 0; for (job = jobs.firstjob; job; job = job->next) if (job->target->must > ((unsigned int)(job->target->dynamic & D_intermediate) != 0)) { n = 1; break; } if (n) { /* * some intermediates must be generated */ error(2, "some intermediates must be generated"); } else { /* * accept missing intermediates */ while (job = jobs.firstjob) { if (error_info.trace || state.explain) error(state.explain ? 0 : -1, "cancelling %s action -- %s", job->target->name, job->status == INTERMEDIATE ? "intermediate not needed" : "missing intermediates accepted"); job->target->status = EXISTS; discard(job); } jobs.intermediate = 0; return 1; } } return 0; } for (;;) { state.waiting = 1; if ((cojob = cowait(state.coshell, check ? (Cojob_t*)state.coshell : (Cojob_t*)0, -1)) && (job = (Joblist_t*)cojob->local)) job->cojob = 0; if (trap()) { if (state.interpreter) clear = resume = 1; if (!cojob) continue; } state.waiting = 0; if (!cojob) { if (check) return 0; break; } if (r = getrule(external.jobdone)) { if (!jobs.tmp) jobs.tmp = sfstropen(); sfprintf(jobs.tmp, "%s %d %s %s", job->target->name, cojob->status, fmtelapsed(cojob->user, CO_QUANT), fmtelapsed(cojob->sys, CO_QUANT)); call(r, sfstruse(jobs.tmp)); } if (cojob->status) { if (n = !EXITED_TERM(cojob->status) || EXIT_CODE(cojob->status)) { if ((job->target->dynamic & D_hasafter) && hasafter(job->target, P_failure)) n = 0; error(n ? 2 : state.explain ? 0 : -1, "%s%s code %d making %s%s", n ? "*** " : null, ERROR_translate(NiL, NiL, NiL, EXITED_TERM(cojob->status) ? "termination" : "exit"), EXIT_CODE(cojob->status), job->target->name, (job->flags & CO_IGNORE) ? ERROR_translate(NiL, NiL, NiL, " ignored") : null); } if (!(job->flags & CO_IGNORE)) { job->flags |= CO_ERRORS; if (state.keepgoing || !n) { if (n) state.errors++; job->flags |= CO_KEEPGOING; } } if (state.interrupt || !(job->flags & (CO_IGNORE|CO_KEEPGOING))) clear = 1; } message((-3, "job: %s: interrupt=%d clear=%d status=%d flags=%08x", job->target->name, state.interrupt, clear, cojob->status, job->flags)); /* * job is done */ if (done(job, clear, cojob)) return 1; } if (resume) longjmp(state.resume.label, 1); if (!state.finish) { if (!copending(state.coshell)) { if (clear) finish(1); } else if (!state.interrupt) error(3, "lost contact with coshell"); } return 0; }
void AIFetchInventoryFolder::multiplex_impl(void) { switch (mRunState) { case AIFetchInventoryFolder_checkFolderExists: { // If LLInventoryModel_mIsAgentInvUsable_true then this should be and stay true forever. llassert(gInventory.isInventoryUsable()); if (mParentFolder.isNull()) mParentFolder = gAgent.getInventoryRootID(); if (mFolderUUID.isNull() || !gInventory.getCategory(mFolderUUID)) // Is the UUID unknown, or doesn't exist? { // Set this to null here in case we abort. mFolderUUID.setNull(); if (mFolderName.empty()) { // We can only find a folder by name, or create it, if we know it's name. llwarns << "Unknown folder ID " << mFolderUUID << llendl; abort(); break; } // Check if the parent exists. if (mParentFolder != gAgent.getInventoryRootID() && !gInventory.getCategory(mParentFolder)) { llwarns << "Unknown parent folder ID " << mParentFolder << llendl; abort(); break; } // Look up UUID by name. LLInventoryModel::cat_array_t* categories; gInventory.getDirectDescendentsOf(mParentFolder, categories); for (S32 i = 0; i < categories->getLength(); ++i) { LLPointer<LLViewerInventoryCategory> const& category(categories->get(i)); if (category->getName() == mFolderName) { mFolderUUID = category->getUUID(); break; } } if (mFolderUUID.isNull()) // Does the folder exist? { if (!mCreate) { // We're done. finish(); break; } // Create the folder. mFolderUUID = gInventory.createNewCategory(mParentFolder, LLFolderType::FT_NONE, mFolderName); llassert_always(!mFolderUUID.isNull()); Dout(dc::statemachine, "Created folder \"" << mFolderName << "\"."); mNeedNotifyObservers = true; } mCreated = true; } // mFolderUUID is now valid. mExists = true; if (!mFetchContents || // No request to fetch contents. LLInventoryModel::isEverythingFetched()) // No need to fetch contents. { // We're done. finish(); break; } set_state(AIFetchInventoryFolder_fetchDescendents); /*Fall-through*/ } case AIFetchInventoryFolder_fetchDescendents: { // This sets the state to AIFetchInventoryFolder_folderCompleted once the folder is complete. new AIInventoryFetchDescendentsObserver(this, mFolderUUID); break; } case AIFetchInventoryFolder_folderCompleted: { // Does it still exist? if (!gInventory.getCategory(mFolderUUID)) { // Assume the folder was deleted in the meantime. abort(); break; } llassert(gInventory.isCategoryComplete(mFolderUUID)); // The folder is complete! finish(); break; } } }
int main(int argc, char** argv) { int argn; int start; #define START_NONE 0 #define START_PARALLEL 1 #define START_RATE 2 int start_parallel = -1, start_rate = -1; int end; #define END_NONE 0 #define END_FETCHES 1 #define END_SECONDS 2 int end_fetches = -1, end_seconds = -1; int cnum; char* url_file; char* sip_file; #ifdef RLIMIT_NOFILE struct rlimit limits; #endif /* RLIMIT_NOFILE */ fd_set rfdset; fd_set wfdset; struct timeval now; int i, r; max_connections = 64 - RESERVED_FDS; /* a guess */ #ifdef RLIMIT_NOFILE /* Try and increase the limit on # of files to the maximum. */ if (getrlimit(RLIMIT_NOFILE, &limits) == 0) { if (limits.rlim_cur != limits.rlim_max) { if (limits.rlim_max == RLIM_INFINITY) limits.rlim_cur = 8192; /* arbitrary */ else if (limits.rlim_max > limits.rlim_cur) limits.rlim_cur = limits.rlim_max; (void)setrlimit(RLIMIT_NOFILE, &limits); } max_connections = limits.rlim_cur - RESERVED_FDS; } #endif /* RLIMIT_NOFILE */ /* Parse args. */ argv0 = argv[0]; argn = 1; do_checksum = do_throttle = do_verbose = do_jitter = do_proxy = 0; throttle = THROTTLE; sip_file = (char*)0; idle_secs = IDLE_SECS; start = START_NONE; end = END_NONE; while (argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0') { if (strncmp(argv[argn], "-checksum", strlen(argv[argn])) == 0) do_checksum = 1; else if (strncmp(argv[argn], "-throttle", strlen(argv[argn])) == 0) do_throttle = 1; else if (strncmp(argv[argn], "-Throttle", strlen(argv[argn])) == 0 && argn + 1 < argc) { do_throttle = 1; throttle = atoi(argv[++argn]) / 10.0; } else if (strncmp(argv[argn], "-verbose", strlen(argv[argn])) == 0) do_verbose = 1; else if (strncmp(argv[argn], "-timeout", strlen(argv[argn])) == 0 && argn + 1 < argc) idle_secs = atoi(argv[++argn]); else if (strncmp(argv[argn], "-jitter", strlen(argv[argn])) == 0) do_jitter = 1; else if (strncmp(argv[argn], "-parallel", strlen(argv[argn])) == 0 && argn + 1 < argc) { start = START_PARALLEL; start_parallel = atoi(argv[++argn]); if (start_parallel < 1) { (void)fprintf(stderr, "%s: parallel must be at least 1\n", argv0); exit(1); } if (start_parallel > max_connections) { (void)fprintf(stderr, "%s: parallel may be at most %d\n", argv0, max_connections); exit(1); } } else if (strncmp(argv[argn], "-rate", strlen(argv[argn])) == 0 && argn + 1 < argc) { start = START_RATE; start_rate = atoi(argv[++argn]); if (start_rate < 1) { (void)fprintf(stderr, "%s: rate must be at least 1\n", argv0); exit(1); } if (start_rate > 1000) { (void)fprintf(stderr, "%s: rate may be at most 1000\n", argv0); exit(1); } } else if (strncmp(argv[argn], "-fetches", strlen(argv[argn])) == 0 && argn + 1 < argc) { end = END_FETCHES; end_fetches = atoi(argv[++argn]); if (end_fetches < 1) { (void)fprintf(stderr, "%s: fetches must be at least 1\n", argv0); exit(1); } } else if (strncmp(argv[argn], "-seconds", strlen(argv[argn])) == 0 && argn + 1 < argc) { end = END_SECONDS; end_seconds = atoi(argv[++argn]); if (end_seconds < 1) { (void)fprintf(stderr, "%s: seconds must be at least 1\n", argv0); exit(1); } } else if (strncmp(argv[argn], "-sip", strlen(argv[argn])) == 0 && argn + 1 < argc) sip_file = argv[++argn]; #ifdef USE_SSL else if ( strncmp( argv[argn], "-cipher", strlen( argv[argn] ) ) == 0 && argn + 1 < argc ) { cipher = argv[++argn]; if ( strcasecmp( cipher, "fastsec" ) == 0 ) cipher = "RC4-MD5"; else if ( strcasecmp( cipher, "highsec" ) == 0 ) cipher = "DES-CBC3-SHA"; else if ( strcasecmp( cipher, "paranoid" ) == 0 ) cipher = "AES256-SHA"; } #endif /* USE_SSL */ else if (strncmp(argv[argn], "-proxy", strlen(argv[argn])) == 0 && argn + 1 < argc) { char* colon; do_proxy = 1; proxy_hostname = argv[++argn]; colon = strchr(proxy_hostname, ':'); if (colon == (char*)0) proxy_port = 80; else { proxy_port = (unsigned short)atoi(colon + 1); *colon = '\0'; } } else usage(); ++argn; } if (argn + 1 != argc) usage(); if (start == START_NONE || end == END_NONE) usage(); if (do_jitter && start != START_RATE) usage(); url_file = argv[argn]; /* Read in and parse the URLs. */ read_url_file(url_file); /* Read in the source IP file, if specified. */ if (sip_file != (char*)0) read_sip_file(sip_file); /* Initialize the connections table. */ if (start == START_PARALLEL) max_connections = start_parallel; connections = (connection*)malloc_check( max_connections * sizeof(connection)); for (cnum = 0; cnum < max_connections; ++cnum) connections[cnum].conn_state = CNST_FREE; num_connections = max_parallel = 0; /* Initialize the HTTP status-code histogram. */ for (i = 0; i < 1000; ++i) http_status_counts[i] = 0; /* Initialize the statistics. */ fetches_started = 0; connects_completed = 0; responses_completed = 0; fetches_completed = 0; total_bytes = 0; total_connect_usecs = 0; max_connect_usecs = 0; min_connect_usecs = 1000000000L; total_response_usecs = 0; max_response_usecs = 0; min_response_usecs = 1000000000L; total_timeouts = 0; total_badbytes = 0; total_badchecksums = 0; /* Initialize the random number generator. */ #ifdef HAVE_SRANDOMDEV srandomdev(); #else srandom((int)time((time_t*)0) ^ getpid()); #endif /* Initialize the rest. */ tmr_init(); (void)gettimeofday(&now, (struct timezone*)0); start_at = now; if (do_verbose) (void)tmr_create(&now, progress_report, JunkClientData, PROGRESS_SECS * 1000L, 1); if (start == START_RATE) { start_interval = 1000L / start_rate; if (do_jitter) { low_interval = start_interval * 9 / 10; high_interval = start_interval * 11 / 10; range_interval = high_interval - low_interval + 1; } (void)tmr_create(&now, start_timer, JunkClientData, start_interval, !do_jitter); } if (end == END_SECONDS) (void)tmr_create(&now, end_timer, JunkClientData, end_seconds * 1000L, 0); (void)signal(SIGPIPE, SIG_IGN); /* Main loop. */ for (;;) { if (end == END_FETCHES && fetches_completed >= end_fetches) finish(&now); if (start == START_PARALLEL) { /* See if we need to start any new connections; but at most 10. */ for (i = 0; i < 10 && num_connections < start_parallel && (end != END_FETCHES || fetches_started < end_fetches); ++i) { start_connection(&now); (void)gettimeofday(&now, (struct timezone*)0); tmr_run(&now); } } /* Build the fdsets. */ FD_ZERO( &rfdset); FD_ZERO( &wfdset); for (cnum = 0; cnum < max_connections; ++cnum) { switch (connections[cnum].conn_state) { case CNST_CONNECTING: FD_SET( connections[cnum].conn_fd, &wfdset); break; case CNST_HEADERS: case CNST_READING: FD_SET( connections[cnum].conn_fd, &rfdset); break; } } r = select(FD_SETSIZE, &rfdset, &wfdset, (fd_set*)0, tmr_timeout(&now)); if (__builtin_expect(r < 0, 0)) { perror("select"); exit(1); } (void)gettimeofday(&now, (struct timezone*)0); /* Service them. */ for (cnum = 0; cnum < max_connections; ++cnum) { switch (connections[cnum].conn_state) { case CNST_CONNECTING: if (FD_ISSET( connections[cnum].conn_fd, &wfdset )) handle_connect(cnum, &now, 1); break; case CNST_HEADERS: case CNST_READING: if (FD_ISSET( connections[cnum].conn_fd, &rfdset )) handle_read(cnum, &now); break; } } /* And run the timers. */ tmr_run(&now); } /* NOT_REACHED */ }
int main(int argc, char *argv[]) { int c, nostop=0; char *h; int i_rc = 0; cd_operation_t cd_op = NO_OP; /* operation to do in non-interactive mode */ psz_program = strrchr(argv[0],'/'); psz_program = psz_program ? psz_program+1 : argv[0]; memset(&cddb_opts, 0, sizeof(cddb_opts)); cdio_loglevel_default = CDIO_LOG_WARN; /* parse options */ while ( 1 ) { if (-1 == (c = getopt(argc, argv, "acCdehkplL:sSt:vx"))) break; switch (c) { case 'v': b_verbose = true; if (cdio_loglevel_default > CDIO_LOG_INFO) cdio_loglevel_default = CDIO_LOG_INFO; break; case 'd': debug = 1; if (cdio_loglevel_default > CDIO_LOG_DEBUG) cdio_loglevel_default = CDIO_LOG_DEBUG; break; case 'a': auto_mode = 1; break; case 'L': i_volume_level = atoi(optarg); cd_op = SET_VOLUME; b_interactive = false; break; case 't': if (NULL != (h = strchr(optarg,'-'))) { *h = 0; start_track = atoi(optarg); stop_track = atoi(h+1)+1; if (0 == start_track) start_track = 1; if (1 == stop_track) stop_track = CDIO_CDROM_LEADOUT_TRACK; } else { start_track = atoi(optarg); stop_track = start_track+1; one_track = 1; } b_interactive = false; cd_op = PLAY_TRACK; break; case 'p': b_interactive = false; cd_op = PLAY_CD; break; case 'l': b_interactive = false; cd_op = LIST_TRACKS; break; case 'C': b_interactive = false; cd_op = CLOSE_CD; break; case 'c': b_interactive = false; cd_op = PS_LIST_TRACKS; break; case 's': b_interactive = false; cd_op = STOP_PLAYING; break; case 'S': b_interactive = false; cd_op = LIST_SUBCHANNEL; break; case 'e': b_interactive = false; cd_op = EJECT_CD; break; case 'k': print_keys(); exit(1); case 'h': usage(psz_program); exit(1); default: usage(psz_program); exit(1); } } if (argc > optind) { psz_device = strdup(argv[optind]); } else { char **ppsz_cdda_drives=NULL; char **ppsz_all_cd_drives = cdio_get_devices_ret(&driver_id); if (!ppsz_all_cd_drives) { fprintf(stderr, "Can't find a CD-ROM drive\n"); exit(2); } ppsz_cdda_drives = cdio_get_devices_with_cap(ppsz_all_cd_drives, CDIO_FS_AUDIO, false); if (!ppsz_cdda_drives || !ppsz_cdda_drives[0]) { fprintf(stderr, "Can't find a CD-ROM drive with a CD-DA in it\n"); exit(3); } psz_device = strdup(ppsz_cdda_drives[0]); cdio_free_device_list(ppsz_all_cd_drives); cdio_free_device_list(ppsz_cdda_drives); } if (!b_interactive) { b_sig = true; nostop=1; } tty_raw(); signal(SIGINT,ctrlc); signal(SIGQUIT,ctrlc); signal(SIGTERM,ctrlc); signal(SIGHUP,ctrlc); signal(SIGWINCH, sigwinch); if (CLOSE_CD != cd_op) { /* open device */ if (b_verbose) fprintf(stderr, "open %s... ", psz_device); p_cdio = cdio_open (psz_device, driver_id); if (!p_cdio && cd_op != EJECT_CD) { cd_close(psz_device); p_cdio = cdio_open (psz_device, driver_id); } if (p_cdio && b_verbose) fprintf(stderr,"ok\n"); } if (b_interactive) { #ifdef HAVE_CDDB cddb_log_set_handler (cddb_log_handler); #else ; #endif } else { b_sig = true; nostop=1; if (EJECT_CD == cd_op) { i_rc = cd_eject() ? 0 : 1; } else { switch (cd_op) { case PS_LIST_TRACKS: case LIST_TRACKS: case PLAY_TRACK: read_toc(p_cdio); default: break; } if (p_cdio) switch (cd_op) { case STOP_PLAYING: b_cd = true; i_rc = cd_stop(p_cdio) ? 0 : 1; break; case EJECT_CD: /* Should have been handled above. */ cd_eject(); break; case LIST_TRACKS: list_tracks(); break; case PS_LIST_TRACKS: ps_list_tracks(); break; case PLAY_TRACK: /* play just this one track */ if (b_record) { printf("%s / %s\n", artist, title); if (one_track) printf("%s\n", cd_info[start_track].title); } i_rc = play_track(start_track, stop_track) ? 0 : 1; break; case PLAY_CD: if (b_record) printf("%s / %s\n", artist, title); play_track(1,CDIO_CDROM_LEADOUT_TRACK); break; case SET_VOLUME: i_rc = set_volume_level(p_cdio, i_volume_level); break; case LIST_SUBCHANNEL: if (read_subchannel(p_cdio)) { if (sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED || sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) { { printf("track %2d - %02x:%02x (%02x:%02x abs) ", sub.track, sub.rel_addr.m, sub.rel_addr.s, sub.abs_addr.m, sub.abs_addr.s); } } printf("drive state: %s\n", mmc_audio_state2str(sub.audio_status)); } else { i_rc = 1; } break; case CLOSE_CD: /* Handled below */ case LIST_KEYS: case TOGGLE_PAUSE: case EXIT_PROGRAM: case NO_OP: break; } else if (CLOSE_CD == cd_op) { i_rc = (DRIVER_OP_SUCCESS == cdio_close_tray(psz_device, NULL)) ? 0 : 1; } else { fprintf(stderr,"no CD in drive (%s)\n", psz_device); } } } /* Play all tracks *unless* we have a play or paused status already. */ read_subchannel(p_cdio); if (sub.audio_status != CDIO_MMC_READ_SUB_ST_PAUSED && sub.audio_status != CDIO_MMC_READ_SUB_ST_PLAY) play_track(1, CDIO_CDROM_LEADOUT_TRACK); while ( !b_sig ) { int key; if (!b_cd) read_toc(p_cdio); read_subchannel(p_cdio); display_status(false); if (1 == select_wait(b_cd ? 1 : 5)) { switch (key = getch()) { case '-': decrease_volume_level(p_cdio); break; case '+': increase_volume_level(p_cdio); break; case 'A': case 'a': auto_mode = !auto_mode; break; case 'X': case 'x': nostop=1; /* fall through */ case 'Q': case 'q': b_sig = true; break; case 'E': case 'e': cd_eject(); break; case 's': cd_stop(p_cdio); break; case 'C': case 'c': cd_close(psz_device); break; case 'L': case 'l': b_all_tracks = !b_all_tracks; if (b_all_tracks) display_tracks(); else { i_last_display_track = CDIO_INVALID_TRACK; display_cdinfo(p_cdio, i_tracks, i_first_track); } break; case 'K': case 'k': case 'h': case 'H': case '?': list_keys(); break; case ' ': case 'P': case 'p': toggle_pause(); break; case KEY_RIGHT: if (b_cd && (sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED || sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY)) play_track(sub.track+1, CDIO_CDROM_LEADOUT_TRACK); else play_track(1,CDIO_CDROM_LEADOUT_TRACK); break; case KEY_LEFT: if (b_cd && (sub.audio_status == CDIO_MMC_READ_SUB_ST_PAUSED || sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY)) play_track(sub.track-1,CDIO_CDROM_LEADOUT_TRACK); break; case KEY_UP: if (b_cd && sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) skip(10); break; case KEY_DOWN: if (b_cd && sub.audio_status == CDIO_MMC_READ_SUB_ST_PLAY) skip(-10); break; case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': play_track(key - '0', CDIO_CDROM_LEADOUT_TRACK); break; case '0': play_track(10, CDIO_CDROM_LEADOUT_TRACK); break; case KEY_F(1): case KEY_F(2): case KEY_F(3): case KEY_F(4): case KEY_F(5): case KEY_F(6): case KEY_F(7): case KEY_F(8): case KEY_F(9): case KEY_F(10): case KEY_F(11): case KEY_F(12): case KEY_F(13): case KEY_F(14): case KEY_F(15): case KEY_F(16): case KEY_F(17): case KEY_F(18): case KEY_F(19): case KEY_F(20): play_track(key - KEY_F(1) + 11, CDIO_CDROM_LEADOUT_TRACK); break; } } } if (!nostop) cd_stop(p_cdio); tty_restore(); finish("bye", i_rc); return 0; /* keep compiler happy */ }
void GLC_Cone::createMeshAndWire() { Q_ASSERT(GLC_Mesh::isEmpty()); Q_ASSERT(m_WireData.isEmpty()); // Create cosinus and sinus array according to the discretion and radius const int vertexNumber= m_Discret + 1; // Normals values QVector<float> cosNormalArray(vertexNumber); QVector<float> sinNormalArray(vertexNumber); QVector<float> cosArray(vertexNumber); QVector<float> sinArray(vertexNumber); const double angle= (2.0 * glc::PI) / static_cast<double>(m_Discret); // Normal Z value GLC_Vector3d normalVector(1.0, 0.0, 0.0); GLC_Matrix4x4 rotation(glc::Y_AXIS, -atan(m_Radius / m_Length)); normalVector= rotation * normalVector; const float normalZ= static_cast<float>(normalVector.z()); const double factor= normalVector.x(); // Normailsation factor for (int i= 0; i < vertexNumber; ++i) { const double cosValue= cos(static_cast<double>(i) * angle); const double sinValue= sin(static_cast<double>(i) * angle); cosNormalArray[i]= static_cast<GLfloat>(factor * cosValue); sinNormalArray[i]= static_cast<GLfloat>(factor * sinValue); cosArray[i]= static_cast<GLfloat>(m_Radius * cosValue); sinArray[i]= static_cast<GLfloat>(m_Radius * sinValue); } // Mesh Data GLfloatVector verticeVector; GLfloatVector normalsVector; GLfloatVector texelVector; // Wire Data GLfloatVector bottomWireData(vertexNumber * 3); const int size= vertexNumber * 3; verticeVector.resize(3 * size); normalsVector.resize(3 * size); texelVector.resize(2 * size); for (int i= 0; i < vertexNumber; ++i) { // Bottom Mesh verticeVector[3 * i]= cosArray[i]; verticeVector[3 * i + 1]= sinArray[i]; verticeVector[3 * i + 2]= 0.0f; normalsVector[3 * i]= cosNormalArray[i]; normalsVector[3 * i + 1]= sinNormalArray[i]; normalsVector[3 * i + 2]= normalZ; texelVector[2 * i]= static_cast<float>(i) / static_cast<float>(m_Discret); texelVector[2 * i + 1]= 0.0f; // Bottom Wire bottomWireData[3 * i]= cosArray[i]; bottomWireData[3 * i + 1]= sinArray[i]; bottomWireData[3 * i + 2]= 0.0f; // Top verticeVector[3 * i + 3 * vertexNumber]= 0.0f; verticeVector[3 * i + 1 + 3 * vertexNumber]= 0.0f; verticeVector[3 * i + 2 + 3 * vertexNumber]= static_cast<float>(m_Length); normalsVector[3 * i + 3 * vertexNumber]= cosNormalArray[i]; normalsVector[3 * i + 1 + 3 * vertexNumber]= sinNormalArray[i]; normalsVector[3 * i + 2 + 3 * vertexNumber]= normalZ; texelVector[2 * i + 2 * vertexNumber]= texelVector[i]; texelVector[2 * i + 1 + 2 * vertexNumber]= 1.0f; // Bottom Cap ends verticeVector[3 * i + 2 * 3 * vertexNumber]= cosArray[i]; verticeVector[3 * i + 1 + 2 * 3 * vertexNumber]= sinArray[i]; verticeVector[3 * i + 2 + 2 * 3 * vertexNumber]= 0.0f; normalsVector[3 * i + 2 * 3 * vertexNumber]= 0.0f; normalsVector[3 * i + 1 + 2 * 3 * vertexNumber]= 0.0f; normalsVector[3 * i + 2 + 2 * 3 * vertexNumber]= -1.0f; texelVector[2 * i + 2 * 2 * vertexNumber]= texelVector[i]; texelVector[2 * i + 1 + 2 * 2 * vertexNumber]= 0.0f; } // Add bulk data in to the mesh GLC_Mesh::addVertice(verticeVector); GLC_Mesh::addNormals(normalsVector); GLC_Mesh::addTexels(texelVector); // Add polyline to wire data GLC_Geometry::addVerticeGroup(bottomWireData); // Set the material to use GLC_Material* pCylinderMaterial; if (hasMaterial()) { pCylinderMaterial= this->firstMaterial(); } else { pCylinderMaterial= new GLC_Material(); } IndexList circumferenceStrips; // Create the index for (int i= 0; i < vertexNumber; ++i) { circumferenceStrips.append(i + vertexNumber); circumferenceStrips.append(i); } addTrianglesStrip(pCylinderMaterial, circumferenceStrips); { IndexList bottomCap; IndexList topCap; int id1= 0; int id2= m_Discret - 1; const int size= m_Discret / 2 + (m_Discret % 2); for (int i= 0; i < size; ++i) { bottomCap.append(id1 + 2 * vertexNumber); bottomCap.append(id2 + 2 * vertexNumber); id1+= 1; id2-= 1; } addTrianglesStrip(pCylinderMaterial, bottomCap); } finish(); }
static int compute_alpha_shape(char* sql, vertex_t **res, int *res_count) { int SPIcode; void *SPIplan; Portal SPIportal; bool moredata = TRUE; int ntuples; vertex_t *vertices = NULL; int total_tuples = 0; vertex_columns_t vertex_columns = {.id= -1, .x= -1, .y= -1}; char *err_msg; int ret = -1; DBG("start alpha_shape\n"); SPIcode = SPI_connect(); if (SPIcode != SPI_OK_CONNECT) { elog(ERROR, "alpha_shape: couldn't open a connection to SPI"); return -1; } SPIplan = SPI_prepare(sql, 0, NULL); if (SPIplan == NULL) { elog(ERROR, "alpha_shape: couldn't create query plan via SPI"); return -1; } if ((SPIportal = SPI_cursor_open(NULL, SPIplan, NULL, NULL, true)) == NULL) { elog(ERROR, "alpha_shape: SPI_cursor_open('%s') returns NULL", sql); return -1; } while (moredata == TRUE) { SPI_cursor_fetch(SPIportal, TRUE, TUPLIMIT); if (vertex_columns.id == -1) { if (fetch_vertices_columns(SPI_tuptable, &vertex_columns) == -1) return finish(SPIcode, ret); } ntuples = SPI_processed; total_tuples += ntuples; if (!vertices) vertices = palloc(total_tuples * sizeof(vertex_t)); else vertices = repalloc(vertices, total_tuples * sizeof(vertex_t)); if (vertices == NULL) { elog(ERROR, "Out of memory"); return finish(SPIcode, ret); } if (ntuples > 0) { int t; SPITupleTable *tuptable = SPI_tuptable; TupleDesc tupdesc = SPI_tuptable->tupdesc; for (t = 0; t < ntuples; t++) { HeapTuple tuple = tuptable->vals[t]; fetch_vertex(&tuple, &tupdesc, &vertex_columns, &vertices[total_tuples - ntuples + t]); } SPI_freetuptable(tuptable); } else { moredata = FALSE; } } // if (total_tuples < 2) //this was the buggy code of the pgrouting project. // TODO: report this as a bug to the pgrouting project // the CGAL alpha-shape function crashes if called with less than three points!!! if (total_tuples == 0) { elog(ERROR, "Distance is too short. no vertex for alpha shape calculation. alpha shape calculation needs at least 3 vertices."); } if (total_tuples == 1) { elog(ERROR, "Distance is too short. only 1 vertex for alpha shape calculation. alpha shape calculation needs at least 3 vertices."); } if (total_tuples == 2) { elog(ERROR, "Distance is too short. only 2 vertices for alpha shape calculation. alpha shape calculation needs at least 3 vertices."); } if (total_tuples < 3) { // elog(ERROR, "Distance is too short ...."); return finish(SPIcode, ret); } DBG("Calling CGAL alpha-shape\n"); profstop("extract", prof_extract); profstart(prof_alpha); ret = alpha_shape(vertices, total_tuples, res, res_count, &err_msg); profstop("alpha", prof_alpha); profstart(prof_store); if (ret < 0) { //elog(ERROR, "Error computing shape: %s", err_msg); ereport(ERROR, (errcode(ERRCODE_E_R_E_CONTAINING_SQL_NOT_PERMITTED), errmsg("Error computing shape: %s", err_msg))); } return finish(SPIcode, ret); } PG_FUNCTION_INFO_V1(alphashape); Datum alphashape(PG_FUNCTION_ARGS) { FuncCallContext *funcctx; int call_cntr; int max_calls; TupleDesc tuple_desc; vertex_t *res = 0; /* stuff done only on the first call of the function */ if (SRF_IS_FIRSTCALL()) { MemoryContext oldcontext; int res_count; int ret; // XXX profiling messages are not thread safe profstart(prof_total); profstart(prof_extract); /* create a function context for cross-call persistence */ funcctx = SRF_FIRSTCALL_INIT(); /* switch to memory context appropriate for multiple function calls */ oldcontext = MemoryContextSwitchTo(funcctx->multi_call_memory_ctx); ret = compute_alpha_shape(text2char(PG_GETARG_TEXT_P(0)), &res, &res_count); /* total number of tuples to be returned */ DBG("Conting tuples number\n"); funcctx->max_calls = res_count; funcctx->user_fctx = res; DBG("Total count %i", res_count); if (get_call_result_type(fcinfo, NULL, &tuple_desc) != TYPEFUNC_COMPOSITE) ereport(ERROR, (errcode(ERRCODE_FEATURE_NOT_SUPPORTED), errmsg("function returning record called in context " "that cannot accept type record"))); funcctx->tuple_desc = BlessTupleDesc(tuple_desc); MemoryContextSwitchTo(oldcontext); } /* stuff done on every call of the function */ DBG("Strange stuff doing\n"); funcctx = SRF_PERCALL_SETUP(); call_cntr = funcctx->call_cntr; max_calls = funcctx->max_calls; tuple_desc = funcctx->tuple_desc; res = (vertex_t*) funcctx->user_fctx; DBG("Trying to allocate some memory\n"); if (call_cntr < max_calls) /* do when there is more left to send */ { HeapTuple tuple; Datum result; Datum *values; char* nulls; /* This will work for some compilers. If it crashes with segfault, try to change the following block with this one values = palloc(3 * sizeof(Datum)); nulls = palloc(3 * sizeof(char)); values[0] = call_cntr; nulls[0] = ' '; values[1] = Float8GetDatum(res[call_cntr].x); nulls[1] = ' '; values[2] = Float8GetDatum(res[call_cntr].y); nulls[2] = ' '; */ values = palloc(2 * sizeof(Datum)); nulls = palloc(2 * sizeof(char)); values[0] = Float8GetDatum(res[call_cntr].x); nulls[0] = ' '; values[1] = Float8GetDatum(res[call_cntr].y); nulls[1] = ' '; DBG("Heap making\n"); tuple = heap_formtuple(tuple_desc, values, nulls); DBG("Datum making\n"); /* make the tuple into a datum */ result = HeapTupleGetDatum(tuple); DBG("Trying to free some memory\n"); /* clean up (this is not really necessary) */ pfree(values); pfree(nulls); SRF_RETURN_NEXT(funcctx, result); } else /* do when there is no more left */ { if (res) free(res); profstop("store", prof_store); profstop("total", prof_total); #ifdef PROFILE elog(NOTICE, "_________"); #endif SRF_RETURN_DONE(funcctx); } }
inline void set_finished() { state.process_event(finish()); }
propt::resultt dplib_propt::prop_solve() { finish(); return P_ERROR; }
virtual ~statement() { finish(); }
void instance::on_end_block_phase(const Event& evt) { log_->debugStream() << "starting battle, I have " << attackers_.size() << " attackers and " << blockers_.size () << " units being blocked"; // 1) tell the clients to start rendering the combat based on what they received // so far broadcast(evt); // 2) calculate the combat outcome /* * for all unit X in attackers_ do: * for all blocker Y for X in blockers_ do: * - attack(X,Y) * - if X is dead, break and get next X * - if Y is dead, get next Y * for all dead unit Z do: * - detach from puppet */ for (auto attacker : attackers_) { attacker->reset(); blockers_t::iterator blockers = blockers_.find(attacker); if (blockers != blockers_.end()) { for (auto blocker : blockers->second) { blocker->reset(); attacker->attack(blocker, true); if (blocker->isDead()) death_list_.push_back(blocker); if (attacker->isDead()) { death_list_.push_back(attacker); break; } } } else { // no blockers std::cout << "attacker " << attacker->getUID() << " is attacking puppet " << waiting_puppet_->getName() << " which has " << waiting_puppet_->getHP(); attacker->attack(waiting_puppet_.get()); std::cout << " and is dead? " << (waiting_puppet_->isDead() ? "yes" : "no") << "\n"; if (waiting_puppet_->isDead()) { // game over return finish(active_puppet_); } } } log_->debugStream() << "calculating battle results"; // rest what's left of the attackers for (auto unit : attackers_) unit->rest(); // clean up dead units log_->debugStream() << death_list_.size() << " dead units"; for (auto unit : death_list_) _destroy_unit(unit->getUID()); //static_cast<Puppet*>((Entity*)unit->getOwner())->detachUnit(unit->getUID()); // clear combat temps death_list_.clear(); attackers_.clear(); blockers_.clear(); log_->debugStream() << "waiting for the blocker to start their turn"; // 3) re-start the on_end_turn routine //~ Event tmp(EventUID::EndTurn); //~ tmp.Sender = active_player_; //~ on_end_turn(tmp); // 4) wait for the blocker to acknowledge and start the new turn // (nothing to do) }
void Single_Player::click() { if(is_in(ui->x->text().toInt(),ui->y->text().toInt())==true) { if(turn==black) { set(ui->x->text().toInt(),ui->y->text().toInt(),turn); change_taw(ui->x->text().toInt(),ui->y->text().toInt(),Black); turn=white; Modify(); check(white); if(size>0) { int x2=rand()%size; if(is_in(white_movement[x2][0],white_movement[x2][1])) set(white_movement[x2][0],white_movement[x2][1],white); else { QMessageBox *msg=new QMessageBox(); msg->setText("Illegal movement"); msg->show(); } change_taw(white_movement[x2][0],white_movement[x2][1],White); } turn=black; Modify(); check(black); ui->label->setText("Black"); } else if(turn==white) { set(ui->x->text().toInt(),ui->y->text().toInt(),turn); change_taw(ui->x->text().toInt(),ui->y->text().toInt(),White); turn=black; Modify(); check(black); if(size>0) { int x2=rand()%size; if(is_in(black_movement[x2][0],black_movement[x2][1])) set(black_movement[x2][0],black_movement[x2][1],black); else { QMessageBox *msg=new QMessageBox(); msg->setText("Illegal movement"); msg->show(); } change_taw(black_movement[x2][0],black_movement[x2][1],Black); } turn=white; Modify(); check(white); ui->label->setText("White"); } } else { QMessageBox *msg=new QMessageBox(); msg->setText("Wrong move"); msg->show(); } count_black_white(); if (finish()==true) { QMessageBox *msg=new QMessageBox(); if(count_black_white()==true) msg->setText("White Win"); else msg->setText("Black win"); msg->show(); ui->pushButton->setEnabled(false); } }
void player_activity::do_turn( player *p ) { switch( type ) { case ACT_WAIT: case ACT_WAIT_NPC: case ACT_WAIT_WEATHER: // Based on time, not speed moves_left -= 100; p->rooted(); p->pause(); break; case ACT_PICKAXE: // Based on speed, not time if( p->moves <= moves_left ) { moves_left -= p->moves; p->moves = 0; } else { p->moves -= moves_left; moves_left = 0; } activity_handlers::pickaxe_do_turn( this, p ); break; case ACT_BURROW: // Based on speed, not time if( p->moves <= moves_left ) { moves_left -= p->moves; p->moves = 0; } else { p->moves -= moves_left; moves_left = 0; } activity_handlers::burrow_do_turn( this, p ); break; case ACT_AIM: if( index == 0 ) { if( !p->weapon.is_gun() ) { // We lost our gun somehow, bail out. type = ACT_NULL; break; } g->m.build_map_cache( g->get_levz() ); g->plfire(); } break; case ACT_GAME: // Takes care of u.activity.moves_left activity_handlers::game_do_turn( this, p ); break; case ACT_VIBE: // Takes care of u.activity.moves_left activity_handlers::vibe_do_turn( this, p ); break; case ACT_REFILL_VEHICLE: type = ACT_NULL; // activity is not used anymore. break; case ACT_PULP: // does not really use u.activity.moves_left, stops itself when finished activity_handlers::pulp_do_turn( this, p ); break; case ACT_FISH: // Based on time, not speed--or it should be // (Being faster doesn't make the fish bite quicker) moves_left -= 100; p->rooted(); p->pause(); break; case ACT_DROP: activity_on_turn_drop(); break; case ACT_STASH: activity_on_turn_stash(); break; case ACT_PICKUP: activity_on_turn_pickup(); break; case ACT_MOVE_ITEMS: activity_on_turn_move_items(); break; case ACT_ADV_INVENTORY: p->cancel_activity(); advanced_inv(); break; case ACT_ARMOR_LAYERS: p->cancel_activity(); p->sort_armor(); break; case ACT_START_FIRE: moves_left -= 100; // based on time if( p->i_at( position ).has_flag( "LENS" ) ) { // if using a lens, handle potential changes in weather activity_handlers::start_fire_lens_do_turn( this, p ); } p->rooted(); p->pause(); break; case ACT_OPEN_GATE: // Based on speed, not time if( p->moves <= moves_left ) { moves_left -= p->moves; p->moves = 0; } else { p->moves -= moves_left; moves_left = 0; } break; case ACT_FILL_LIQUID: activity_handlers::fill_liquid_do_turn( this, p ); break; case ACT_ATM: iexamine::atm( *p, p->pos() ); break; case ACT_START_ENGINES: moves_left -= 100; p->rooted(); p->pause(); break; case ACT_OXYTORCH: if( p->moves <= moves_left ) { moves_left -= p->moves; p->moves = 0; } else { p->moves -= moves_left; moves_left = 0; } if( values[0] > 0 ) { activity_handlers::oxytorch_do_turn( this, p ); } break; case ACT_CRACKING: if( !( p->has_amount( "stethoscope", 1 ) || p->has_bionic( "bio_ears" ) ) ) { // We lost our cracking tool somehow, bail out. type = ACT_NULL; break; } // Based on speed, not time if( p->moves <= moves_left ) { moves_left -= p->moves; p->moves = 0; } else { p->moves -= moves_left; moves_left = 0; } p->practice( skill_id( "mechanics" ), 1 ); break; case ACT_REPAIR_ITEM: { // Based on speed * detail vision const int effective_moves = p->moves / p->fine_detail_vision_mod(); if( effective_moves <= moves_left ) { moves_left -= effective_moves; p->moves = 0; } else { p->moves -= moves_left * p->fine_detail_vision_mod(); moves_left = 0; } } break; case ACT_BUTCHER: // Drain some stamina p->mod_stat( "stamina", -20.0f * p->stamina / p->get_stamina_max() ); // Based on speed, not time if( p->moves <= moves_left ) { moves_left -= p->moves; p->moves = 0; } else { p->moves -= moves_left; moves_left = 0; } break; default: // Based on speed, not time if( p->moves <= moves_left ) { moves_left -= p->moves; p->moves = 0; } else { p->moves -= moves_left; moves_left = 0; } } if( is_complete() ) { finish( p ); } }
~LeakChecks() { finish(); }
static int recv_pack(unsigned char *buf, int len, struct sockaddr_ll *FROM) { struct arphdr *ah = (struct arphdr *) buf; unsigned char *p = (unsigned char *) (ah + 1); struct in_addr src_ip, dst_ip; /* Filter out wild packets */ if (FROM->sll_pkttype != PACKET_HOST && FROM->sll_pkttype != PACKET_BROADCAST && FROM->sll_pkttype != PACKET_MULTICAST) return 0; /* Only these types are recognised */ if (ah->ar_op != htons(ARPOP_REQUEST) && ah->ar_op != htons(ARPOP_REPLY)) return 0; /* ARPHRD check and this darned FDDI hack here :-( */ if (ah->ar_hrd != htons(FROM->sll_hatype) && (FROM->sll_hatype != ARPHRD_FDDI || ah->ar_hrd != htons(ARPHRD_ETHER))) return 0; /* Protocol must be IP. */ if (ah->ar_pro != htons(ETH_P_IP)) return 0; if (ah->ar_pln != 4) return 0; if (ah->ar_hln != me.sll_halen) return 0; if (len < sizeof(*ah) + 2 * (4 + ah->ar_hln)) return 0; memcpy(&src_ip, p + ah->ar_hln, 4); memcpy(&dst_ip, p + ah->ar_hln + 4 + ah->ar_hln, 4); if (!(cfg & dad)) { if (src_ip.s_addr != dst.s_addr) return 0; if (src.s_addr != dst_ip.s_addr) return 0; if (memcmp(p + ah->ar_hln + 4, &me.sll_addr, ah->ar_hln)) return 0; } else { /* DAD packet was: src_ip = 0 (or some src) src_hw = ME dst_ip = tested address dst_hw = <unspec> We fail, if receive request/reply with: src_ip = tested_address src_hw != ME if src_ip in request was not zero, check also that it matches to dst_ip, otherwise dst_ip/dst_hw do not matter. */ if (src_ip.s_addr != dst.s_addr) return 0; if (memcmp(p, &me.sll_addr, me.sll_halen) == 0) return 0; if (src.s_addr && src.s_addr != dst_ip.s_addr) return 0; } if (!(cfg & quiet)) { int s_printed = 0; struct timeval tv; gettimeofday(&tv, NULL); printf("%scast re%s from %s [%s]", FROM->sll_pkttype == PACKET_HOST ? "Uni" : "Broad", ah->ar_op == htons(ARPOP_REPLY) ? "ply" : "quest", inet_ntoa(src_ip), ether_ntoa((struct ether_addr *) p)); if (dst_ip.s_addr != src.s_addr) { printf("for %s ", inet_ntoa(dst_ip)); s_printed = 1; } if (memcmp(p + ah->ar_hln + 4, me.sll_addr, ah->ar_hln)) { if (!s_printed) printf("for "); printf("[%s]", ether_ntoa((struct ether_addr *) p + ah->ar_hln + 4)); } if (last.tv_sec) { long usecs = (tv.tv_sec - last.tv_sec) * 1000000 + tv.tv_usec - last.tv_usec; long msecs = (usecs + 500) / 1000; usecs -= msecs * 1000 - 500; printf(" %ld.%03ldms\n", msecs, usecs); } else { printf(" UNSOLICITED?\n"); } fflush(stdout); } received++; if (FROM->sll_pkttype != PACKET_HOST) brd_recv++; if (ah->ar_op == htons(ARPOP_REQUEST)) req_recv++; if (cfg & quit_on_reply) finish(); if (!(cfg & broadcast_only)) { memcpy(he.sll_addr, p, me.sll_halen); cfg |= unicasting; } return 1; }
ossimOpjCompressor::~ossimOpjCompressor() { finish(); }
void main_loop(ping_func_set_st *fset, socket_st *sock, __u8 *packet, int packlen) { char addrbuf[128]; char ans_data[4096]; struct iovec iov; struct msghdr msg; struct cmsghdr *c; int cc; int next; int polling; iov.iov_base = (char *)packet; for (;;) { /* Check exit conditions. */ if (exiting) break; if (npackets && nreceived + nerrors >= npackets) break; if (deadline && nerrors) break; /* Check for and do special actions. */ if (status_snapshot) status(); /* Send probes scheduled to this time. */ do { next = pinger(fset, sock); next = schedule_exit(next); } while (next <= 0); /* "next" is time to send next probe, if positive. * If next<=0 send now or as soon as possible. */ /* Technical part. Looks wicked. Could be dropped, * if everyone used the newest kernel. :-) * Its purpose is: * 1. Provide intervals less than resolution of scheduler. * Solution: spinning. * 2. Avoid use of poll(), when recvmsg() can provide * timed waiting (SO_RCVTIMEO). */ polling = 0; if ((options & (F_ADAPTIVE|F_FLOOD_POLL)) || next<SCHINT(interval)) { int recv_expected = in_flight(); /* If we are here, recvmsg() is unable to wait for * required timeout. */ if (1000 % HZ == 0 ? next <= 1000 / HZ : (next < INT_MAX / HZ && next * HZ <= 1000)) { /* Very short timeout... So, if we wait for * something, we sleep for MININTERVAL. * Otherwise, spin! */ if (recv_expected) { next = MININTERVAL; } else { next = 0; /* When spinning, no reasons to poll. * Use nonblocking recvmsg() instead. */ polling = MSG_DONTWAIT; /* But yield yet. */ sched_yield(); } } if (!polling && ((options & (F_ADAPTIVE|F_FLOOD_POLL)) || interval)) { struct pollfd pset; pset.fd = sock->fd; pset.events = POLLIN; pset.revents = 0; if (poll(&pset, 1, next) < 1 || !(pset.revents&(POLLIN|POLLERR))) continue; polling = MSG_DONTWAIT; } } for (;;) { struct timeval *recv_timep = NULL; struct timeval recv_time; int not_ours = 0; /* Raw socket can receive messages * destined to other running pings. */ iov.iov_len = packlen; memset(&msg, 0, sizeof(msg)); msg.msg_name = addrbuf; msg.msg_namelen = sizeof(addrbuf); msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = ans_data; msg.msg_controllen = sizeof(ans_data); cc = recvmsg(sock->fd, &msg, polling); polling = MSG_DONTWAIT; if (cc < 0) { if (errno == EAGAIN || errno == EINTR) break; if (!fset->receive_error_msg(sock)) { if (errno) { perror("ping: recvmsg"); break; } not_ours = 1; } } else { #ifdef SO_TIMESTAMP for (c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) { if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SO_TIMESTAMP) continue; if (c->cmsg_len < CMSG_LEN(sizeof(struct timeval))) continue; recv_timep = (struct timeval*)CMSG_DATA(c); } #endif if ((options&F_LATENCY) || recv_timep == NULL) { if ((options&F_LATENCY) || ioctl(sock->fd, SIOCGSTAMP, &recv_time)) gettimeofday(&recv_time, NULL); recv_timep = &recv_time; } not_ours = fset->parse_reply(sock, &msg, cc, addrbuf, recv_timep); } /* See? ... someone runs another ping on this host. */ if (not_ours && sock->socktype == SOCK_RAW) fset->install_filter(sock); /* If nothing is in flight, "break" returns us to pinger. */ if (in_flight() == 0) break; /* Otherwise, try to recvmsg() again. recvmsg() * is nonblocking after the first iteration, so that * if nothing is queued, it will receive EAGAIN * and return to pinger. */ } } finish(); }
void SplashScreen::slotFinish(QWidget *mainWin) { finish(mainWin); }
/** * 左侧按钮切换页面tabwidget界面类实现 * @author fanxiang * @version 1.0.0 * @date 2013-08-18 */ TabWidgetManager::TabWidgetManager(QWidget *parent) : QWidget(parent), ui(new Ui::TabWidgetManager) { ui->setupUi(this); QIcon icon; icon.addFile(QString::fromUtf8(":image/icon.png"), QSize(), QIcon::Normal, QIcon::Off); this->setWindowIcon(icon); // 【注意】,此处添加widget为了是窗口布局随大窗口缩放而改变 // 【注意!】ui->gridLayout为自己在Ui设计器中命名的Layout,该Layout中包含QStackedWidget ui->gridLayout->addWidget(ui->page1, 0, 1, 1, 1); ui->gridLayout->addWidget(ui->page2, 0, 1, 1, 1); ui->gridLayout->addWidget(ui->page3, 0, 1, 1, 1); ui->gridLayout->addWidget(ui->page4, 0, 1, 1, 1); ui->gridLayout->addWidget(ui->page5, 0, 1, 1, 1); ui->gridLayout->addWidget(ui->page6, 0, 1, 1, 1); ui->gridLayout->addWidget(ui->page7, 0, 1, 1, 1); ui->gridLayout->addWidget(ui->page8, 0, 1, 1, 1); BackupDatabaseWidget *widgetbackupdb = new BackupDatabaseWidget(ui->page3); WidgetOne *widget2 = new WidgetOne(ui->page1); InputBridgeWidget * widget3 = new InputBridgeWidget(ui->page2); SelectAvaliableTunnelWidget *widget4 = new SelectAvaliableTunnelWidget(ui->page4); SynthesisCorrectWidget * widget56 = new SynthesisCorrectWidget(ui->page5); SelectHistoricalTunnelDataWidget *widget7 = new SelectHistoricalTunnelDataWidget(ui->page7); OutputClearanceWidget *widget8 = new OutputClearanceWidget(ui->page8); QGridLayout *layout1 = new QGridLayout(); layout1->addWidget(widget2); ui->page1->setLayout(layout1); QGridLayout *layout8 = new QGridLayout(); layout8->addWidget(widget3); ui->page2->setLayout(layout8); QGridLayout *layout7 = new QGridLayout(); layout7->addWidget(widgetbackupdb); ui->page3->setLayout(layout7); QGridLayout *layout2 = new QGridLayout(); layout2->addWidget(widget4); ui->page4->setLayout(layout2); QGridLayout *layout3 = new QGridLayout(); layout3->addWidget(widget56); ui->page5->setLayout(layout3); QGridLayout *layout6 = new QGridLayout(); layout6->addWidget(widget7); ui->page7->setLayout(layout6); QGridLayout *layout4 = new QGridLayout(); layout4->addWidget(widget8); ui->page8->setLayout(layout4); /************************************/ // 鼠标点击信号槽 connect(ui->button1, SIGNAL(clicked()), this, SLOT(button1Clicked())); connect(ui->button2, SIGNAL(clicked()), this, SLOT(button2Clicked())); connect(ui->button3, SIGNAL(clicked()), this, SLOT(button3Clicked())); connect(ui->button4, SIGNAL(clicked()), this, SLOT(button4Clicked())); connect(ui->button5, SIGNAL(clicked()), this, SLOT(button5Clicked())); connect(ui->button6, SIGNAL(clicked()), this, SLOT(button6Clicked())); connect(ui->button7, SIGNAL(clicked()), this, SLOT(button7Clicked())); connect(ui->button8, SIGNAL(clicked()), this, SLOT(button8Clicked())); // 界面间通信信号槽 connect(widget7, SIGNAL(updateOutput(SingleOrMultiSelectionMode, CurveType)), widget8, SLOT(updateClearanceTableModel(SingleOrMultiSelectionMode, CurveType))); connect(widget2, SIGNAL(signalBridgeToEdit(int, QString)), widget3, SLOT(slotBridgeToEdit(int, QString))); connect(widget4, SIGNAL(signalSelectedTunnelToEdit(int, QString, bool, bool, bool, double, long long, long long)), widget56, SLOT(slotSelectedTunnelToSynthesis(int, QString, bool, bool, bool, double, long long, long long))); // 关闭窗口信号槽,告知数据库可能需要备份 connect(this, SIGNAL(my_close()), widgetbackupdb, SLOT(checkIfExport())); // 按钮切换界面信号槽 connect(widget7, SIGNAL(updateOutput(SingleOrMultiSelectionMode, CurveType)), this, SLOT(button8Clicked())); connect(widget2, SIGNAL(signalBridgeToEdit(int, QString)), this, SLOT(button2Clicked())); connect(widget8, SIGNAL(backToSelectionSignal()), this, SLOT(button7Clicked())); connect(widget3, SIGNAL(signalEndEdit()), this, SLOT(button1Clicked())); connect(widget4, SIGNAL(signalSelectedTunnelToEdit(int, QString, bool, bool, bool, double, long long, long long)), this, SLOT(button5Clicked())); connect(widget56, SIGNAL(toTabCorrect()), this, SLOT(button6Clicked())); connect(widget56, SIGNAL(toTabSynthesis()), this, SLOT(button5Clicked())); connect(widget56, SIGNAL(finish()), this, SLOT(button4Clicked())); /************关于流程控制*************/ // 开始时禁止点击按钮功能 ui->button2->setEnabled(false); ui->button5->setEnabled(false); ui->button6->setEnabled(false); ui->button8->setEnabled(false); // 显示第一个界面 button3Clicked(); }
MemoryInstrumenter::~MemoryInstrumenter() { finish(); }
static Bool draw_main(ModeInfo *mi, cube21_conf *cp) { GLfloat theta = cp->ramount<0?cp->t:-cp->t; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glLoadIdentity(); if(wander) glTranslatef(3.0*cp->ratio*sin(13.0*cp->posarg), 3.0*sin(17.0*cp->posarg), zpos); else glTranslatef(0, 0, zpos); glScalef(size, size, size); # ifdef HAVE_MOBILE /* Keep it the same relative size when rotated. */ { GLfloat h = MI_HEIGHT(mi) / (GLfloat) MI_WIDTH(mi); int o = (int) current_device_rotation(); if (o != 0 && o != 180 && o != -180) glScalef (1/h, 1/h, 1/h); } # endif glRotatef(cp->xrot, 1.0, 0.0, 0.0); glRotatef(cp->yrot, 0.0, 1.0, 0.0); gltrackball_rotate (cp->trackball); if(cp->wire) glColor3f(0.7, 0.7, 0.7); switch(cp->state) { case CUBE21_PAUSE1: case CUBE21_PAUSE2: draw_top_face(mi, cp); draw_bottom_face(mi, cp); draw_middle(cp); break; case CUBE21_ROT_TOP: glRotatef(theta, 0.0, 0.0, 1.0); draw_top_face(mi, cp); glRotatef(-theta, 0.0, 0.0, 1.0); draw_bottom_face(mi, cp); draw_middle(cp); break; case CUBE21_ROT_BOTTOM: draw_top_face(mi, cp); glRotatef(theta, 0.0, 0.0, 1.0); draw_bottom_face(mi, cp); glRotatef(-theta, 0.0, 0.0, 1.0); draw_middle(cp); break; case CUBE21_HALF1: glRotatef(theta, 0.0, 1.0, 0.0); case CUBE21_HALF2: draw_half_face(mi, cp, 0, 0); glRotatef(-180.0, 0.0, 0.0, 1.0); draw_half_face(mi, cp, 1, 0); glRotatef(-180.0, 0.0, 0.0, 1.0); if(cp->hf[0]) glRotatef(180.0, 0.0, 1.0, 0.0); draw_middle_piece(cp, 0, cp->cind, cp->colors); if(cp->hf[0]) glRotatef(180.0, 0.0, 1.0, 0.0); if(cp->state==CUBE21_HALF1) glRotatef(-theta, 0.0, 1.0, 0.0); else glRotatef(theta, 0.0, 1.0, 0.0); glRotatef(180.0, 0.0, 0.0, 1.0); draw_half_face(mi, cp, 0, 6); glRotatef(-180.0, 0.0, 0.0, 1.0); draw_half_face(mi, cp, 1, 6); glRotatef(-180.0, 0.0, 0.0, 1.0); if(cp->hf[1]) glRotatef(180.0, 0.0, 1.0, 0.0); draw_middle_piece(cp, 1, cp->cind, cp->colors); break; } if(spin) { if((cp->xrot += spinspeed)>360.0) cp->xrot -= 360.0; if((cp->yrot += spinspeed)>360.0) cp->yrot -= 360.0; } if(wander) if((cp->posarg += wspeed/1000.0)>360.0) cp->posarg -= 360.0; if((cp->t += tspeed)>cp->tmax) finish(cp); return True; }
int cmd_merge(int argc, const char **argv, const char *prefix) { unsigned char result_tree[20]; unsigned char stash[20]; unsigned char head_sha1[20]; struct commit *head_commit; struct strbuf buf = STRBUF_INIT; const char *head_arg; int flag, i, ret = 0, head_subsumed; int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0; struct commit_list *common = NULL; const char *best_strategy = NULL, *wt_strategy = NULL; struct commit_list *remoteheads, *p; void *branch_to_free; if (argc == 2 && !strcmp(argv[1], "-h")) usage_with_options(builtin_merge_usage, builtin_merge_options); /* * Check if we are _not_ on a detached HEAD, i.e. if there is a * current branch. */ branch = branch_to_free = resolve_refdup("HEAD", 0, head_sha1, &flag); if (branch && starts_with(branch, "refs/heads/")) branch += 11; if (!branch || is_null_sha1(head_sha1)) head_commit = NULL; else head_commit = lookup_commit_or_die(head_sha1, "HEAD"); git_config(git_merge_config, NULL); if (branch_mergeoptions) parse_branch_merge_options(branch_mergeoptions); argc = parse_options(argc, argv, prefix, builtin_merge_options, builtin_merge_usage, 0); if (shortlog_len < 0) shortlog_len = (merge_log_config > 0) ? merge_log_config : 0; if (verbosity < 0 && show_progress == -1) show_progress = 0; if (abort_current_merge) { int nargc = 2; const char *nargv[] = {"reset", "--merge", NULL}; if (!file_exists(git_path_merge_head())) die(_("There is no merge to abort (MERGE_HEAD missing).")); /* Invoke 'git reset --merge' */ ret = cmd_reset(nargc, nargv, prefix); goto done; } if (read_cache_unmerged()) die_resolve_conflict("merge"); if (file_exists(git_path_merge_head())) { /* * There is no unmerged entry, don't advise 'git * add/rm <file>', just 'git commit'. */ if (advice_resolve_conflict) die(_("You have not concluded your merge (MERGE_HEAD exists).\n" "Please, commit your changes before you merge.")); else die(_("You have not concluded your merge (MERGE_HEAD exists).")); } if (file_exists(git_path_cherry_pick_head())) { if (advice_resolve_conflict) die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).\n" "Please, commit your changes before you merge.")); else die(_("You have not concluded your cherry-pick (CHERRY_PICK_HEAD exists).")); } resolve_undo_clear(); if (verbosity < 0) show_diffstat = 0; if (squash) { if (fast_forward == FF_NO) die(_("You cannot combine --squash with --no-ff.")); option_commit = 0; } if (!argc) { if (default_to_upstream) argc = setup_with_upstream(&argv); else die(_("No commit specified and merge.defaultToUpstream not set.")); } else if (argc == 1 && !strcmp(argv[0], "-")) { argv[0] = "@{-1}"; } if (!argc) usage_with_options(builtin_merge_usage, builtin_merge_options); if (!head_commit) { struct commit *remote_head; /* * If the merged head is a valid one there is no reason * to forbid "git merge" into a branch yet to be born. * We do the same for "git pull". */ if (squash) die(_("Squash commit into empty head not supported yet")); if (fast_forward == FF_NO) die(_("Non-fast-forward commit does not make sense into " "an empty head")); remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv, NULL); remote_head = remoteheads->item; if (!remote_head) die(_("%s - not something we can merge"), argv[0]); if (remoteheads->next) die(_("Can merge only exactly one commit into empty head")); read_empty(remote_head->object.oid.hash, 0); update_ref("initial pull", "HEAD", remote_head->object.oid.hash, NULL, 0, UPDATE_REFS_DIE_ON_ERR); goto done; } /* * This could be traditional "merge <msg> HEAD <commit>..." and * the way we can tell it is to see if the second token is HEAD, * but some people might have misused the interface and used a * commit-ish that is the same as HEAD there instead. * Traditional format never would have "-m" so it is an * additional safety measure to check for it. */ if (!have_message && is_old_style_invocation(argc, argv, head_commit->object.oid.hash)) { warning("old-style 'git merge <msg> HEAD <commit>' is deprecated."); strbuf_addstr(&merge_msg, argv[0]); head_arg = argv[1]; argv += 2; argc -= 2; remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv, NULL); } else { /* We are invoked directly as the first-class UI. */ head_arg = "HEAD"; /* * All the rest are the commits being merged; prepare * the standard merge summary message to be appended * to the given message. */ remoteheads = collect_parents(head_commit, &head_subsumed, argc, argv, &merge_msg); } if (!head_commit || !argc) usage_with_options(builtin_merge_usage, builtin_merge_options); if (verify_signatures) { for (p = remoteheads; p; p = p->next) { struct commit *commit = p->item; char hex[GIT_SHA1_HEXSZ + 1]; struct signature_check signature_check; memset(&signature_check, 0, sizeof(signature_check)); check_commit_signature(commit, &signature_check); find_unique_abbrev_r(hex, commit->object.oid.hash, DEFAULT_ABBREV); switch (signature_check.result) { case 'G': break; case 'U': die(_("Commit %s has an untrusted GPG signature, " "allegedly by %s."), hex, signature_check.signer); case 'B': die(_("Commit %s has a bad GPG signature " "allegedly by %s."), hex, signature_check.signer); default: /* 'N' */ die(_("Commit %s does not have a GPG signature."), hex); } if (verbosity >= 0 && signature_check.result == 'G') printf(_("Commit %s has a good GPG signature by %s\n"), hex, signature_check.signer); signature_check_clear(&signature_check); } } strbuf_addstr(&buf, "merge"); for (p = remoteheads; p; p = p->next) strbuf_addf(&buf, " %s", merge_remote_util(p->item)->name); setenv("GIT_REFLOG_ACTION", buf.buf, 0); strbuf_reset(&buf); for (p = remoteheads; p; p = p->next) { struct commit *commit = p->item; strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(commit->object.oid.hash)); setenv(buf.buf, merge_remote_util(commit)->name, 1); strbuf_reset(&buf); if (fast_forward != FF_ONLY && merge_remote_util(commit) && merge_remote_util(commit)->obj && merge_remote_util(commit)->obj->type == OBJ_TAG) fast_forward = FF_NO; } if (option_edit < 0) option_edit = default_edit_option(); if (!use_strategies) { if (!remoteheads) ; /* already up-to-date */ else if (!remoteheads->next) add_strategies(pull_twohead, DEFAULT_TWOHEAD); else add_strategies(pull_octopus, DEFAULT_OCTOPUS); } for (i = 0; i < use_strategies_nr; i++) { if (use_strategies[i]->attr & NO_FAST_FORWARD) fast_forward = FF_NO; if (use_strategies[i]->attr & NO_TRIVIAL) allow_trivial = 0; } if (!remoteheads) ; /* already up-to-date */ else if (!remoteheads->next) common = get_merge_bases(head_commit, remoteheads->item); else { struct commit_list *list = remoteheads; commit_list_insert(head_commit, &list); common = get_octopus_merge_bases(list); free(list); } update_ref("updating ORIG_HEAD", "ORIG_HEAD", head_commit->object.oid.hash, NULL, 0, UPDATE_REFS_DIE_ON_ERR); if (remoteheads && !common) ; /* No common ancestors found. We need a real merge. */ else if (!remoteheads || (!remoteheads->next && !common->next && common->item == remoteheads->item)) { /* * If head can reach all the merge then we are up to date. * but first the most common case of merging one remote. */ finish_up_to_date("Already up-to-date."); goto done; } else if (fast_forward != FF_NO && !remoteheads->next && !common->next && !hashcmp(common->item->object.oid.hash, head_commit->object.oid.hash)) { /* Again the most common case of merging one remote. */ struct strbuf msg = STRBUF_INIT; struct commit *commit; if (verbosity >= 0) { char from[GIT_SHA1_HEXSZ + 1], to[GIT_SHA1_HEXSZ + 1]; find_unique_abbrev_r(from, head_commit->object.oid.hash, DEFAULT_ABBREV); find_unique_abbrev_r(to, remoteheads->item->object.oid.hash, DEFAULT_ABBREV); printf(_("Updating %s..%s\n"), from, to); } strbuf_addstr(&msg, "Fast-forward"); if (have_message) strbuf_addstr(&msg, " (no commit created; -m option ignored)"); commit = remoteheads->item; if (!commit) { ret = 1; goto done; } if (checkout_fast_forward(head_commit->object.oid.hash, commit->object.oid.hash, overwrite_ignore)) { ret = 1; goto done; } finish(head_commit, remoteheads, commit->object.oid.hash, msg.buf); drop_save(); goto done; } else if (!remoteheads->next && common->next) ; /* * We are not doing octopus and not fast-forward. Need * a real merge. */ else if (!remoteheads->next && !common->next && option_commit) { /* * We are not doing octopus, not fast-forward, and have * only one common. */ refresh_cache(REFRESH_QUIET); if (allow_trivial && fast_forward != FF_ONLY) { /* See if it is really trivial. */ git_committer_info(IDENT_STRICT); printf(_("Trying really trivial in-index merge...\n")); if (!read_tree_trivial(common->item->object.oid.hash, head_commit->object.oid.hash, remoteheads->item->object.oid.hash)) { ret = merge_trivial(head_commit, remoteheads); goto done; } printf(_("Nope.\n")); } } else { /* * An octopus. If we can reach all the remote we are up * to date. */ int up_to_date = 1; struct commit_list *j; for (j = remoteheads; j; j = j->next) { struct commit_list *common_one; /* * Here we *have* to calculate the individual * merge_bases again, otherwise "git merge HEAD^ * HEAD^^" would be missed. */ common_one = get_merge_bases(head_commit, j->item); if (hashcmp(common_one->item->object.oid.hash, j->item->object.oid.hash)) { up_to_date = 0; break; } } if (up_to_date) { finish_up_to_date("Already up-to-date. Yeeah!"); goto done; } } if (fast_forward == FF_ONLY) die(_("Not possible to fast-forward, aborting.")); /* We are going to make a new commit. */ git_committer_info(IDENT_STRICT); /* * At this point, we need a real merge. No matter what strategy * we use, it would operate on the index, possibly affecting the * working tree, and when resolved cleanly, have the desired * tree in the index -- this means that the index must be in * sync with the head commit. The strategies are responsible * to ensure this. */ if (use_strategies_nr == 1 || /* * Stash away the local changes so that we can try more than one. */ save_state(stash)) hashcpy(stash, null_sha1); for (i = 0; i < use_strategies_nr; i++) { int ret; if (i) { printf(_("Rewinding the tree to pristine...\n")); restore_state(head_commit->object.oid.hash, stash); } if (use_strategies_nr != 1) printf(_("Trying merge strategy %s...\n"), use_strategies[i]->name); /* * Remember which strategy left the state in the working * tree. */ wt_strategy = use_strategies[i]->name; ret = try_merge_strategy(use_strategies[i]->name, common, remoteheads, head_commit, head_arg); if (!option_commit && !ret) { merge_was_ok = 1; /* * This is necessary here just to avoid writing * the tree, but later we will *not* exit with * status code 1 because merge_was_ok is set. */ ret = 1; } if (ret) { /* * The backend exits with 1 when conflicts are * left to be resolved, with 2 when it does not * handle the given merge at all. */ if (ret == 1) { int cnt = evaluate_result(); if (best_cnt <= 0 || cnt <= best_cnt) { best_strategy = use_strategies[i]->name; best_cnt = cnt; } } if (merge_was_ok) break; else continue; } /* Automerge succeeded. */ write_tree_trivial(result_tree); automerge_was_ok = 1; break; } /* * If we have a resulting tree, that means the strategy module * auto resolved the merge cleanly. */ if (automerge_was_ok) { ret = finish_automerge(head_commit, head_subsumed, common, remoteheads, result_tree, wt_strategy); goto done; } /* * Pick the result from the best strategy and have the user fix * it up. */ if (!best_strategy) { restore_state(head_commit->object.oid.hash, stash); if (use_strategies_nr > 1) fprintf(stderr, _("No merge strategy handled the merge.\n")); else fprintf(stderr, _("Merge with strategy %s failed.\n"), use_strategies[0]->name); ret = 2; goto done; } else if (best_strategy == wt_strategy) ; /* We already have its result in the working tree. */ else { printf(_("Rewinding the tree to pristine...\n")); restore_state(head_commit->object.oid.hash, stash); printf(_("Using the %s to prepare resolving by hand.\n"), best_strategy); try_merge_strategy(best_strategy, common, remoteheads, head_commit, head_arg); } if (squash) finish(head_commit, remoteheads, NULL, NULL); else write_merge_state(remoteheads); if (merge_was_ok) fprintf(stderr, _("Automatic merge went well; " "stopped before committing as requested\n")); else ret = suggest_conflicts(); done: free(branch_to_free); return ret; }
void thr(int ifno) { uint64_t in64=0, previn64=0, out64=0, prevout64=0, ratein64=0, rateout64=0; uint32_t in32=0, previn32=0, out32=0, prevout32=0, ratein32=0, rateout32=0; time_t t; struct tm *ltime; char ifname[32]; snprintf(ifname, sizeof(ifname), "%s.%d", "1.3.6.1.2.1.2.2.1.2", ifno); printf("stats for interface (#%d) ", ifno); prsnmpstr(ifname); printf(" @ "); prsnmpstr(".1.3.6.1.2.1.1.5.0"); if(extended) printf(" in 64bit mode:\n"); else printf(" in 32bit mode:\n"); signal(SIGINT, (void*)finish); while(1) { if(iterations>count) finish(); if(extended) { previn64=in64; prevout64=out64; in64=getcntr64(OID_XIN, ifno); out64=getcntr64(OID_XOUT, ifno); ratein64=(uint64_t)(in64-previn64); rateout64=(uint64_t)(out64-prevout64); } else { previn32=in32; prevout32=out32; in32=getcntr32(OID_IN, ifno); out32=getcntr32(OID_OUT, ifno); ratein32=(uint32_t)(in32-previn32); rateout32=(uint32_t)(out32-prevout32); } if(iterations) { if(extended) { sumin+=ratein64; sumout+=rateout64; if(ratein64>maxin) maxin=ratein64; if(ratein64<minin) minin=ratein64; if(rateout64>maxout) maxout=rateout64; if(rateout64<minout) minout=rateout64; } else { sumin+=ratein32; sumout+=rateout32; if(ratein32>maxin) maxin=ratein32; if(ratein32<minin) minin=ratein32; if(rateout32>maxout) maxout=rateout32; if(rateout32<minout) minout=rateout32; } time(&t); ltime=localtime(&t); printf("[%02d:%02d:%02d] current throughput: in ", ltime->tm_hour, ltime->tm_min, ltime->tm_sec); if(extended) kbprint((uint64_t)(ratein64/interval)); else kbprint((uint64_t)(ratein32/interval)); printf(" out "); if(extended) kbprint((uint64_t)(rateout64/interval)); else kbprint((uint64_t)(rateout32/interval)); if (debug) { if(extended) printf(" [%llu-%llu=%llu] [%llu-%llu=%llu]", in64,previn64,ratein64, out64,prevout64,rateout64); else printf(" [%u-%u=%u] [%u-%u=%u]", in32,previn32,ratein32, out32,prevout32,rateout32); } putchar('\n'); } iterations++; #ifndef WIN32 sleep(interval); #else Sleep(interval*1000); #endif } }