Decorator that makes a generator function automatically advance to its
    first yield point when initially called (PEP 342).
12484
def consumer(function):
    """"""
    @wraps(function)
    def wrapper(*args, **kwargs):
        generator = function(*args, **kwargs)
        next(generator)
        return generator
    return wrapper
492769
function runUntilResolved(genInstance, nextArg) {
  try {
    let nextResult = genInstance.next(nextArg);
    if (nextResult.done) {
      return Promise.resolve(nextResult.value);
    } else {
      let v = nextResult.value;
      let fn = v.fn;
      let thisArg;
      if (fn instanceof Array) {
        thisArg = fn[0];
        fn = fn[1];
      }
      let args = v.args;

      if (fn == null || args == null) {
        throw new Error('`Episode7.run` requires using `Episode7.call` with every `yield`. '+
          'Check all of the `yield` expressions in [Function: '+genInstance.episode7Name+']');
      }

      // Iterate through the generator, handling
      // promises & nested generators.
      // Side-effect function is called without `this`.
      let sideEffect;
      if (isGeneratorFunction(fn)) {
        sideEffect = Promise.resolve()
          .then(function() {
            // Wrapped in `then` to promisify return value
            return run(fn, ...args)
          })
      } else {
        sideEffect = Promise.resolve()
          .then(function() {
            // Wrapped in `then` to promisify return value
            return fn.call(thisArg, ...args)
          })
      }
      return sideEffect
        .then(function(result) {
          return runUntilResolved(genInstance, result);
        })
    }

  } catch(error) {
    return Promise.reject(error);
  }
}
120838
def dategenerator(start, end, step=1, desc=False):
    ''''''
    delta = timedelta(abs(step))
    end = max(start, end)
    if desc:
        dt = end
        while dt >= start:
            yield dt
            dt -= delta
    else:
        dt = start
        while dt <= end:
            yield dt
            dt += delta
901696
def generative(func):
    
    def wrap(inst, *args, **kw):
        clone = type(inst).__new__(type(inst))
        clone.__dict__ = inst.__dict__.copy()
        return func(clone, *args, **kw)
    return update_wrapper(wrap, func)
1191041
def progress(iterator, enum=False, length=None):
    
    progress = ProgressBar()
    length = len(iterator) if length is None else length
    gen = enumerate(iterator)
    while True:
        i, val = next(gen)
        progress((i+1.0)/length * 100)
        if enum:
            yield i, val
        else:
            yield val
1160919
def wrap_as_node(self, func):
        ''
        name = self.get_name(func)

        @wraps(func)
        def wrapped(*args, **kwargs):
            'wrapped version of func'
            message = self.get_message_from_call(*args, **kwargs)
            self.logger.info('calling "%s" with %r', name, message)
            result = func(message)

            # functions can return multiple values ("emit" multiple times)
            # by yielding instead of returning. Handle this case by making
            # a list of the results and processing them all after the
            # generator successfully exits. If we were to process them as
            # they came out of the generator, we might get a partially
            # processed input sent down the graph. This may be possible in
            # the future via a flag.
            if isinstance(result, GeneratorType):
                results = [
                    self.wrap_result(name, item)
                    for item in result
                    if item is not NoResult
                ]
                self.logger.debug(
                    '%s returned generator yielding %d items', func, len(results)
                )

                [self.route(name, item) for item in results]
                return tuple(results)

            # the case of a direct return is simpler. wrap, route, and
            # return the value.
            else:
                if result is NoResult:
                    return result

                result = self.wrap_result(name, result)
                self.logger.debug(
                    '%s returned single value %s', func, result
                )
                self.route(name, result)
                return result

        return wrapped
785855
def trace_walker(module):
    

    for name, function in inspect.getmembers(module, inspect.isfunction):
        yield None, function

    for name, cls in inspect.getmembers(module, inspect.isclass):
        yield cls, None

        for name, method in inspect.getmembers(cls, inspect.ismethod):
            yield cls, method

        for name, function in inspect.getmembers(cls, inspect.isfunction):
            yield cls, function

        for name, accessor in inspect.getmembers(cls, lambda x: type(x) is property):
            yield cls, accessor.fget
            yield cls, accessor.fset
            yield cls, accessor.fdel
892447
def backoff_generator(self):
        """"""
        for x in self.config.backoff_delays:
            yield x
        while True:
            yield self.config.backoff_delays[-1]
996415
def _accumulate(sequence, func):
    
    iterator = iter(sequence)
    total = next(iterator)
    yield total
    for element in iterator:
        total = func(total, element)
        yield total
903631
def _gdecorator(generate_func):
        
        def dostuff(self):
            for func in self._pregenerate_functions:
                self.current_params = func(self.current_params)
            res = generate_func(self) # pylint:disable=not-callable
            return self._postgenerate(res)
        return dostuff
746033
function continuer(verb, arg) {
            var result;

            // Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only
            // engine that has a deployed base of browsers that support generators.
            // However, SM's generators use the Python-inspired semantics of
            // outdated ES6 drafts.  We would like to support ES6, but we'd also
            // like to make it possible to use generators in deployed browsers, so
            // we also support Python-style generators.  At some point we can remove
            // this block.

            if (typeof StopIteration === "undefined") {
                // ES6 Generators
                try {
                    result = generator[verb](arg);
                } catch (exception) {
                    return reject(exception);
                }
                if (result.done) {
                    return Q(result.value);
                } else {
                    return when(result.value, callback, errback);
                }
            } else {
                // SpiderMonkey Generators
                // FIXME: Remove this case when SM does ES6 generators.
                try {
                    result = generator[verb](arg);
                } catch (exception) {
                    if (isStopIteration(exception)) {
                        return Q(exception.value);
                    } else {
                        return reject(exception);
                    }
                }
                return when(result, callback, errback);
            }
        }
708727
def build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]] = None, *,
                     init: Any = NONE):
    
    _init = init

    def _build_accumulate(function: Callable[[Any, Any], Tuple[Any, Any]]):
        @wraps(function)
        def _wrapper(init=NONE) -> Accumulate:
            init = _init if init is NONE else init
            if init is NONE:
                raise TypeError('"init" argument has to be defined')
            return Accumulate(function, init=init)
        return _wrapper

    if function:
        return _build_accumulate(function)

    return _build_accumulate
853461
def nt_yielder(self, graph, size):
        
        for grp in self.make_batch(size, graph):
            tmpg = Graph()
            # Add statements as list to tmp graph
            tmpg += grp
            yield (len(tmpg), tmpg.serialize(format='nt'))
150944
def make_input_fn_from_generator(gen):
  """"""
  first_ex = six.next(gen)
  flattened = tf.contrib.framework.nest.flatten(first_ex)
  types = [t.dtype for t in flattened]
  shapes = [[None] * len(t.shape) for t in flattened]
  first_ex_list = [first_ex]

  def py_func():
    if first_ex_list:
      example = first_ex_list.pop()
    else:
      example = six.next(gen)
    return tf.contrib.framework.nest.flatten(example)

  def input_fn():
    flat_example = tf.py_func(py_func, [], types)
    _ = [t.set_shape(shape) for t, shape in zip(flat_example, shapes)]
    example = tf.contrib.framework.nest.pack_sequence_as(first_ex, flat_example)
    return example

  return input_fn
883730
def decorate(func, caller, extras=()):
    
    evaldict = dict(_call_=caller, _func_=func)
    es = ''
    for i, extra in enumerate(extras):
        ex = '_e%d_' % i
        evaldict[ex] = extra
        es += ex + ', '

    if '3.5' <= sys.version < '3.6':
        # with Python 3.5 isgeneratorfunction returns True for all coroutines
        # however we know that it is NOT possible to have a generator
        # coroutine in python 3.5: PEP525 was not there yet
        generatorcaller = isgeneratorfunction(
            caller) and not iscoroutinefunction(caller)
    else:
        generatorcaller = isgeneratorfunction(caller)
    if generatorcaller:
        fun = FunctionMaker.create(
            func, "for res in _call_(_func_, %s%%(shortsignature)s):\n"
                  "    yield res" % es, evaldict, __wrapped__=func)
    else:
        fun = FunctionMaker.create(
            func, "return _call_(_func_, %s%%(shortsignature)s)" % es,
            evaldict, __wrapped__=func)
    if hasattr(func, '__qualname__'):
        fun.__qualname__ = func.__qualname__
    return fun
112176
def iapply(function, *iterables):
    

    iterables = map(iter, iterables)
    while True:
        args = [next(it) for it in iterables]
        if function is None:
            yield tuple(args)
        else:
            function(*args)
            yield args[0]
737050
def generate(fn):
    ''''''
    if isinstance(fn, str):
        return lambda f: generate(f).desc(fn)

    @wraps(fn)
    @Parser
    def generated(text, index):
        iterator, value = fn(), None
        try:
            while True:
                parser = iterator.send(value)
                res = parser(text, index)
                if not res.status:  # this parser failed.
                    return res
                value, index = res.value, res.index  # iterate
        except StopIteration as stop:
            endval = stop.value
            if isinstance(endval, Parser):
                return endval(text, index)
            else:
                return Value.success(index, endval)
    return generated.desc(fn.__name__)