/*
Internal function to run the generator, waiting on
each side-effect's returned Promise.

Each side-effect function is executed via standard
JavaScript `Function.prototype.call`.

Returns a Promise of the return value from
the generator.
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);
  }
}
693889
function execPromise (fn) {
  return new Promise(function (resolve) {
    resolve(fn(process.argv.slice(2)))
  }).then(onSuccess, onError)
}
619579
function generatorToPromise(fn) {
    if (typeof fn !== 'function') {
        throw Error('fn is not a function');
    }
    if (!isGenerator(fn)) {
        // assume it's Promise-based
        return fn;
    }
    return co.wrap(fn);
}
412675
function(err,data){
                            if (fiber.callbackAlreadyCalled)
                                 throw new Error("Callback for function "+fnName+" called twice. Wait.for already resumed the execution.");
                            fiber.callbackAlreadyCalled = true;
                            fiber.err=err; //store err on fiber object
                            fiber.data=data; //store data on fiber object
                            if (!fiber.yielded) {//when callback is called *before* async function returns
                                // no need to "resume" because we never got the chance to "yield"
                                return;
                            }
                            else {
                                //resume fiber after "yield"
                                fiber.run();   
                            }
                        }
502257
function co(gen) {
  var ctx = this;
  var args = slice.call(arguments, 1)

  // we wrap everything in a promise to avoid promise chaining,
  // which leads to memory leak errors.
  // see https://github.com/tj/co/issues/180
  return new Promise(function(resolve, reject) {
    if (typeof gen === 'function') gen = gen.apply(ctx, args);
    if (!gen || typeof gen.next !== 'function') return resolve(gen);

    onFulfilled();

    /**
     * @param {Mixed} res
     * @return {Promise}
     * @api private
     */

    function onFulfilled(res) {
      var ret;
      try {
        ret = gen.next(res);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }

    /**
     * @param {Error} err
     * @return {Promise}
     * @api private
     */

    function onRejected(err) {
      var ret;
      try {
        ret = gen.throw(err);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }

    /**
     * Get the next value in the generator,
     * return a promise.
     *
     * @param {Object} ret
     * @return {Promise}
     * @api private
     */

    function next(ret) {
      if (ret.done) return resolve(ret.value);
      var value = toPromise.call(ctx, ret.value);
      if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
      return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
        + 'but the following object was passed: "' + String(ret.value) + '"'));
    }
  });
}
538676
function invokeFunction(promise, child, func) {
  var value = promise.value;
  var state = promise.state;

  // If we have a function to run, run it
  if (typeof func === 'function') {
    try {
      value = func(value);
    } catch (err) {
      rejectPromise(child, err);
      return;
    }

    resolvePromise(child, value);
  }

  else if (state === FULFILLED) {
    resolvePromise(child, value);
  }

  else if (state === FAILED) {
    rejectPromise(child, value);
  }
}
794570
def call(self):
        
        is_mutable = False
        if self.token.nature == Nature.MUT:
            is_mutable = True
            self._process(Nature.MUT)

        identifier = Identifier(name=self.token.value)
        self._process(Nature.ID)

        if self.token.nature == Nature.LPAREN:
            return FunctionCall(identifier=identifier, parameters=self.parameters())
        else:
            return Variable(identifier=identifier, is_mutable=is_mutable)
196561
function invoke(method, arg) {
          var result = generator[method](arg);
          var value = result.value;
          return value instanceof AwaitArgument
            ? Promise.resolve(value.arg).then(invokeNext, invokeThrow)
            : Promise.resolve(value).then(function(unwrapped) {
            // When a yielded Promise is resolved, its final value becomes
            // the .value of the Promise<{value,done}> result for the
            // current iteration. If the Promise is rejected, however, the
            // result for this iteration will be rejected with the same
            // reason. Note that rejections of yielded Promises are not
            // thrown back into the generator function, as is the case
            // when an awaited Promise is rejected. This difference in
            // behavior between yield and await is important, because it
            // allows the consumer to decide what to do with the yielded
            // rejection (swallow it and continue, manually .throw it back
            // into the generator, abandon iteration, whatever). With
            // await, by contrast, there is no opportunity to examine the
            // rejection reason outside the generator function, so the
            // only option is to throw it from the await expression, and
            // let the generator function handle the exception.
            result.value = unwrapped;
            return result;
          });
        }
158194
function Deferred () {
	var self      = this;

	this.promise  = promise.factory();
	this.onDone   = [];
	this.onAlways = [];
	this.onFail   = [];

	// Setting handlers to execute Arrays of Functions
	this.promise.then( function ( arg ) {
		promise.delay( function () {
			array.each( self.onDone, function ( i ) {
				i( arg );
			});

			array.each( self.onAlways, function ( i ) {
				i( arg );
			});

			self.onAlways = [];
			self.onDone   = [];
			self.onFail   = [];
		});
	}, function ( arg ) {
		promise.delay( function () {
			array.each( self.onFail, function ( i ) {
				i( arg );
			});

			array.each( self.onAlways, function ( i ) {
				i( arg );
			});

			self.onAlways = [];
			self.onDone   = [];
			self.onFail   = [];
		});
	});
}
56776
function evaluatePromise() {
  var promise = kew.defer();
  var args = utils.toArray(arguments);
  args.push(promise.makeNodeResolver());
  /*jshint validthis:true */
  evaluate.apply(this, args);
  return promise;
}
1096790
function promiseOrCallback (callback, executor) {
    var promise = new Promise(executor);

    // no callback: do not attach
    if (typeof callback !== 'function') {
        return promise;
    }

    return promise.then(function (value) {
        setImmediate(function () {
            callback(null, value);
        });
        return value;
    }, function (error) {
        setImmediate(function () {
            callback(error);
        });
        throw error;
    });
}
1014799
function (args, start) {
    var start = start || 0
    return Array.prototype.slice.call(args, start)
  }
734924
function listenAndPromise(callback, bindContext) {
        var me = this;
        bindContext = bindContext || this;
        this.willCallPromise = (this.willCallPromise || 0) + 1;

        var removeListen = this.listen(function() {

            if (!callback) {
                throw new Error("Expected a function returning a promise but got " + callback);
            }

            var args = arguments,
                returnedPromise = callback.apply(bindContext, args);
            return me.promise.call(me, returnedPromise);
        }, bindContext);

        return function () {
          me.willCallPromise--;
          removeListen.call(me);
        };

    }
1201718
function callHandler(fn, req, res, next) {
    let context = new Context(req, res);
    if (utils.isGeneratorFunction(fn)) {
        co(fn).call(context, function (err) {
            if (err || !res.terminated) {
                next(err);
            }
        });
    } else {
        fn.call(context);
        if (!res.terminated) {
            next();
        }
    }
}
1292808
function execAsCallback(genFn) {
  const args = Array.prototype.slice.call(arguments, 1);
  const callback = args.pop();
  if (typeof callback !== 'function') {
    throw new TypeError(`the last argument must be a callback function`);
  }
  return genFnToPromise(genFn).apply(this, args).then(ret => callback(null, ret)).catch(callback);
}
516732
function Deferred(opts){
 	/**
	 * @define {object} Collection of public methods.
	 */
	var self = {};

	/**
	 * @define {object} options for the constructor 
	 */
	var opts = opts || {};

	/**
	 * @define {object} A promise object that will be returned
	 */
	var promise = {};

	/**
	 * @define {object} Event system for controlling events
	 */
	var event = Event();
	
	/**
	 * Promise then method
	 * This is for chaining promis callbacks
	 * @example promiseFunction().then(
	 * function(){ // success }, 
	 * function(){ // rejected }, 
	 * function(){ // notify } 
	 * ).then( ... );
	 * @param {function} sucess Success callback
	 * @param {function} reject Reject callback
	 * @param {function} notify notify callback
	 * @return {object} Returns the promise object
	 */
	function promiseThen(success, reject, notify){
		/**
		 * @define {object} Return a new promise
		 */
		var def = Deferred();

		/**
		 * Resolved promise
		 * @example example
		 * @param {string} A string key for the event system
		 * @param {function} A callback when event is triggered
		 * @return {object} Returns promise object
		 */
		event.on('resolve', function(){ 
			/**
			 * If the success callback returns a promise
			 * then resolve/reject/notify that returned promise
			 */
			var promise = success();
			if(!promise) return;
			promise.success(function(){
				/** handle the returned deferred object */
				def.resolve();
			});
			promise.error(function(){
				def.reject();
			});
			promise.notify(function(){
				def.notify();
			});
		});

		/**
		 * If promise is rejected/notify trigger the callback
		 */
		event.on('reject', function(){ 
			if(reject) reject();
		});

		event.on('notify', function(){ 
			if(notify) notify();
		});

		/**
		 * @return {object} Returns a promise object
		 */
		return def.promise; 
	}

	/**
	 * Promise methods
	 * @example promise.then( //new promise ).then(...)
	 * @example promise.success(...).error(...).notify(...)
	 * @param {function} callback A callback for the promise
	 * @return {object} Return the promise
	 */
	function promiseSuccess(callback){
		event.on('resolve', callback);
		return promise;
	}

	function promiseError(callback){
		event.on('reject', callback);
		return promise;
	}

	function promiseNotified(callback){
		event.on('notify', callback);
		return promise;
	}

	/**
	 * Deferred methods to trigger the promise
	 * @example def.resolve(args)
	 * @example def.reject(args)
	 * @example def.notify(args)
	 */
	function resolve(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('resolve', args);
	}

	function reject(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('reject', args);	
	}

	function notify(){
		var args = Array.prototype.slice.call(arguments);
		event.trigger('notify', args);		
	}

	/**
	 * Add the promise methods to the promise object
	 */
	promise.then = promiseThen;
	promise.success = promiseSuccess;
	promise.error = promiseError;
	promise.notify = promiseNotified;

	/**
	 * The promise object
	 * @public {object}
	 */
	self.promise = promise;

	/**
	 * Deferred public methods	
	 * @public {function}
	 */
	self.resolve = resolve;
	self.reject = reject;
	self.notify = notify;

	/**
	 * @return {object} return public methos
	 */
	return self;
}
705740
function(err) {
		/**
		 * If err is an Error object, break the chain and call catch
		 */
		if (err && (err.constructor.name === "Error" || err.constructor.name === "TypeError") && this.onCatch) {
			this.onCatch(err);
			return;
		}

		var nextFn = this.fnStack.shift();
		if (nextFn) {
			/**
			 * Ensure arguments are passed as an Array
			 */
			var args = Array.prototype.slice.call(arguments);
			return this.execute(nextFn.fn, args);
		}
	}