This is a time limited pipeline. If you have a infinite pipeline and
        want it to stop yielding after a certain amount of time, use this!
506694
def timed_pipe(generator, seconds=3):
    '''  '''
    # grab the highest precision timer
    # when it started
    start = ts()
    # when it will stop
    end = start + seconds
    # iterate over the pipeline
    for i in generator:
        # if there is still time
        if ts() < end:
            # yield the next item
            yield i
        # otherwise
        else:
            # stop
            break
1308883
private boolean blockUntilOpenShardsAtMost(int maxOpenShards, @Nullable TransferKey permittedKey, Instant timeout)
            throws IOException, InterruptedException {
        Stopwatch stopWatch = Stopwatch.createStarted();
        Instant now;

        _lock.lock();
        try {
            while (!_closed &&
                    maxOpenShardsGreaterThan(maxOpenShards, permittedKey) &&
                    (now = Instant.now()).isBefore(timeout)) {
                // Stop blocking if there is an exception
                propagateExceptionIfPresent();

                // Wait no longer than 30 seconds; we want to log at least every 30 seconds we've been waiting.
                long waitTime = Math.min(Duration.ofSeconds(30).toMillis(), Duration.between(now, timeout).toMillis());
                _shardFilesClosedOrExceptionCaught.await(waitTime, TimeUnit.MILLISECONDS);

                if (!maxOpenShardsGreaterThan(maxOpenShards, permittedKey)) {
                    propagateExceptionIfPresent();
                    return true;
                }

                _log.debug("After {} seconds task {} still has {} open shards",
                        stopWatch.elapsed(TimeUnit.SECONDS), _taskId, _openShardFiles.size());
            }

            propagateExceptionIfPresent();
            return !maxOpenShardsGreaterThan(maxOpenShards, permittedKey);
        } finally {
            _lock.unlock();
        }
    }
29098
private boolean blockOnPipeLine() {
    if (this.isKilled()) {
      return true;
    }

    // For pipelining of jobs. Will watch other jobs.
    if (!this.pipelineJobs.isEmpty()) {
      String blockedList = "";
      final ArrayList<BlockingStatus> blockingStatus =
          new ArrayList<>();
      for (final String waitingJobId : this.pipelineJobs) {
        final Status status = this.watcher.peekStatus(waitingJobId);
        if (status != null && !Status.isStatusFinished(status)) {
          final BlockingStatus block = this.watcher.getBlockingStatus(waitingJobId);
          blockingStatus.add(block);
          blockedList += waitingJobId + ",";
        }
      }
      if (!blockingStatus.isEmpty()) {
        this.logger.info("Pipeline job " + this.jobId + " waiting on " + blockedList
            + " in execution " + this.watcher.getExecId());

        for (final BlockingStatus bStatus : blockingStatus) {
          this.logger.info("Waiting on pipelined job " + bStatus.getJobId());
          this.currentBlockStatus = bStatus;
          bStatus.blockOnFinishedStatus();
          if (this.isKilled()) {
            this.logger.info("Job was killed while waiting on pipeline. Quiting.");
            return true;
          } else {
            this.logger.info("Pipelined job " + bStatus.getJobId() + " finished.");
          }
        }
      }
    }

    this.currentBlockStatus = null;
    return false;
  }
501276
function stopOnProcess(index) {
  log( 'Attempting to stop ' + index + '...' );

  done = this.async();
  findProcessWithIndex( index, function(process) {
    if( typeof process !== 'undefined' ) {
      log( forever.format(true,[process]) );

      forever.stop( index )
        .on('stop', function() {
          done();
        })
        .on('error', function(message) {
          error( 'Error stopping ' + index + '. [REASON] :: ' + message );
          done(false);
        });
    }
    else {
      gruntRef.warn( index + ' not found in list of processes in forever.' );
      done();
    }
  });
}
704235
def _check_stop(self, iters, elapsed_time, converged):
        

        r_c = self.config['resources']
        
        stop = False
        if converged==0:
            stop=True
        if r_c['maximum-iterations'] !='NA' and iters>= r_c['maximum-iterations']:
            stop = True
        if r_c['max-run-time'] != 'NA' and elapsed_time/60.>= r_c['max-run-time']:
            stop = True
        return stop
293412
function stop () {
        currentValues = fromValues;
        triggerEvent('stop');
        stopLoop(animationId);
        pausedAfter = undefined;
        startTime = undefined;
        return self;
      }
387473
def _flush_timeout(self, timeout):
        
        future = tornado.concurrent.Future()
        yield self._send_ping(future)
        try:
            result = yield tornado.gen.with_timeout(
                timedelta(seconds=timeout), future)
        except tornado.gen.TimeoutError:
            # Set the future to False so it can be ignored in _process_pong,
            # and try to remove from the list of pending pongs.
            future.set_result(False)
            for i, pong_future in enumerate(self._pongs):
                if pong_future == future:
                    del self._pongs[i]
                    break
            raise
        raise tornado.gen.Return(result)
1335139
public void stop() {
		thread.requestStop = true;
		long start = System.currentTimeMillis()+timeout;
		while( start > System.currentTimeMillis() && thread.running )
			Thread.yield();

		device.stopDepth();
		device.stopVideo();
		device.close();
	}
995512
def stop(self, timeout=None):
        

        self.stopping = True

        for process in list(self.processes):
            self.stop_process(process, timeout=timeout)
559928
def decaying(start, stop, decay):
    """"""

    curr = float(start)
    while True:
        yield max(curr, stop)
        curr -= (decay)
1230325
def ratelimit(key, limit, per=1, redis=None):
    

    if redis is None:
        redis = connections.redis

    # http://redis.io/commands/INCR
    now = int(time.time())

    k = "ratelimit:%s:%s" % (key, now // per)

    with redis.pipeline(transaction=True) as pipeline:
        pipeline.incr(k, 1)
        pipeline.expire(k, per + 10)
        value = pipeline.execute()

    current = int(value[0]) - 1

    if current >= limit:
        return 0
    else:
        return limit - current
423539
static void waitForPipelineToFinish(PipelineResult result) {
    try {
      // Check to see if we are creating a template.
      // This should throw {@link UnsupportedOperationException} when creating a template.
      result.getState();

      State state = result.waitUntilFinish();
      LOG.info("Job finished with state: " + state.name());
      if (state != State.DONE) {
        System.exit(1);
      }
    } catch (UnsupportedOperationException e) {
      LOG.warn("Unable to wait for pipeline to finish.", e);
    }
  }
386679
function RateLimit(type, distFactor, config) {
  this.config = config;
  this.type = type;
  this.buckets = this.config.defaultBuckets.map(b => new TokenBucket(b.timespan, b.limit, b));
  this.retryAfter = 0;
  this.distFactor = distFactor;
}
666561
def stop(self):
        
        if not self._timer.isActive():
            return

        self._elapsed += self._delta
        self._timer.stop()
282758
def uniq(pipe):
    '''  '''
    pipe = iter(pipe)
    previous = next(pipe)
    yield previous
    for i in pipe:
        if i is not previous:
            previous = i
            yield i
987104
function () {
    var self = this;
    if (self._stopped)
      throw new Error("Called waitUntilCaughtUp on stopped handle!");

    // Calling waitUntilCaughtUp requries us to wait for the oplog connection to
    // be ready.
    self._readyFuture.wait();

    while (!self._stopped) {
      // We need to make the selector at least as restrictive as the actual
      // tailing selector (ie, we need to specify the DB name) or else we might
      // find a TS that won't show up in the actual tail stream.
      try {
        var lastEntry = self._oplogLastEntryConnection.findOne(
          OPLOG_COLLECTION, self._baseOplogSelector,
          {fields: {ts: 1}, sort: {$natural: -1}});
        break;
      } catch (e) {
        // During failover (eg) if we get an exception we should log and retry
        // instead of crashing.
        Meteor._debug("Got exception while reading last entry: " + e);
        Meteor._sleepForMs(100);
      }
    }

    if (self._stopped)
      return;

    if (!lastEntry) {
      // Really, nothing in the oplog? Well, we've processed everything.
      return;
    }

    var ts = lastEntry.ts;
    if (!ts)
      throw Error("oplog entry without ts: " + EJSON.stringify(lastEntry));

    if (self._lastProcessedTS && ts.lessThanOrEqual(self._lastProcessedTS)) {
      // We've already caught up to here.
      return;
    }


    // Insert the future into our list. Almost always, this will be at the end,
    // but it's conceivable that if we fail over from one primary to another,
    // the oplog entries we see will go backwards.
    var insertAfter = self._catchingUpFutures.length;
    while (insertAfter - 1 > 0
           && self._catchingUpFutures[insertAfter - 1].ts.greaterThan(ts)) {
      insertAfter--;
    }
    var f = new Future;
    self._catchingUpFutures.splice(insertAfter, 0, {ts: ts, future: f});
    f.wait();
  }
985493
def stopProducing(self):
        
        _legacy_twisted_log.msg("Disconnecting from the AMQP broker")
        yield self.pauseProducing()
        yield self.close()
        self._consumers = {}
        self._channel = None