Run functions, provided by string name, on multiple cores on the current machine.
971680
def runner(parallel, config):
    
    def run_parallel(fn_name, items):
        items = [x for x in items if x is not None]
        if len(items) == 0:
            return []
        items = diagnostics.track_parallel(items, fn_name)
        fn, fn_name = (fn_name, fn_name.__name__) if callable(fn_name) else (get_fn(fn_name, parallel), fn_name)
        logger.info("multiprocessing: %s" % fn_name)
        if "wrapper" in parallel:
            wrap_parallel = {k: v for k, v in parallel.items() if k in set(["fresources", "checkpointed"])}
            items = [[fn_name] + parallel.get("wrapper_args", []) + [wrap_parallel] + list(x) for x in items]
        return run_multicore(fn, items, config, parallel=parallel)
    return run_parallel
383968
def run(self):
        '''
        
        '''
        salt.utils.process.appendproctitle(self.name)
        self.clear_funcs = ClearFuncs(
           self.opts,
           self.key,
           )
        self.aes_funcs = AESFuncs(self.opts)
        salt.utils.crypt.reinit_crypto()
        self.__bind()
942751
def run_script(dist_spec, script_name):
    """"""
    ns = sys._getframe(1).f_globals
    name = ns['__name__']
    ns.clear()
    ns['__name__'] = name
    require(dist_spec)[0].run_script(script_name, ns)
713840
def run_once(function, state={}, errors={}):
    """"""
    @six.wraps(function)
    def _wrapper(*args, **kwargs):
        if function in errors:
            # Deliberate use of LBYL.
            six.reraise(*errors[function])

        try:
            return state[function]
        except KeyError:
            try:
                state[function] = result = function(*args, **kwargs)
                return result
            except Exception:
                errors[function] = sys.exc_info()
                raise
    return _wrapper
402397
def run_with_reloader(main_func, extra_files=None, interval=1, reloader_type="auto"):
    """"""
    import signal

    reloader = reloader_loops[reloader_type](extra_files, interval)
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))
    try:
        if os.environ.get("WERKZEUG_RUN_MAIN") == "true":
            ensure_echo_on()
            t = threading.Thread(target=main_func, args=())
            t.setDaemon(True)
            t.start()
            reloader.run()
        else:
            sys.exit(reloader.restart_with_reloader())
    except KeyboardInterrupt:
        pass
1173230
@Override
  public void run() {
    synchronized (lock) {
      if (!callables.hasNext()) {
        checkEnd();
        return;
      }

      for (int i = 0; i < parallelism && callables.hasNext(); i++) {
        setupNext(callables.next());
      }
    }

    future.whenCancelled(() -> {
      cancel = true;
      checkNext();
    });
  }
550656
function doRun() {
    if (Module['calledRun']) return; // run may have just been called while the async setStatus time below was happening
    Module['calledRun'] = true;

    if (ABORT) return;

    ensureInitRuntime();

    preMain();


    if (Module['onRuntimeInitialized']) Module['onRuntimeInitialized']();

    if (Module['_main'] && shouldRunNow) Module['callMain'](args);

    postRun();
  }
92186
def parallel_fn(f):
    

    def simple_parallel(func, sequence, **args):
        """ f takes an element of sequence as input and the keyword args in **args"""
        if 'processes' in args:
            processes = args.get('processes')
            del args['processes']
        else:
            processes = multiprocessing.cpu_count()

        pool = multiprocessing.Pool(processes)  # depends on available cores

        result = pool.map_async(universal_worker, pool_args(func, sequence, args))
        pool.close()
        pool.join()
        cleaned = [x for x in result.get() if x is not None]  # getting results
        cleaned = asarray(cleaned)
        return cleaned
    return partial(simple_parallel, f)
219637
def multiprocessing_ppmap_worker(in_queue, out_queue, func, fixed_arg):
    
    while True:
        i, var_arg = in_queue.get()
        if i is None:
            break
        out_queue.put((i, func(i, fixed_arg, var_arg)))
791482
function(connection, collection, functionName) {
      var args = Array.prototype.slice.call(arguments, 3);
      return connections[connection].runFunction(functionName, args);
    }
947039
def run(input=sys.stdin, output=sys.stdout):
    
    """
    functions = []
    environments = dict()

    def _writejson(obj):
        obj = json.encode(obj)
        if isinstance(obj, unicode):
            obj = obj.encode('utf-8')
        output.write(obj)
        output.write('\n')
        output.flush()

    def _log(message):
        if not isinstance(message, basestring):
            message = json.encode(message)
        _writejson({'log': message})

    def reset(config=None):
        del functions[:]
        return True

    def add_fun(string):
        string = BOM_UTF8 + string.encode('utf-8')
        try:
            function = _compile(string, "map_compilation_error", "map")
        except CompileError as e:
            return e.args[0]
        functions.append(function)
        return True

    def map_doc(doc):
        results = []
        for function in functions:
            try:
                results.append([[key, value] for key, value in function(doc)])
            except Exception, e:
                log.error('runtime error in map function: %s', e,
                          exc_info=True)
                results.append([])
                _log(traceback.format_exc())
        return results

    def reduce(*cmd, **kwargs):
        code = BOM_UTF8 + cmd[0][0].encode('utf-8')
        args = cmd[1]

        try:
            function = _compile(code, "reduce_compilation_error", "reduce")
        except CompileError as e:
            return e.args[0]

        rereduce = kwargs.get('rereduce', False)
        results = []
        if rereduce:
            keys = None
            vals = args
        else:
            if args:
                keys, vals = zip(*args)
            else:
                keys = []
                vals = []
        if function.func_code.co_argcount == 3:
            results = function(keys, vals, rereduce)
        else:
            results = function(keys, vals)
        return [True, [results]]

    def rereduce(*cmd):
        # Note: weird kwargs is for Python 2.5 compat
        return reduce(*cmd, **{'rereduce': True})

    def ddoc_new(name, doc):
        env = dict()
        # key in design doc -> expected function name
        method_mapping = dict(filters='filter', views='map')
        for key, section in doc.iteritems():
            if key not in method_mapping:
                continue
            env[key] = dict()
            id_error = "%s_compilation_error" % (key)
            for f_name, func_str in section.iteritems():
                if isinstance(func_str, dict):
                    env[key][f_name] = dict()
                    for expected_name, code in func_str.iteritems():
                        try:
                            env[key][f_name][expected_name] = _compile(
                                code, id_error, expected_name)
                        except CompileError as e:
                            return e.args[0]
                else:
                    try:
                        expected_name = method_mapping[key]
                        env[key][f_name] = _compile(func_str, id_error,
                                                    expected_name)
                    except CompileError as e:
                        return e.args[0]
        environments[name] = env
        return True

    def ddoc_exec(ddoc_name, ref, args):
        e = environments[ddoc_name]
        for r in ref:
            e = e[r]
        function = e
        h = handlers[ref[0]]

        return h(*args, **{"function": function})

    def ddoc(*args):
        args = list(args)
        n = args.pop(0)
        if n == 'new':
            return ddoc_new(*args)
        return ddoc_exec(n, args.pop(0), args[0])

    def filter(rows, request, dbinfo=None, function=None):
        request['db'] = dbinfo
        results = []

        for row in rows:
            r = function(row, request)
            if r is True:
                results.append(True)
            else:
                results.append(False)

        return [True, results]

    def filter_view(rows, function=None):
        results = []

        for row in rows:
            r = function(row)
            try:
                r.next()
                results.append(True)
            except StopIteration:
                results.append(False)

        return [True, results]

    def _compile(func_str, error_id, f_name):
        globals_ = {}

        if func_str in ('_count', '_sum', '_stats'):
            # These are builtins which are not ment to be complited
            # by the python server
            return func_str

        try:
            exec func_str in {'log': _log}, globals_
        except Exception, e:
            log.error('runtime error in filter function: %s', e,
                      exc_info=True)
            raise CompileError({'error': {
                'id': error_id,
                'reason': e.args[0]}})
        err = {'error': {
            'id': error_id,
            'reason': ('string must eval to a function named %(f_name)s '
                       '(ex: "def %(f_name)s(doc, request): return True")' %
                       dict(f_name=f_name))}}
        if f_name not in globals_:
            raise CompileError(err)
        function = globals_.pop(f_name)
        if type(function) is not FunctionType:
            raise CompileError(err)
        # merge in remaining globals so that they are available in the function
        function.func_globals.update(globals_)
        return function


    handlers = {'reset': reset, 'add_fun': add_fun, 'map_doc': map_doc,
                'reduce': reduce, 'rereduce': rereduce, 'ddoc': ddoc,
                'filters': filter, 'views': filter_view}

    try:
        while True:
            line = input.readline()
            if not line:
                break
            try:
                cmd = json.decode(line)
                log.debug('Processing %r', cmd)
            except ValueError, e:
                log.error('Error: %s', e, exc_info=True)
                return 1
            else:
                retval = handlers[cmd[0]](*cmd[1:])
                log.debug('Returning  %r', retval)
                _writejson(retval)
    except KeyboardInterrupt:
        return 0
    except Exception, e:
        log.error('Error: %s', e, exc_info=True)
        return 1
55193
def run(self):
        """"""
        ret = eventlet.spawn(self.context(self.func))
        eventlet.sleep(self.seconds)
        try:
            ret.wait()
        except Exception:  # pylint: disable=broad-except
            traceback.print_exc()
        self.thread = eventlet.spawn(self.run)
943229
def _local_run(self, run_conf):
        '''
        
        '''
        try:
            ret = self._get_runner(run_conf).run()
        except SystemExit:
            ret = 'Runner is not available at this moment'
            self.out.error(ret)
        except Exception as ex:
            ret = 'Unhandled exception occurred: {}'.format(ex)
            log.debug(ex, exc_info=True)

        return ret
503242
def runner(queue, parallel):
    
    def run(fn_name, items):
        logger.info("clusterk: %s" % fn_name)
        assert "wrapper" in parallel, "Clusterk requires bcbio-nextgen-vm wrapper"
        fn = getattr(__import__("{base}.clusterktasks".format(base=parallel["module"]),
                                fromlist=["clusterktasks"]),
                     parallel["wrapper"])
        wrap_parallel = {k: v for k, v in parallel.items() if k in set(["fresources", "pack"])}
        out = []
        for data in [fn(fn_name, queue, parallel.get("wrapper_args"), wrap_parallel, x) for x in items]:
            if data:
                out.extend(data)
        return out
    return run
975563
def run(self, gates, n_qubits, *args, **kwargs):
        """"""
        return self._run(gates, n_qubits, args, kwargs)
134226
def run(endpoint, name=None):
    """"""
    try:
        if os.isatty(0):
            # output mode
            for data in stream_skypipe_output(endpoint, name):
                sys.stdout.write(data)
                sys.stdout.flush()

        else:
            # input mode
            with skypipe_input_stream(endpoint, name) as stream:
                for line in stream_stdin_lines():
                    stream.send(line)

    except KeyboardInterrupt:
        pass
1066694
def threaded(
    name: typing.Callable[..., typing.Any], daemon: bool = False, started: bool = False
) -> typing.Callable[..., threading.Thread]:
    """"""