Decorator function that instantiates the Retrying object
    @param *dargs: positional arguments passed to Retrying object
    @param **dkw: keyword arguments passed to the Retrying object
335008
def retry(*dargs, **dkw):
    
    # support both @retry and @retry() as valid syntax
    if len(dargs) == 1 and callable(dargs[0]):
        def wrap_simple(f):

            @six.wraps(f)
            def wrapped_f(*args, **kw):
                return Retrying().call(f, *args, **kw)

            return wrapped_f

        return wrap_simple(dargs[0])

    else:
        def wrap(f):

            @six.wraps(f)
            def wrapped_f(*args, **kw):
                return Retrying(*dargs, **dkw).call(f, *args, **kw)

            return wrapped_f

        return wrap
312332
function rimrafWithRetries(...args) {
    let retries = 0;
    return new Promise((resolve, reject) => {
        function rm(...rmArgs) {
            try {
                rimraf.sync(...rmArgs);
                resolve();
            } catch (e) {
                retries += 1;
                if (retries < 5) {
                    setTimeout(() => {
                        rm(...rmArgs);
                    }, 100);
                } else {
                    reject(e);
                }
            }
        }
        rm(...args);
    });
}
780431
def detect_and_decorate(decorator, args, kwargs):
    
    # special behavior when invoked with only one non-keyword argument: act as
    # a normal decorator, decorating and returning that argument with
    # click.option
    if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
        return decorator(args[0])

    # if we're not doing that, we should see no positional args
    # the alternative behavior is to fall through and discard *args, but this
    # will probably confuse someone in the future when their arguments are
    # silently discarded
    elif len(args) != 0:
        raise ValueError("this decorator cannot take positional args")

    # final case: got 0 or more kwargs, no positionals
    # do the function-which-returns-a-decorator dance to produce a
    # new decorator based on the arguments given
    else:

        def inner_decorator(f):
            return decorator(f, **kwargs)

        return inner_decorator
605625
def mk_kwargs(cls, kwargs):
        
        ret = {}
        kws = ['row_factory', 'body', 'parent']
        for k in kws:
            if k in kwargs:
                ret[k] = kwargs.pop(k)

        return ret
523362
def _dask_or_eager_func(name, eager_module=np, dask_module=dask_array,
                        list_of_args=False, array_args=slice(1),
                        requires_dask=None):
    """"""
    if dask_module is not None:
        def f(*args, **kwargs):
            if list_of_args:
                dispatch_args = args[0]
            else:
                dispatch_args = args[array_args]
            if any(isinstance(a, dask_array.Array) for a in dispatch_args):
                try:
                    wrapped = getattr(dask_module, name)
                except AttributeError as e:
                    raise AttributeError("%s: requires dask >=%s" %
                                         (e, requires_dask))
            else:
                wrapped = getattr(eager_module, name)
            return wrapped(*args, **kwargs)
    else:
        def f(*args, **kwargs):
            return getattr(eager_module, name)(*args, **kwargs)
    return f
1080793
def main(name, klass):
    

    # Common args parser.
    parser = create_args_parser(name)

    # Common args
    cargs = get_common_args(parser)
    logging.getLogger().setLevel(cargs['log_level'])
    wrapper = klass(certfile=cargs['certfile'], keyfile=cargs['keyfile'],
                    cafile=cargs['cafile'])

    if cargs['version']:
        print_version(wrapper)
        sys.exit()

    if cargs['foreground']:
        console = logging.StreamHandler()
        console.setFormatter(
            logging.Formatter(
                '%(asctime)s %(name)s: %(levelname)s: %(message)s'))
        logging.getLogger().addHandler(console)
    elif cargs['log_file']:
        logfile = logging.handlers.WatchedFileHandler(cargs['log_file'])
        logfile.setFormatter(
            logging.Formatter(
                '%(asctime)s %(name)s: %(levelname)s: %(message)s'))
        logging.getLogger().addHandler(logfile)
        go_to_background()
    else:
        syslog = logging.handlers.SysLogHandler('/dev/log')
        syslog.setFormatter(
            logging.Formatter('%(name)s: %(levelname)s: %(message)s'))
        logging.getLogger().addHandler(syslog)
        # Duplicate syslog's file descriptor to stout/stderr.
        syslog_fd = syslog.socket.fileno()
        os.dup2(syslog_fd, 1)
        os.dup2(syslog_fd, 2)
        go_to_background()

    if not wrapper.check():
        return 1
    return wrapper.run(cargs['address'], cargs['port'], cargs['unix_socket'])
945286
def retry(tries, CatchExceptions=(Exception,), delay=0.01, backoff=2):
    '''
    

    '''
    if backoff <= 1:
        raise ValueError("backoff must be greater than 1")

    if tries < 0:
        raise ValueError("tries must be 0 or greater")

    if delay <= 0:
        raise ValueError("delay must be greater than 0")

    def deco_retry(f):
        @wraps(f)
        def f_retry(*args, **kwargs):
            mdelay = delay
            retException = None
            for mtries in range(tries):
                try:
                    return f(*args, **kwargs)
                except CatchExceptions as ex:
                    logger.warning(
                        "function %s(%s, %s) try %d times error: %s\n" % (f.__name__, args, kwargs, mtries, str(ex)))
                    logger.warning("Retrying in %.4f seconds..." % (mdelay))

                    retException = ex
                    time.sleep(mdelay)
                    mdelay *= backoff
            raise retException

        return f_retry

    return deco_retry
1069749
def auto_retry(fun):
    """"""

    @functools.wraps(fun)
    def decorated(instance, *args, **kwargs):
        """Wrapper around a decorated function."""
        cfg = instance._retry_config
        remaining_tries = cfg.retry_attempts
        current_wait = cfg.retry_wait
        retry_backoff = cfg.retry_backoff
        last_error = None

        while remaining_tries >= 0:
            try:
                return fun(instance, *args, **kwargs)
            except socket.error as e:
                last_error = e
                instance._retry_logger.warning('Connection failed: %s', e)

            remaining_tries -= 1
            if remaining_tries == 0:
                # Last attempt
                break

            # Wait a bit
            time.sleep(current_wait)
            current_wait *= retry_backoff

        # All attempts failed, let's raise the last error.
        raise last_error

    return decorated
667538
def teb_retry(exc=RequestException,
              when=dict(response__status_code=429),
              delay='response__headers__Retry-After',
              max_collisions=MAX_COLLISIONS,
              default_retry=DEFAULT_RETRY):
    
    def wrap(f):
        @functools.wraps(f)
        def wrapped_f(*args, **kwargs):
            attempt = kwargs.pop('teb_retry_attempt', 0)
            try:
                return f(*args, **kwargs)
            except exc as e:
                if kwargsql.and_(e, **when):
                    try:
                        retry_after = kwargsql.get(e, delay)
                    except:
                        retry_after = default_retry
                    else:
                        if retry_after is not None:
                            retry_after = int(retry_after)
                        else:
                            retry_after = default_retry
                    countdown = retry_after + truncated_exponential_backoff(
                        retry_after, attempt % max_collisions)
                    raise Retry(kwargs=dict(attempt=attempt + 1),
                                countdown=countdown)
                else:
                    raise e, None, sys.exc_info()[2] # flake8: noqa.
        return wrapped_f
    return wrap
72310
<T> T callWithRetries(Callable<T> callable, RecurringPolicy<?> recurringPolicy,
      RecurringStats retryStats, Set<Class<? extends Exception>> retryableExceptions,
      boolean recoverable, boolean logFailures) throws Exception {
    boolean recovery = retryStats != null;

    while (true) {
      try {
        return callable.call();
      } catch (Exception e) {
        ShutdownSignalException sse = extractCause(e, ShutdownSignalException.class);
        if (sse == null && logFailures && recurringPolicy != null
            && recurringPolicy.allowsAttempts())
          log.error("Invocation of {} failed.", callable, e);

        if (sse != null && (recovery || !recoverable))
          throw e;

        if (!closed) {
          try {
            // Retry on channel recovery failure or retryable exception
            boolean retryable =
                recurringPolicy != null && recurringPolicy.allowsAttempts()
                    && isRetryable(retryableExceptions, e, sse);
            long startTime = System.nanoTime();

            if (retryable) {
              if (retryStats == null) 
                retryStats = new RecurringStats(recurringPolicy);
                
              // Wait for pending recovery
              if (sse != null) {
                if (recurringPolicy.getMaxDuration() == null)
                  circuit.await();
                else if (!circuit.await(retryStats.getMaxWaitTime())) {
                  log.debug("Exceeded max wait time while waiting for {} to recover", this);
                  throw e;
                }
              }

              // Continue retries
              retryStats.incrementAttempts();
              if (!retryStats.isPolicyExceeded()) {
                long remainingWaitTime =
                    retryStats.getWaitTime().toNanos() - (System.nanoTime() - startTime);
                if (remainingWaitTime > 0)
                  retryWaiter.await(Duration.nanos(remainingWaitTime));
                continue;
              }
            }
          } catch (Throwable ignore) {
          }
        }

        throw e;
      }
    }
  }
693212
def call_after(lag):
  
  def decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
      wrapper.timer.cancel() # Debounce
      wrapper.timer = threading.Timer(lag, func, args=args, kwargs=kwargs)
      wrapper.timer.start()
    wrapper.timer = threading.Timer(0, lambda: None) # timer.cancel now exists
    return wrapper
  return decorator
1211556
def register_dispatch_wrapper(wrapper):
    

    signature = inspect.getargspec(wrapper)
    if any([len(signature.args) != 1,
            signature.varargs is None,
            signature.keywords is None]):
        raise TypeError("Wrapper signature mismatch")

    def _wrapper(func, *args, **kwargs):
        """Exception handling"""
        try:
            return wrapper(func, *args, **kwargs)
        except Exception as e:
            # Kill subprocess
            _state["currentServer"].stop()
            traceback.print_exc()
            raise e

    _state["dispatchWrapper"] = _wrapper
62749
def wrap_rethink_errors(func_, *args, **kwargs):
    
    try:
        return func_(*args, **kwargs)
    except WRAP_RETHINK_ERRORS as reql_err:
        raise ValueError(str(reql_err))
547868
function kw(bundler) {
  assert.equal(typeof bundler, 'object')
  const handler = thenify(wreq(bundler))

  // Koa middleware.
  // @param {Function} next
  // @return {Promise}
  return function *watchifyRequest(next) {
    const ctx = this

    return yield handler(this.req, this.res)
      .then(success)
      .catch(failure)

    function success(res) {
      ctx.response.body = res
    }

    function failure(err) {
      ctx.throw(err)
    }
  }
}
563301
async def retry_create_artifact(*args, **kwargs):
    
    await retry_async(
        create_artifact,
        retry_exceptions=(
            ScriptWorkerRetryException,
            aiohttp.ClientError
        ),
        args=args,
        kwargs=kwargs
    )
100851
function WrapperError(message, innerError) {
  // supports instantiating the object without the new keyword
  if (!(this instanceof WrapperError)) {
    return new WrapperError(message, innerError);
  }

  Error.call(this);
  Error.captureStackTrace(this, WrapperError);

  this.message = message;
  this.innerError = innerError;
}
966800
def _multicall(hook_impls, caller_kwargs, firstresult=False):
    
    __tracebackhide__ = True
    results = []
    excinfo = None
    try:  # run impl and wrapper setup functions in a loop
        teardowns = []
        try:
            for hook_impl in reversed(hook_impls):
                try:
                    args = [caller_kwargs[argname] for argname in hook_impl.argnames]
                except KeyError:
                    for argname in hook_impl.argnames:
                        if argname not in caller_kwargs:
                            raise HookCallError(
                                "hook call must provide argument %r" % (argname,)
                            )

                if hook_impl.hookwrapper:
                    try:
                        gen = hook_impl.function(*args)
                        next(gen)  # first yield
                        teardowns.append(gen)
                    except StopIteration:
                        _raise_wrapfail(gen, "did not yield")
                else:
                    res = hook_impl.function(*args)
                    if res is not None:
                        results.append(res)
                        if firstresult:  # halt further impl calls
                            break
        except BaseException:
            excinfo = sys.exc_info()
    finally:
        if firstresult:  # first result hooks return a single value
            outcome = _Result(results[0] if results else None, excinfo)
        else:
            outcome = _Result(results, excinfo)

        # run all wrapper post-yield blocks
        for gen in reversed(teardowns):
            try:
                gen.send(outcome)
                _raise_wrapfail(gen, "has second yield")
            except StopIteration:
                pass

        return outcome.get_result()