A decorator to invoke a function, retrying on assertion errors for a
    specified time interval.

    Adds a kwarg `timeout` to `func` which is a number of seconds to try
    for (default 15).
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
176132
def retry(tries, delay=0, back_off=1, raise_msg=''):
    

    if back_off < 1:
        raise ValueError('back_off must be 1 or greater')

    tries = math.floor(tries)
    if tries < 0:
        raise ValueError('tries must be 0 or greater')

    if delay < 0:
        raise ValueError('delay must be 0 or greater')

    def deco_retry(f):
        def f_retry(*args, **kwargs):
            max_tries, max_delay = tries, delay  # make mutable

            while max_tries > 0:
                rv = f(*args, **kwargs)  # first attempt
                if rv:  # Done on success
                    return rv

                max_tries -= 1  # consume an attempt
                time.sleep(max_delay)  # wait...
                max_delay *= back_off  # make future wait longer
            else:
                if raise_msg:
                    raise Exception(raise_msg)
                return

        return f_retry  # true decorator -> decorated function

    return deco_retry
1197784
def _timed_run(self, func, distribution, args=(), kwargs={},  default=None):
        
        class InterruptableThread(threading.Thread):
            def __init__(self):
                threading.Thread.__init__(self)
                self.result = default
                self.exc_info = (None, None, None)

            def run(self):
                try:
                    self.result = func(args, **kwargs)
                except Exception as err:
                    self.exc_info = sys.exc_info()

            def suicide(self):
                raise RuntimeError('Stop has been called')

        it = InterruptableThread()
        it.start()
        started_at = datetime.now()
        it.join(self.timeout)
        ended_at = datetime.now()
        diff = ended_at - started_at

        if it.exc_info[0] is not None:  # if there were any exceptions
            a,b,c = it.exc_info
            raise Exception(a,b,c)  # communicate that to caller

        if it.isAlive():
            it.suicide()
            raise RuntimeError
        else:
            return it.result
612893
def retry(retry_count):
    

    def func(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            for backoff in range(retry_count):
                try:
                    return f(*args, **kwargs)
                except Exception:
                    time.sleep(2 ** backoff)
            else:
                raise SbgError('{}: failed to complete: {}'.format(
                    threading.current_thread().getName(), f.__name__)
                )

        return wrapper

    return func
1323087
def _reset_on_error(self, server, func, *args, **kwargs):
        
        try:
            return func(*args, **kwargs)
        except NetworkTimeout:
            # The socket has been closed. Don't reset the server.
            raise
        except ConnectionFailure:
            self.__reset_server(server.description.address)
            raise
696319
def retry(self, f, *args, **kwargs):
        
        backoff = random.random() / 100  # 5ms on average
        for _ in range(self.tries - 1):
            try:
                return f(*args, **kwargs)
            except NetworkError:
                time.sleep(backoff)
                backoff *= 2
        return f(*args, **kwargs)
86791
def integrity(integrity_func, retry_errors=(ResponseNotValid,)):
    
    def build_decorator(func):
        @functools.wraps(func)
        def func_wrapper(self, grab, task):
            if isinstance(integrity_func, (list, tuple)):
                int_funcs = integrity_func
            else:
                int_funcs = [integrity_func]
            try:
                for int_func in int_funcs:
                    if isinstance(int_func, str):
                        getattr(self, int_func)(grab)
                    else:
                        int_func(grab)
            except retry_errors as ex:
                yield task.clone(refresh_cache=True)
                error_code = ex.__class__.__name__.replace('_', '-')
                self.stat.inc('integrity:%s' % error_code)
            else:
                result = func(self, grab, task)
                if result is not None:
                    for event in result:
                        yield event
        func_wrapper._original_func = func # pylint: disable=protected-access
        return func_wrapper
    return build_decorator
1233202
def try_catch(func, *args, **kwargs):
    '''
    
    '''
    try:
        return log_debug(func, *args, **kwargs)
    except Exception as exc:
        logging.debug('Error in "%s" in thread %s: %s', func.__name__, current_thread(), exc)
        return exc
22951
function timer(ms, func) {
  var ref;
  if (ms) {
    ref = setTimeout(func, ms);
  } else {
    ref = setImmediate(func);
  }
  return function abortTimer() {
    if (ms) {
      clearTimeout(ref);
    } else {
      clearImmediate(ref);
    }
  };
}
1077577
def timeout(seconds, err_msg="xtls: function run too long."):
    

    def decorator(function):
        def _on_timeout(signum, frame):
            raise TimeoutError(err_msg)

        @wraps(function)
        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _on_timeout)
            signal.alarm(seconds)
            try:
                result = function(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wrapper

    return decorator
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))
983688
function startTimeout(func, time, self) {
  return {
    timer: setTimeout(func.bind(self), time),
    stopped: false
  };
}
905326
def retry_timeout(api, retries=3):
    """"""
    @wraps(api)
    def retry_api(*args, **kwargs):
        """Retrying API."""
        for i in range(1, retries + 1):
            try:
                return api(*args, **kwargs)
            except RequestTimeout:
                if i == retries:
                    raise

    return retry_api
283846
def timeout(func):
    """"""

    @wraps(func)
    def _timeout(*args, **kwargs):
        now = time()
        deadline = kwargs.pop("deadline", None)
        seconds = kwargs.pop("timeout", None)

        if deadline is None and seconds is not None:
            deadline = now + seconds

        if deadline is not None and deadline < now:
            raise TimeExceeded("TxMongo: run time exceeded by {0}s.".format(now-deadline))

        kwargs['_deadline'] = deadline
        raw_d = func(*args, **kwargs)

        if deadline is None:
            return raw_d

        if seconds is None and deadline is not None and deadline - now > 0:
            seconds = deadline - now

        timeout_d = defer.Deferred()
        times_up = reactor.callLater(seconds, timeout_d.callback, None)

        def on_ok(result):
            if timeout_d.called:
                raw_d.cancel()
                raise TimeExceeded("TxMongo: run time of {0}s exceeded.".format(seconds))
            else:
                times_up.cancel()
                return result[0]

        def on_fail(failure):
            failure.trap(defer.FirstError)
            assert failure.value.index == 0
            times_up.cancel()
            failure.value.subFailure.raiseException()


        return defer.DeferredList([raw_d, timeout_d], fireOnOneCallback=True,
                                  fireOnOneErrback=True, consumeErrors=True).addCallbacks(on_ok, on_fail)

    return _timeout
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)
939068
def sleep_and_retry(func):
    '''
    
    '''
    @wraps(func)
    def wrapper(*args, **kargs):
        '''
        Call the rate limited function. If the function raises a rate limit
        exception sleep for the remaing time period and retry the function.

        :param args: non-keyword variable length argument list to the decorated function.
        :param kargs: keyworded variable length argument list to the decorated function.
        '''
        while True:
            try:
                return func(*args, **kargs)
            except RateLimitException as exception:
                time.sleep(exception.period_remaining)
    return wrapper
918841
def RetryOnUnavailable(func):
  """"""

  @functools.wraps(func)
  def Wrapper(*args, **kwargs):
    while True:
      try:
        response = func(*args, **kwargs)
      except (httpclient.HTTPException, socket.error, urlerror.URLError) as e:
        time.sleep(5)
        if (isinstance(e, urlerror.HTTPError)
            and e.getcode() == httpclient.SERVICE_UNAVAILABLE):
          continue
        elif isinstance(e, socket.timeout):
          continue
        raise
      else:
        if response.getcode() == httpclient.OK:
          return response
        else:
          raise StatusException(response)
  return Wrapper