Calls the callback_func, passing in the two positional arguments,
        conditionally waiting if the callback function hasn't been set yet.
        Meant to be run in a threadpool owned by the FutureCollection.

        Returns:
            None
552055
def run_callback(self):
        

        if self._callback_func is not None:
            try:
                self._callback_func(self._request, self._result)
            except Exception:  # pylint: disable=broad-except
                LOGGER.exception('An unhandled error occurred while running '
                                 'future callback')
986651
def add_done_callback(self, fn):
        
        if self.done():
            return fn(self)
        self._callbacks.append(fn)
51303
def maybe_call_closing_deferred(self):
        

        if self._closing_deferred:
            self._closing_deferred.callback(self)
            self._closing_deferred = None
961532
def _call_watcher(self_, watcher, event):
        
        if self_.self_or_cls.param._TRIGGER:
            pass
        elif watcher.onlychanged and (not self_._changed(event)):
            return

        if self_.self_or_cls.param._BATCH_WATCH:
            self_._events.append(event)
            if watcher not in self_._watchers:
                self_._watchers.append(watcher)
        elif watcher.mode == 'args':
            with batch_watch(self_.self_or_cls, run=False):
                watcher.fn(self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER))
        else:
            with batch_watch(self_.self_or_cls, run=False):
                event = self_._update_event_type(watcher, event, self_.self_or_cls.param._TRIGGER)
                watcher.fn(**{event.name: event.new})
1148785
def useThis(self, *args, **kwargs):
        
        self._callback = functools.partial(self._callback, *args, **kwargs)
1076284
def schedule(self, function, args=(), kwargs={}):
        
        self._check_pool_state()

        future = Future()
        payload = TaskPayload(function, args, kwargs)
        task = Task(next(self._task_counter), future, None, payload)

        self._context.task_queue.put(task)

        return future
291465
def call(func, args):
    
    assert hasattr(func, '__call__'), 'Cannot call func: {}'.format(
        func.__name__)
    raw_func = (
        func if isinstance(func, FunctionType) else func.__class__.__call__)
    hints = collections.defaultdict(lambda: Any, get_type_hints(raw_func))
    argspec = _getargspec(raw_func)
    named_args = {}
    varargs = ()
    for k, nk, v in _normalize(args):
        if nk == argspec.varargs:
            hints[nk] = Tuple[hints[nk], ...]
        elif nk not in argspec.args and argspec.varkw in hints:
            hints[nk] = hints[argspec.varkw]
        try:
            value = cast(hints[nk], v)
        except TypeError as e:
            _LOGGER.exception(e)
            six.raise_from(exc.InvalidCliValueError(k, v), e)
        if nk == argspec.varargs:
            varargs = value
        elif (nk in argspec.args or argspec.varkw) and (
                nk not in named_args or named_args[nk] is None):
            named_args[nk] = value
    return func(*varargs, **named_args)
695437
def wrap_async(func):
    """"""
    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        fut = asyncio.ensure_future(func(*args, **kwargs))
        cur = greenlet.getcurrent()
        def callback(fut):
            try:
                cur.switch(fut.result())
            except BaseException as e:
                cur.throw(e)
        fut.add_done_callback(callback)
        return cur.parent.switch()
    return wrapped
1328214
public <T> Future<T> submit(Callable<T> callable) {
		checkThreadQueue();
		return threadPool.submit(callable);
	}
960052
def wait_for(func):
    

    @wraps(func)
    def wrapped(*args, **kwargs):
        timeout = kwargs.pop('timeout', TIMEOUT)

        start = None

        while True:
            try:
                return func(*args, **kwargs)
            except AssertionError:
                # The function took some time to test the assertion, however,
                # the result might correspond to the state of the world at any
                # point in time, perhaps earlier than the timeout. Therefore,
                # start counting time from the first assertion fail, not from
                # before the function was called.
                if not start:
                    start = time()
                if time() - start < timeout:
                    sleep(CHECK_EVERY)
                    continue
                else:
                    raise

    return wrapped
770129
def run_on_new_thread(func, daemon=True):
    
    f = concurrent.futures.Future()
    def wrapper():
        if not f.set_running_or_notify_cancel():
            return
        try:
            f.set_result(func())
        except Exception as e:
            f.set_exception(e)
    t = threading.Thread(target=wrapper)
    t.daemon = daemon
    t.start()
    return f
1137628
def run_func_until_ret_arg(fun, kwargs, fun_call=None,
                           argument_being_watched=None, required_argument_response=None):
    '''
    
    '''
    status = None
    while status != required_argument_response:
        f_result = fun(kwargs, call=fun_call)
        r_set = {}
        for d in f_result:
            if isinstance(d, list):
                d0 = d[0]
                if isinstance(d0, dict):
                    for k, v in six.iteritems(d0):
                        r_set[k] = v
        status = _unwrap_dict(r_set, argument_being_watched)
        log.debug(
            'Function: %s, Watched arg: %s, Response: %s',
            six.text_type(fun).split(' ')[1], argument_being_watched, status
        )
        time.sleep(5)

    return True
19607
def threadpooled(
    func: typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]],
    *,
    loop_getter: typing.Union[typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop],
    loop_getter_need_context: bool = False,
) -> typing.Callable[..., "asyncio.Task[typing.Any]"]:
    """"""
1064390
def submit(self, func, *args, **kwargs):
        
        with self._shutdown_lock:
            if self._shutdown:
                raise RuntimeError(
                    'cannot schedule new futures after shutdown')
            if self.in_green_worker:
                return wait(func(*args, **kwargs))
            else:
                future = create_future(self._loop)
                self._put((future, func, args, kwargs))
                return future
1074316
def connect(cls, *args, **kwargs):
        
        loop = kwargs.get('loop')
        if loop is None:
            loop = trollius.get_event_loop()
        future = trollius.Future(loop=loop)

        def callback(arg):
            if not future.done():
                if isinstance(arg, Exception):
                    loop.call_soon_threadsafe(future.set_exception, arg)
                else:
                    loop.call_soon_threadsafe(future.set_result, arg)

        stream = cls(callback, *args, **kwargs)
        yield From(future)
        raise Return(stream)
1217593
def bind(self, __fun, *args, **kwargs):
    

    with self._lock:
      if self._running or self._completed or self._cancelled:
        raise RuntimeError('Future object can not be reused')
      if self._worker:
        raise RuntimeError('Future object is already bound')
      self._worker = functools.partial(__fun, *args, **kwargs)
    return self
1141676
def wait(self, timeout: Union[float, datetime.timedelta] = None) -> Awaitable[None]:
        
        fut = Future()  # type: Future[None]
        if self._value:
            fut.set_result(None)
            return fut
        self._waiters.add(fut)
        fut.add_done_callback(lambda fut: self._waiters.remove(fut))
        if timeout is None:
            return fut
        else:
            timeout_fut = gen.with_timeout(
                timeout, fut, quiet_exceptions=(CancelledError,)
            )
            # This is a slightly clumsy workaround for the fact that
            # gen.with_timeout doesn't cancel its futures. Cancelling
            # fut will remove it from the waiters list.
            timeout_fut.add_done_callback(
                lambda tf: fut.cancel() if not fut.done() else None
            )
            return timeout_fut