Calls :code:`func` with given arguments and handle rate limit exceptions.

    :param func: Function to call
    :param args: Argument list for :code:`func`
    :param kwargs: Dict arguments for `func`
    :returns: :code:`func` result
503057
def handle_rate_limit(func: Callable[[Any], Any], *args, **kwargs) -> Any:
    
    error_count = 0
    while True:
        try:
            return func(*args, **kwargs)
        except Exception as e:
            if error_count > 3:
                util_logger.error('Retried to call <{}> 3 times without success. '
                                  'Continuing without calling it.'.format(func.__name__))
                break

            if 'DELETED_COMMENT' in str(e):
                util_logger.warning('The comment has been deleted. '
                                    'Function <{}> was not executed.'.format(func.__name__))
                break
            wait = parse_wait_time(str(e))
            util_logger.error(e)
            util_logger.warning('Waiting ~{} minutes'.format(round(float(wait + 30) / 60)))
            time.sleep(wait + 30)
            error_count += 1
1356865
def callable_check(func, arg_count=1, arg_value=None, allow_none=False):
        """"""
        if func is None:
            if not allow_none:
                raise ValueError('callable cannot be None')
        elif not arg_checker(func, *[arg_value for _ in range(arg_count)]):
            raise ValueError('callable %s invalid (for %d arguments)' % (func, arg_count))
1205699
def decorate(self, func, limit=0, ttl=0, *anoop, **kwnoop):
        """"""
        self.limit = int(limit)
        self.ttl = int(ttl)
        return super(RateLimitDecorator, self).decorate(func, target=None, *anoop, **kwnoop)
548880
def argument(*args, **kwargs):
    

    def decorator(func):
        adaptor = ScriptAdaptor._get_adaptor(func)
        group = kwargs.pop('group', None)
        adaptor._add_argument(args, kwargs, group=group)
        return func
    return decorator
930004
def restrict_args(func, *args, **kwargs):
    '''
    
    '''
    callargs = getargspec(func)
    if not callargs.varargs:
        args = args[0:len(callargs.args)]
    return func(*args, **kwargs)
561012
def build_call(func, *args, **kwargs):
    

    func = get_wrapped_func(func)
    named, vargs, _, defs, kwonly, kwonlydefs, _ = getfullargspec(func)

    nonce = object()
    actual = dict((name, nonce) for name in named)

    defs = defs or ()
    kwonlydefs = kwonlydefs or {}

    actual.update(kwonlydefs)
    actual.update(dict(zip(reversed(named), reversed(defs))))
    actual.update(dict(zip(named, args)))

    if vargs:
        actual[vargs] = tuple(args[len(named):])

    actual.update(kwargs)

    for name, value in actual.items():
        if value is nonce:
            raise TypeError("%s missing required positional argument: '%s'" % (func.__name__, name))

    return tuple_of_dict(actual)
525832
def _add_request_parameters(func):
        """"""

        # The function the decorator returns
        async def decorated_func(*args, handle_ratelimit=None, max_tries=None, request_timeout=None, **kwargs):
            return await func(*args, handle_ratelimit=handle_ratelimit, max_tries=max_tries,
                              request_timeout=request_timeout, **kwargs)

        # We return the decorated func
        return decorated_func
1006155
def wrap_exception(func: Callable) -> Callable:
    """"""
    try:
        # only do the wrapping if bluepy is installed.
        # otherwise it's pointless anyway
        from bluepy.btle import BTLEException
    except ImportError:
        return func

    def _func_wrapper(*args, **kwargs):
        error_count = 0
        last_error = None
        while error_count < RETRY_LIMIT:
            try:
                return func(*args, **kwargs)
            except BTLEException as exception:
                error_count += 1
                last_error = exception
                time.sleep(RETRY_DELAY)
                _LOGGER.debug('Call to %s failed, try %d of %d', func, error_count, RETRY_LIMIT)
        raise BluetoothBackendException() from last_error

    return _func_wrapper
1212181
def _wrapper(self, q, start):
        
        try:
            func_name = self.fnc.__name__
        except AttributeError:
            func_name = str(self.fnc)
        logger.debug("Running \"%s\" with parameters: \"%s\":\t%s/%s"
                     % (func_name, str(self.kwargs), round(time.time() - start), self.timeout))
        try:
            result = self.fnc(**self.kwargs)
            # let's log only first 50 characters of the response
            logger.debug("callback result = %s", str(result)[:50])
            q.put(result)
        except self.expected_exceptions as ex:
            logger.debug("expected exception was caught: %s", ex)
            q.put(False)
        except Exception as ex:
            logger.debug("adding exception %s to queue", ex)
            q.put(ex)
647521
function throttle(func, limit) {
        if (typeof func !== 'function') {
            throw new Error('function argument is expected');
        } else if (typeof limit !== 'number') {
            throw new Error('number argument is expected');
        }

        var listener = new ThrottleListener(limit);

        return function () {
            return listener.execute(func, this, arguments);
        };
    }
145259
def offset_limit(func):
    

    def func_wrapper(self, start, stop):
        offset = start
        limit = stop - start
        return func(self, offset, limit)

    return func_wrapper
1206139
def _argspec(func):
    
    assert isinstance(func, collections.Callable), 'Argument must be a callable'

    try: sp =  inspect.getargspec(func) if six.PY2 else inspect.getfullargspec(func)
    except TypeError:
        # inspect.getargspec() fails for built-in functions
        return []

    # Collect arguments with defaults
    ret = []
    defaults_start = len(sp.args) - len(sp.defaults) if sp.defaults else len(sp.args)
    for i, name in enumerate(sp.args):
        arg = data.ArgumentSpec(name)
        if i >= defaults_start:
            arg['default'] = sp.defaults[i - defaults_start]
        ret.append(arg)

    # *args, **kwargs
    if sp.varargs:
        ret.append(data.ArgumentSpec(sp.varargs, varargs=True))
    if six.PY2:
        if sp.keywords:
            ret.append(data.ArgumentSpec(sp.keywords, keywords=True))
    else:
        if sp.varkw:
            ret.append(data.ArgumentSpec(sp.varkw, keywords=True))

    # TODO: support Python 3: kwonlyargs, kwonlydefaults, annotations

    # Finish
    return ret
124479
def call_func(self, fun, **kwargs):
        '''
        
        '''
        return self.low(fun, kwargs, print_event=kwargs.get('print_event', True), full_return=kwargs.get('full_return', False))
530053
def error_map(func):
    
    @six.wraps(func)
    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except exceptions.RequestException as err:
            raise TVDBRequestException(
                err,
                response=getattr(err, 'response', None),
                request=getattr(err, 'request', None))
    return wrapper
291312
def apply(self, func, axis, *args, **kwargs):
        
        if callable(func):
            return self._callable_func(func, axis, *args, **kwargs)
        elif isinstance(func, dict):
            return self._dict_func(func, axis, *args, **kwargs)
        elif is_list_like(func):
            return self._list_like_func(func, axis, *args, **kwargs)
        else:
            pass
149496
def communicator(func):
    ''''''
    def _call(queue, args, kwargs):
        '''called with [queue, args, kwargs] as first optional arg'''
        kwargs['queue'] = queue
        ret = None
        try:
            ret = func(*args, **kwargs)
            queue.put('END')
        except KeyboardInterrupt as ex:
            trace = traceback.format_exc()
            queue.put('KEYBOARDINT')
            queue.put('Keyboard interrupt')
            queue.put('{0}\n{1}\n'.format(ex, trace))
        except Exception as ex:
            trace = traceback.format_exc()
            queue.put('ERROR')
            queue.put('Exception')
            queue.put('{0}\n{1}\n'.format(ex, trace))
        except SystemExit as ex:
            trace = traceback.format_exc()
            queue.put('ERROR')
            queue.put('System exit')
            queue.put('{0}\n{1}\n'.format(ex, trace))
        return ret
    return _call
936803
def overload(func):
    
    if sys.version_info < (3, 3):
        raise OverloadingError("The 'overload' syntax requires Python version 3.3 or higher.")
    fn = unwrap(func)
    ensure_function(fn)
    fname = get_full_name(fn)
    if fname.find('<locals>') >= 0:
        raise OverloadingError("The 'overload' syntax cannot be used with nested functions. "
                               "Decorators must use functools.wraps().")
    try:
        return register(__registry[fname], func)
    except KeyError:
        __registry[fname] = overloaded(func)
        return __registry[fname]