Generate the return function for taskObject. Each task needs a specific function to bind the response to correct order of call
765261
function binder(taskID) {
		expected++;
		return function(ret) {
			expected--;
			if(!returned && taskID !== 'false') {
				if		(typeof taskID == 'number') returned=[];
				else if (typeof taskID == 'string') returned={};
			};
			taskID !== false ? returned[taskID]=ret : returned = ret;
			// Timeout needed to increment expected, if next item exists.
			// If it run without timeout, expected always be 0 and only
			// the first function of the group will be executed.
			setTimeout(function(){if (! expected) runQueue();},1);
		}
	}
879060
function injectNumbers (funcs, task) {
  /**
   * Inject a function that returns a number.
   */

  function inject (taskKey) {
    var taskName = task[taskKey]

    var num = parseFloat(taskName)

    if (!isNaN(num)) {
      funcs[taskName] = function () { return num }
    }
  }

  Object.keys(task)
    .forEach(inject)
}
532760
function(tasks, callback) {

      var keys; var length; var i; var results; var kind;
      var updated_tasks = [];
      var is_object;
      var counter = 0;

      if (isArray(tasks)) {

        length = tasks.length;
        results = [];

      } else if (isObject(tasks)) {

        is_object = true;
        keys = ObjectKeys(tasks);
        length = keys.length;
        results = {};

      } else {
        return callback();
      }

      for (i=0; i<length; i++) {

        if (is_object) {
          updated_tasks.push({ k: keys[i], t: tasks[keys[i]] });
        } else {
          updated_tasks.push({ k: i, t: tasks[i] });
        }

      }

      updated_tasks.forEach(function(task_object) {

        task_object.t(function(err, result) {
          if (err) return callback(err);

          results[task_object.k] = result;

          counter++;
          if (counter == length) callback(null, results);
        });

      });

    }
437075
def sync_fetch(self, task):
        ''''''
        if not self._running:
            return self.ioloop.run_sync(functools.partial(self.async_fetch, task, lambda t, _, r: True))

        wait_result = threading.Condition()
        _result = {}

        def callback(type, task, result):
            wait_result.acquire()
            _result['type'] = type
            _result['task'] = task
            _result['result'] = result
            wait_result.notify()
            wait_result.release()

        wait_result.acquire()
        self.ioloop.add_callback(self.fetch, task, callback)
        while 'result' not in _result:
            wait_result.wait()
        wait_result.release()
        return _result['result']
1001703
function generatePromise (promiseFunctions, contraMethod, silenceErrors) {
  return new Promise((resolve, reject) => {
    // Generate a function that executes the promise function and
    // calls back in a way that the contra library requires
    for (let i in promiseFunctions) {
      let promiseFunction = promiseFunctions[i]

      if (!isFunction(promiseFunction)) {
        return reject(new Error('One of the supplied promise functions is not a function'))
      }

      promiseFunctions[i] = (contraCallback) => {
        promiseFunction()
          .then(data => contraCallback(null, data))
          .catch(err => silenceErrors ? contraCallback(null, null) : contraCallback(err))
      }
    }

    contraMethod(promiseFunctions, (err, results) => {
      if (err) return reject(err)
      resolve(results)
    })
  })
}
1173104
function getHandler(fn) {
    if (isFunction(fn) && fn.actionHandler) {
        return function (req, res, next) {
            terminateMethods.map(function (method) {
                res[method] = getWrappedResponse(res[method]);
            });
            callHandler(fn, req, res, next);
        };
    } else {
        return fn;
    }
}
448541
function() {
    // A stack, latest task is the last item in the array
    this.tasks = [];
    this.currentLine = 0;

    // Keeping track of current line in the log
    // Shadow stdout.write and stderr.write
    newlines(process.stdout);
    newlines(process.stderr);
    process.stderr.on('newline', function() {
        this.currentLine++;
    }.bind(this));
    process.stdout.on('newline', function() {
        this.currentLine++;
    }.bind(this));

    // Functions to expose
    this.log = function() {
        // Similar to console.log, but nested appropriately
        const args = [].slice.call(arguments);
        log(console.log, args, this.tasks.length);
    };

    this.error = function() {
        // Similar to console.error, but nested appropriately
        const args = [].slice.call(arguments);
        log(console.error, args, this.tasks.length);
    };

    /**
     *  Task tracking, acts almost like a wrapper around Promise(func(resolve, reject))
     *  If the passed in function takes no arguments, then it is assumed to be a sync
     *  call that may throw (reject) or return a value (resolve)
     *
     *  @returns Promise that resolves/rejects as if the contents, but adds some
     *  logging logic around it
     */
    this.task = function(taskName, taskFunction) {
        const indentation = this.tasks.length;
        const lines = indentation === 0 ? 1 : 0;

        // Push a simple task object to the queue
        const task = {
            name: taskName,
            line: this.currentLine + lines,
            indentation: indentation
        };

        const introLine = `${_.repeat('\t', indentation)}${taskName}`;

        const finish = function(t, succeed, err) {
            const idx = _.findIndex(this.tasks, t);
            if (idx === -1) {
                throw new Error('Task is not part of the logger');
            }

            // Remove from tasks
            this.tasks.splice(idx, 1);

            // Create message to write, then decide where to write
            let message;
            if (succeed) {
                message = `${introLine} ${chalk.green('✔')}`;
            } else if (err) {
                message = `${introLine} ${chalk.red('✖')} ${err.message}`;
            } else {
                message = `${introLine} ${chalk.red('✖')}`;
            }

            // Simple check, if on next line of the task, append to previous line
            // otherwise add a new line
            if (this.currentLine === task.line + 1) {
                cursor.up(1).eraseLine().write(message).down(1).horizontalAbsolute(0);
            } else {
                cursor.write(message).write('\n\n');
            }
        }.bind(this);

        return new Promise(function(resolve, reject) {
            // If there are currently no tasks, add an empty line
            // (top-level or first tasks are separated by empty lines)
            if (this.tasks.length === 0) {
                cursor.write('\n');
            }

            // Print out the task name
            cursor.write(`${introLine}\n`);

            // Add to the tasks array
            this.tasks.push(task);

            if (taskFunction.length === 0) {
                // Sync task
                try {
                    const result = taskFunction();
                    finish(task, true, null);
                    resolve(result);
                } catch (err) {
                    finish(task, false, err);
                    reject(err);
                }
            } else {
                // Async task
                const res = function(value) {
                    finish(task, true, null);
                    resolve(value);
                };

                const rej = function(err) {
                    finish(task, false, err);
                    reject(err);
                };

                taskFunction(res, rej);
            }
        }.bind(this));
    };

    return this;
}
1001702
function () {
    if (this._lock) return
    this._lock = true
    let task = this._tasks.shift()
    let tstType = this.error ? ['catch', 'end'] : ['then', 'end']
    while (task && !~tstType.indexOf(task.type)) {
      task = this._tasks.shift()
    }
    if (task) {
      let cb = (err, res) => {
        this.error = err
        this.result = res || this.result
        this._lock = false
        this._run()
      }
      let fn = task.fn
      if (task.type === 'end') { // .end
        fn(this.error, this.result)
      } else {
        try {
          if (task.type === 'catch') { // .catch
            fn(this.error, this.result, cb)
          } else { // .then
            fn(this.result, cb)
          }
        } catch (e) {
          cb(e)
        }
      }
    } else {
      this._lock = false
    }
  }
598549
def to_task(self):
    """"""
    # Never pass params to taskqueue.Task. Use payload instead. Otherwise,
    # it's up to a particular taskqueue implementation to generate
    # payload from params. It could blow up payload size over limit.
    return taskqueue.Task(
        url=self.url,
        payload=self._payload,
        name=self.name,
        eta=self.eta,
        countdown=self.countdown,
        headers=self._headers)
302955
def catch_result(task_func):
    

    @functools.wraps(task_func, assigned=available_attrs(task_func))
    def dec(*args, **kwargs):
        # inicialize
        orig_stdout = sys.stdout
        sys.stdout = content = StringIO()
        task_response = task_func(*args, **kwargs)
        # catch
        sys.stdout = orig_stdout
        content.seek(0)
        # propagate to the response
        task_response['stdout'] = content.read()
        return task_response
    return dec
1057098
function sequence(tasks /* Any Arguments */) {
    const args = Array.prototype.slice.call(arguments, 1);

    return Promise.reduce(tasks, function (results, task) {
        const response = task.apply(this, args);

        if (response && response.then) {
            return response.then(function (result) {
                results.push(result);
                return results;
            });
        } else {
            return Promise.resolve().then(() => {
                results.push(response);
                return results;
            });
        }
    }, []);
}
1019556
def delay(self, func, args=None, kwargs=None, queue=None,
              hard_timeout=None, unique=None, lock=None, lock_key=None,
              when=None, retry=None, retry_on=None, retry_method=None,
              max_queue_size=None):
        

        task = Task(self, func, args=args, kwargs=kwargs, queue=queue,
                    hard_timeout=hard_timeout, unique=unique,
                    lock=lock, lock_key=lock_key,
                    retry=retry, retry_on=retry_on, retry_method=retry_method)

        task.delay(when=when, max_queue_size=max_queue_size)

        return task
213977
function injectDotOperators (funcs, task) {
  /**
   * Inject dot operator.
   */

  function inject (taskKey) {
    var taskName = task[taskKey]

    /**
     * Dot operator function.
     *
     * @param {String} attributeName
     * @param {Object} obj
     * @param {...} rest of arguments
     *
     * @returns {*} result
     */

    function dotOperatorFunc (attributeName, obj) {
      var func

      if (obj) func = obj[attributeName]

      if (typeof func === 'function') {
        return func.apply(obj, Array.prototype.slice.call(arguments, 2))
      }
    }

    if (regexDotOperator.func.test(taskName)) {
      // .foo() -> foo
      funcs[taskName] = dotOperatorFunc.bind(null, taskName.substring(1, taskName.length - 2))
    }

    /**
     * Dot operator attribute write.
     *
     * @param {String} attributeName
     * @param {Object} obj
     * @param {*} attributeValue
     *
     * @returns {Object} obj modified
     */

    function dotOperatorAttributeWrite (attributeName, obj, attributeValue) {
      obj[attributeName] = attributeValue

      return obj
    }

    if (regexDotOperator.attrWrite.test(taskName)) {
      // .foo= -> foo
      funcs[taskName] = dotOperatorAttributeWrite.bind(null, taskName.substring(1, taskName.length - 1))
    }

    /**
     * Dot operator attribute read.
     *
     * @param {String} attributeName
     * @param {Object} obj
     *
     * @returns {*} attribute
     */

    function dotOperatorAttributeRead (attributeName, obj) {
      var attr

      if (obj) attr = obj[attributeName]

      if (typeof attr === 'function') return attr.bind(obj)

      return attr
    }

    if (regexDotOperator.attrRead.test(taskName)) {
      // .foo -> foo
      funcs[taskName] = dotOperatorAttributeRead.bind(null, taskName.substring(1))
    }
  }

  Object.keys(task).forEach(inject)
}
624560
function(tasks) {
		var l = tasks.length,
			chain = function(task, idx) {
				++idx;
				if (tasks[idx]) {
					return chain(task.then(tasks[idx]), idx);
				} else {
					return task;
				}
			};
		if (l > 1) {
			return chain(tasks[0](), 0);
		} else {
			return tasks[0]();
		}
	}
1197006
function utilTask( methodCallback, methodType, methodSchema ) {
        function tackTask( opt, success ) {
            var async;

            success = success || Noop;
            
            if ( opt.async ) {
                async = opt.async;
                delete opt.async;
            }

            if ( async ) {
                nextTick( nextTickTask, methodCallback, this, opt, success, methodType );
            }
            else {
                nextTickTask( methodCallback, this, opt, success, methodType );
            }

            return this;
        }

        Object.defineProperty( tackTask, 'task', { value: methodSchema || true });
        Object.defineProperty( tackTask, 'callback', { value: methodCallback });

        return tackTask;
    }
1315854
def _taskify(func):
	''''''
	if not isinstance(func, _Task):
		func = _Task(func)

		spec = inspect.getargspec(func.func)
		if spec.args:
			num_args = len(spec.args)
			num_kwargs = len(spec.defaults or [])
			isflag = lambda x, y: '' if x.defaults[y] is False else '='

			func.args = spec.args[:(num_args - num_kwargs)]
			func.defaults = {spec.args[i - num_kwargs]: spec.defaults[i] for i in range(num_kwargs)}
			func.kwargs = [key.replace('_','-') + isflag(func, key) for key in func.defaults]

		if not func.name.startswith('_'):
			TASKS.append(func)

	return func
1052085
def synctasklet(func):
  
  taskletfunc = tasklet(func)  # wrap at declaration time.

  @utils.wrapping(func)
  def synctasklet_wrapper(*args, **kwds):
    # pylint: disable=invalid-name
    __ndb_debug__ = utils.func_info(func)
    return taskletfunc(*args, **kwds).get_result()
  return synctasklet_wrapper