Call after check_future(). If True, it is time to yield tornado.gen.moment
185562
def time_to_yield(self):
        """"""
        delta = self.ioloop.time() - self.done_since
        if self.done and delta > self.max_loop_latency:
            return True
        return False
1139099
def has_next_async(self):
    
    if self._fut is None:
      self._fut = self._iter.getq()
    flag = True
    try:
      yield self._fut
    except EOFError:
      flag = False
    raise tasklets.Return(flag)
1079867
def sendFuture(self, future):
        """"""
        try:
            if shared.getConst(hash(future.callable),
                               timeout=0):
                # Enforce name reference passing if already shared
                future.callable = SharedElementEncapsulation(hash(future.callable))
            self.socket.send_multipart([b"TASK",
                                        pickle.dumps(future,
                                                     pickle.HIGHEST_PROTOCOL)])
        except pickle.PicklingError as e:
            # If element not picklable, pickle its name
            # TODO: use its fully qualified name
            scoop.logger.warn("Pickling Error: {0}".format(e))
            previousCallable = future.callable
            future.callable = hash(future.callable)
            self.socket.send_multipart([b"TASK",
                                        pickle.dumps(future,
                                                     pickle.HIGHEST_PROTOCOL)])
            future.callable = previousCallable
160576
def at(self, instant):
        

        for event in self:
            if event.begin <= instant <= event.end:
                yield event
217818
def _handle_event_socket_recv(self, raw):
        '''
        
        '''
        mtag, data = self.event.unpack(raw, self.event.serial)

        # see if we have any futures that need this info:
        for (tag, matcher), futures in six.iteritems(self.tag_map):
            try:
                is_matched = matcher(mtag, tag)
            except Exception:
                log.error('Failed to run a matcher.', exc_info=True)
                is_matched = False

            if not is_matched:
                continue

            for future in futures:
                if future.done():
                    continue
                future.set_result({'data': data, 'tag': mtag})
                self.tag_map[(tag, matcher)].remove(future)
                if future in self.timeout_map:
                    tornado.ioloop.IOLoop.current().remove_timeout(self.timeout_map[future])
                    del self.timeout_map[future]
1045929
def wait_for_futures(self):
        
        [future for future in futures.as_completed(self.futures)]
        self.futures = []
800477
def _end_flusher_loop(self):
        
        if not self.is_connected or self.is_connecting or self.io.closed():
            if self._flush_queue is not None and self._flush_queue.empty():
                self._flush_pending(check_connected=False)
            yield tornado.gen.moment
316907
def _future_completed(future):
    
    exc = future.exception()
    if exc:
        log.debug("Failed to run task on executor", exc_info=exc)
929628
def gather(self, futures, consume_exceptions=True):
        

        # from the asyncio docs: "If return_exceptions is True, exceptions
        # in the tasks are treated the same as successful results, and
        # gathered in the result list; otherwise, the first raised
        # exception will be immediately propagated to the returned
        # future."
        return asyncio.gather(*futures, return_exceptions=consume_exceptions)
164133
def next(self, now=None, increments=_increments, delta=True, default_utc=WARN_CHANGE):
        '''
        
        '''
        if default_utc is WARN_CHANGE and (isinstance(now, _number_types) or (now and not now.tzinfo) or now is None):
            warnings.warn(WARNING_CHANGE_MESSAGE, FutureWarning, 2)
            default_utc = False

        now = now or (datetime.utcnow() if default_utc and default_utc is not WARN_CHANGE else datetime.now())
        if isinstance(now, _number_types):
            now = datetime.utcfromtimestamp(now) if default_utc else datetime.fromtimestamp(now)

        # handle timezones if the datetime object has a timezone and get a
        # reasonable future/past start time
        onow, now = now, now.replace(tzinfo=None)
        tz = onow.tzinfo
        future = now.replace(microsecond=0) + increments[0]()
        if future < now:
            # we are going backwards...
            _test = lambda: future.year < self.matchers.year
            if now.microsecond:
                future = now.replace(microsecond=0)
        else:
            # we are going forwards
            _test = lambda: self.matchers.year < future.year

        # Start from the year and work our way down. Any time we increment a
        # higher-magnitude value, we reset all lower-magnitude values. This
        # gets us performance without sacrificing correctness. Still more
        # complicated than a brute-force approach, but also orders of
        # magnitude faster in basically all cases.
        to_test = ENTRIES - 1
        while to_test >= 0:
            if not self._test_match(to_test, future):
                inc = increments[to_test](future, self.matchers)
                future += inc
                for i in xrange(0, to_test):
                    future = increments[ENTRIES+i](future, inc)
                try:
                    if _test():
                        return None
                except:
                    print(future, type(future), type(inc))
                    raise
                to_test = ENTRIES-1
                continue
            to_test -= 1

        # verify the match
        match = [self._test_match(i, future) for i in xrange(ENTRIES)]
        _assert(all(match),
            "\nYou have discovered a bug with crontab, please notify the\n" \
            "author with the following information:\n" \
            "crontab: %r\n" \
            "now: %r", ' '.join(m.input for m in self.matchers), now)

        if not delta:
            onow = now = datetime(1970, 1, 1)

        delay = future - now
        if tz:
            delay += _fix_none(onow.utcoffset())
            if hasattr(tz, 'localize'):
                delay -= _fix_none(tz.localize(future).utcoffset())
            else:
                delay -= _fix_none(future.replace(tzinfo=tz).utcoffset())

        return delay.days * 86400 + delay.seconds + delay.microseconds / 1000000.
308053
def ensure_result(self, supress_exception = False, defaultresult = None):
        '''
        
        '''
        try:
            yield self
        except Exception as exc:
            if not self.done():
                self.set_exception(exc)
            if not supress_exception:
                raise
        except:
            if not self.done():
                self.set_exception(FutureCancelledException('cancelled'))
            raise
        else:
            if not self.done():
                self.set_result(defaultresult)
102588
private boolean acquireWriteFuture(int sliceLength) {
        if (sliceLength > 0) {
            Object writeResult = null;
            // determine a good timeout value based on the slice length to write
            int timeout = sliceLength * 500;
            // check for existing future
            if (writerFuture != null) {
                try {
                    // wait for a result from the last writer
                    writeResult = writerFuture.get(timeout, TimeUnit.MILLISECONDS);
                } catch (Exception e) {
                    log.warn("Exception waiting for write result. Timeout: {}ms", timeout, e);
                    return false;
                }
            }
            log.debug("Write future result (expect null): {}", writeResult);
            return true;
        }
        return false;
    }
1249441
def _timeout_future(self, tag, matcher, future):
        '''
        
        '''
        if (tag, matcher) not in self.tag_map:
            return
        if not future.done():
            future.set_exception(TimeoutException())
            self.tag_map[(tag, matcher)].remove(future)
        if not self.tag_map[(tag, matcher)]:
            del self.tag_map[(tag, matcher)]
21064
def return_future(fn):
    
    @wraps(fn)
    def decorated(*args, **kwargs):
        return gen.maybe_future(fn(*args, **kwargs))

    return decorated
476607
function executeCallback(cb, arg) {
    var r = cb(arg)
    if(r !== undefined && !isLikeAFuture(r) )
        throw Error("Value returned from then or catch ("+r+") is *not* a Future. Callback: "+cb.toString())

    return r
}
1200191
def _wait(self, generator, method, timeout=None, *args, **kwargs):
        """"""
        if self.debug:
            print("waiting for %s to pause" % generator)

        original_timeout = timeout
        while timeout is None or timeout > 0:
            last_time = time.time()
            if self._lock.acquire(False):  # timeout param was added in 3.2
                try:
                    if self.can_resume():
                        return method(generator, *args, **kwargs)
                    elif self.has_terminated():
                        raise RuntimeError("%s has already terminated" % generator)
                finally:
                    self._lock.release()

            if timeout is not None:
                timeout -= time.time() - last_time

        msg = "%s did not pause after %ss" % (generator, original_timeout)
        if self.debug:
            print(msg)
        raise WaitTimeoutError(msg)
628046
private void fetchNext() {
		if (pendingUtc != null || done) {
			return;
		}

		DateValue dUtc = generateInstance();

		//check the exit condition
		if (dUtc == null || !condition.apply(dUtc)) {
			done = true;
			return;
		}

		pendingUtc = dUtc;
		yearGenerator.workDone();
	}