asyncer
Run groups of (a)sync functions.

@name asyncer
@function
@param {Array|Object} tasks The tasks to run in parallel or one by one.
@param {Function} cb The callback function.
494720
function asyncer (tasks, cb) {

    cb = cb || noop6;

    if (typpy(tasks, Function)) {
        if (tasks.length >= 1) {
            return tasks(cb);
        }
        return fnResult(tasks, cb);
    }

    let normalize = tsks => tsks.map(c => {
        if (typpy(c, Function) && c.length >= 1) {
            return c;
        }

        return done => {
            asyncer(c, done)
        };
    });

    if (typpy(tasks, Object)) {
        tasks = normalize(tasks.parallel || tasks.p);
        sameTime(tasks, cb);
        return;
    }

    if (typpy(tasks, Array)) {
        tasks = normalize(tasks);
        oneByOne(tasks, cb);
        return;
    }

    throw new TypeError("The tasks should be an array or an object.");
}
1327179
@SuppressWarnings("unchecked")
    public void parallel(C context, final Outcome<C> outcome, final Function<C>... functions) {
        final C finalContext = context != null ? context : (C) EMPTY_CONTEXT;
        final CountingControl ctrl = new CountingControl(finalContext, functions);
        progress.reset(functions.length);

        Scheduler.get().scheduleIncremental(new Scheduler.RepeatingCommand() {
            @Override
            public boolean execute() {
                if (ctrl.isAborted() || ctrl.allFinished()) {
                    // schedule deferred so that 'return false' executes first!
                    Scheduler.get().scheduleDeferred(new Scheduler.ScheduledCommand() {
                        @Override
                        @SuppressWarnings("unchecked")
                        public void execute() {
                            if (ctrl.isAborted()) {
                                progress.finish();
                                outcome.onFailure(finalContext);
                            } else {
                                progress.finish();
                                outcome.onSuccess(finalContext);
                            }

                        }
                    });
                    return false;
                } else {
                    // one after the other until all are active
                    ctrl.next();
                    return true;
                }
            }
        });
    }
40836
function list(tasks) {
    return function continuable(callback) {
        var result = []
        var count = 0

        if (tasks.length === 0) {
            return callback(null, result)
        }

        tasks.forEach(function invokeSource(source, index) {
            source(function continuation(err, value) {
                if (err && result) {
                    result = null
                    callback(err)
                } else if (!err && result) {
                    result[index] = value
                    if (++count === tasks.length) {
                        callback(null, result)
                    }
                }
            })
        })
    }
}
798103
private List<Future<Boolean>> startTasks(ExecutorService executor, List<Callable<Boolean>> callables) {
        List<Future<Boolean>> tasks = Lists.newArrayList();
        for (Callable<Boolean> callable : callables) {
            tasks.add(executor.submit(callable));
        }
        return tasks;
    }
1060772
function invokeTask(taskName)
{
    const tc = TASKS.globals.globalTaskCollection;
    const t = tc.getByName(taskName);
    if (t === undefined)
    {
        YERROR.raiseError(`task ${taskName} not found`);
    }

    TASKS.invokeTask(tc, t);    
}
719379
function(callback) {
        var scarlet = new Scarlet(Math.min(opts.n, 100));

        function connect(taskObject) {
            var client = taskObject.task.client;
            var i = taskObject.task.idx;

            client.connect(function() {
                scarlet.taskDone(taskObject);
            });

            client.on("error", function(err) {
                console.log(err + ": Client " + i);
            });
        }

        console.time("Connect");

        // if mode is `clients`, we create (opts.complicating) clients,
        // otherwise we create only one.
        var max = opts["complicating-mode"] === "clients" ? opts.complicating : 1;
        for(var i = 0; i < max; i++) {
            var client = illyria2.createClient("127.0.0.1", SERVER_PORT, {
                runTimeout: 10000,
                retryInterval: 1000,
                reconnect: true
            });

            scarlet.push({ idx: i, client: client }, connect);

            clients.push(client);
        }

        scarlet.afterFinish(max, function() {
            console.timeEnd("Connect");
            callback();
        }, false);
    }
460486
function(list) {

        var i = self.tasksCount;

        if (i > list.length-1) {
            process.exit(0)
        }

        var err = false;
        var cb = ( typeof(list[i].cb) != 'undefined' ) ? list[i].cb : false;

        if (cb) {
            list[i].func( function done(err, data) {
                if (err) {
                    console.error(err.stack||err.message);
                    process.exit(1)
                } else {
                    if (data) {
                        //var str = data.toString();
                        console.info(data);
                    }
                    ++self.tasksCount;
                    run(list)
                }

            })
        } else {
            try {
                list[i].func();
                ++self.tasksCount;
                run(list)
            } catch (err) {
                console.error(err.stack);
                process.exit(1)
            }
        }
    }
1370930
@SuppressWarnings("unchecked")
    @TargetApi(VERSION_CODES.HONEYCOMB)
    public static <T> void execute(AsyncTask<T, ?, ?> task, T... args) {
        if (Build.VERSION.SDK_INT < VERSION_CODES.HONEYCOMB) {
            task.execute(args);
        } else {
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, args);
        }
    }
308447
public function task($task, Closure $callback = null)
    {
        if (isset($this->tasks[$task])) {
            $this->run($this->tasks[$task], $callback);
        }
    }
612097
function _process(templates, params, cb) {
    var _templates = _.extend(templates, {}), // process template copies, not the originals
      tasks = {};

    _.keys(_templates).forEach(function (key) {
      tasks[key] = function (cb) {
        _templates[key].process(params, function (data) {
          cb(null, data);
        });
      };
    });

    async.parallel(tasks, function (err, results) {
      cb(results);
    });
  }
703587
function startRelay(cb) {
        var asyncArr = [],
            hashedPassword = '',
            self = this;

        if (this.process) {
            return cb();
        }

        if (!this.service.socks.port) {
            asyncArr.push(function (cb) {
                freeport(function (err, port) {
                    self.service.socks.port = port;
                    return cb(err);
                });
            });
        }
        if (!this.service.control.port) {
            asyncArr.push(function (cb) {
                freeport(function (err, port) {
                    self.service.control.port = port;
                    return cb(err);
                });
            });
        }

        if (!this.dataDirectory) {
            asyncArr.push(function (cb) {
                var dirname = crypto.createHash('sha1')
                    .update(Date.now().toString() + Math.random().toString())
                    .digest('hex');
                if (self.cleanUpOnExit) {
                    temp.track();
                }
                temp.mkdir(dirname, function (err, path) {
                    self.dataDirectory = path;
                    return cb(err);
                });
            });
        }

        // hash a password
        if (this.service.control.password) {
            asyncArr.push(function (cb) {
                var hashedPasswordCmd;

                hashedPasswordCmd = spawn('tor', ['--hash-password', self.service.control.password]);
                hashedPasswordCmd.stdout.on('data', function (data) {
                    hashedPassword += data.toString();
                });
                hashedPasswordCmd.stdout.on('end', function (status) {
                    if (status) {
                        return cb(new Error('Can not hash your password (Exit status: ' + status + ')'));
                    }
                    hashedPassword = hashedPassword.match(/16:[A-F0-9]{58}/)[0];
                    return cb();
                });
            });
        }

        async.parallel(asyncArr, function (err) {
            var timeout,
                listener = function (event) {
                    if (event.message.indexOf('Tor has successfully opened a circuit') !== -1) {
                        self.removeListener('notice', listener);
                        clearTimeout(timeout);
                        /**
                         * @event TorRequest#ready
                         */
                        self.emit('ready');
                        /**
                         * @callback TorRelay~startCallback
                         * @param {null| error} error - Error if there was one
                         */
                        return cb();
                    }
                },
                params = [//'--RunAsDaemon', '0',
                    '--CookieAuthentication', '0',
                    '--ControlPort', self.service.control.port,
                    //'--PidFile', 'tor.pid',
                    '--SocksPort', self.service.socks.port,
                    '--DataDirectory', self.dataDirectory],
                startFn,
                tries = 0,
                restart;
            if (err) {
                return cb(err);
            }

            if (hashedPassword) {
                params.push('--HashedControlPassword', hashedPassword);
            }
            if (self.service.socks.username && self.service.socks.password) {
                params.push('--Socks5ProxyUsername', self.service.socks.username,
                    '--Socks5ProxyPassword', self.service.socks.password);
            }

            self.on('notice', listener);

            startFn = function () {
                restart = false;
                self.process = spawn('tor', params);
                self.process.on('exit', function () {
                    if (restart) {
                        return startFn();
                    }
                    self.process = null;
                    self.control = null;
                });

                self.process.stdout.on('data', function (chunk) {
                    var arr = chunk.toString().split(/\r?\n/),
                        i,
                        tmp,
                        year = (new Date()).getFullYear();

                    for (i = 0; i < arr.length; i += 1) {
                        if (arr[i] !== '') {
                            tmp = {
                                type: arr[i].substring(arr[i].indexOf('[') + 1, arr[i].indexOf(']')),
                                date: new Date(arr[i].substr(0, 7) + year + arr[i].substr(6, 12)),
                                message: arr[i].substr(arr[i].indexOf(']') + 2),
                                data: arr[i]
                            };
                            /**
                             * @event TorRequest#notice
                             * @type {{}}
                             * @property {string} type - Type of message
                             * @property {Array} messages - Array of messages
                             * @property {number} code - Status code
                             * @property {string} type - Type of message
                             */
                            /**
                             * @event TorRequest#warn
                             * @type {{}}
                             * @property {string} type - Type of message
                             * @property {Array} messages - Array of messages
                             * @property {number} code - Status code
                             * @property {string} type - Type of message
                             */
                            self.emit(tmp.type, tmp);
                        }

                    }
                });

                timeout = setTimeout(function () {
                    console.error('Can not establish a circuit');
                    self.process.kill('SIGKILL');
                    tries += 1;
                    if (self.retries >= tries) {
                        console.error('Retry establishing a circuit', tries);
                        //self.removeAllListeners('notice');
                        //self.removeAllListeners('warn');
                        restart = true;
                        return;
                    }
                    cb(new Error('Can not establish a connection to a circuit'));
                }, self.timeout);
            };

            startFn();



            self.control = new TorControl({
                port: self.service.control.port,
                password: self.service.control.password
            });
        });

    }
527146
function doWork(cb) {
  async.series([
    async.apply(deleteTags),
    async.apply(createTag)
  ], cb);
}
246250
async function run(task, action, ...args) {
  const command = process.argv[2]
  const taskName =
    command && !command.startsWith('-') ? `${task} ${command}` : task
  const start = new Date()
  process.stdout.write(`Starting '${taskName}'...\n`)
  try {
    await action(...args)
    process.stdout.write(
      `Finished '${taskName}' after ${new Date().getTime() -
        start.getTime()}ms\n`
    )
  } catch (error) {
    process.stderr.write(`${error.stack}\n`)
  }
}
907474
function TaskRun(target) {
    this.name = target.name || 0;
    this.files = target.files || [];
    this._getConfig = target._getConfig;
    this.options = target.options;
    this.startedAt = false;
    this.spawned = null;
    this.changedFiles = Object.create(null);
    this.spawnTaskFailure = false;
    this.livereloadOnError = true;
    if (typeof this.options.livereloadOnError !== 'undefined') {
      this.livereloadOnError = this.options.livereloadOnError;
    }
  }
763254
function runSync(context, func, callback)
{
  var result
    , requiresContext = isArrowFunction(func)
    ;

  try
  {
    if (requiresContext)
    {
      result = func.call(null, context);
    }
    else
    {
      result = func.call(context);
    }
  }
  catch (ex)
  {
    // pass error as error-first callback
    callback(ex);
    return;
  }

  // everything went well
  callback(null, result);
}
89655
public static void runAsyncTask(Object context, int asyncTaskId, Object... args) {
		
		if(!ProfileService.getInstance(context).isActive(context, Profile.THREADING)) {

			StringBuilder builder = new StringBuilder()
			.append("Async task with ID ")
			.append(asyncTaskId)
			.append("cannot be run since the threading profile is inactive.");
			
			Log.w("Async task cannot ", builder.toString());

			return;
		}
		
		TaskManagers.ASYNC.execute(context, asyncTaskId, args);
	}
481424
@FFDCIgnore(value = { RejectedExecutionException.class })
    @Override
    public <T> List<PolicyTaskFuture<T>> invokeAll(Collection<? extends Callable<T>> tasks, PolicyTaskCallback[] callbacks) throws InterruptedException {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        // Determine if we need a permit to run one or more of the tasks on the current thread, and if so, acquire it,
        int taskCount = tasks.size();
        boolean havePermit = false;
        boolean useCurrentThread = maxPolicy == MaxPolicy.loose || (havePermit = taskCount > 0 && maxConcurrencyConstraint.tryAcquire());

        List<PolicyTaskFutureImpl<T>> futures = new ArrayList<PolicyTaskFutureImpl<T>>(taskCount);
        try {
            // create futures in advance, which gives the callback an opportunity to reject
            int t = 0;
            for (Callable<T> task : tasks) {
                PolicyTaskCallback callback = callbacks == null ? null : callbacks[t++];
                PolicyExecutorImpl executor = callback == null ? this : (PolicyExecutorImpl) callback.getExecutor(this);
                long startTimeoutNS = callback == null ? startTimeout : callback.getStartTimeout(executor.startTimeout);
                futures.add(new PolicyTaskFutureImpl<T>(executor, task, callback, startTimeoutNS));
            }

            // enqueue tasks (except the last if we are able to run tasks on the current thread)
            int numToSubmitAsync = useCurrentThread ? taskCount - 1 : taskCount;
            t = 0;
            for (PolicyTaskFutureImpl<T> taskFuture : futures)
                if (t++ < numToSubmitAsync || taskFuture.executor != this) {
                    boolean enqueued;
                    if (useCurrentThread && taskFuture.executor == this)
                        enqueued = taskFuture.executor.enqueue(taskFuture, 0, true);
                    else
                        enqueued = taskFuture.executor.enqueue(taskFuture, taskFuture.executor.maxWaitForEnqueueNS.get(), null);

                    if (!enqueued) // must immediately return if ran on current thread and was interrupted
                        taskFuture.throwIfInterrupted();
                } else {
                    taskFuture.accept(true);
                }

            // run on current thread (by current executor) if possible
            if (useCurrentThread)
                for (t = numToSubmitAsync; t >= 0; t--) {
                    PolicyTaskFutureImpl<T> taskFuture = futures.get(t);
                    State currentState = taskFuture.executor.state.get();
                    if (taskFuture.executor == this && t == numToSubmitAsync) { // we intentionally avoided submitting the last task
                        if (currentState != State.ACTIVE)
                            throw new RejectedExecutionException(Tr.formatMessage(tc, "CWWKE1202.submit.after.shutdown", taskFuture.getIdentifier()));
                    } else if (taskFuture.executor == this && !taskFuture.isDone() && currentState.canStartTask && queue.remove(taskFuture)) {
                        maxQueueSizeConstraint.release();
                        taskFuture.nsQueueEnd = System.nanoTime();
                    } else {
                        if (trace && tc.isDebugEnabled())
                            Tr.debug(this, tc, "no longer in queue, or this executor is unable to run it", taskFuture);
                        continue; // other thread could already be processing the task, or it could be cancelled
                    }

                    if (taskFuture.nsStartBy == taskFuture.nsAcceptBegin - 1 // never times out, or
                        || taskFuture.nsStartBy - taskFuture.nsQueueEnd > 0) // have time remaining
                        runTask(taskFuture);
                    else { // timed out
                        taskFuture.nsRunEnd = taskFuture.nsQueueEnd;
                        RejectedExecutionException x = new RejectedExecutionException(new StartTimeoutException( //
                                        taskFuture.getIdentifier(), taskFuture.getTaskName(), //
                                        taskFuture.nsQueueEnd - taskFuture.nsAcceptBegin, //
                                        taskFuture.nsStartBy - taskFuture.nsAcceptBegin));
                        taskFuture.abort(false, x);
                        throw x;
                    }

                    // must immediately return if current thread is interrupted
                    taskFuture.throwIfInterrupted();
                }

            // wait for completion
            for (PolicyTaskFutureImpl<T> future : futures) {
                future.await();
                taskCount--;
            }
        } catch (RejectedExecutionException x) {
            if (trace && tc.isDebugEnabled())
                Tr.debug(this, tc, "rejected", x);
            if (x.getCause() instanceof InterruptedException)
                throw (InterruptedException) x.getCause();
            else
                throw x;
        } finally {
            if (havePermit)
                transferOrReleasePermit();

            if (taskCount != 0)
                for (Future<T> f : futures)
                    f.cancel(true);
        }

        @SuppressWarnings({ "rawtypes", "unchecked" })
        List<PolicyTaskFuture<T>> list = (List) futures;
        return list;
    }