function wrapper that limits the amount of time it has to run
    optional args:
        seconds - how long it has until the function times out
        default_output - what will be returned instead of an error
197583
def timeout(seconds=10, default_output='default_output'):
    
    def decorator(func):
        def _handle_timeout(signum, frame):
            """ throw the custom TimeoutError if called """
            raise TimeoutError(strerror(ETIME))

        def wrapper(*args, **kwargs):
            """ main wrapper for the error """
            # set up the propper error signal
            signal(SIGALRM, _handle_timeout)
            # set the time the function has to run
            alarm(seconds)
            try:
                result = func(*args, **kwargs)
            except TimeoutError:
                if default_output == 'default_output':
                    raise
                else:
                    result = default_output
            finally:
                # cancel the timer
                alarm(0)
            return result

        return wraps(func)(wrapper)
    return decorator
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
272243
def measure_time(func_to_measure):
    
    def wrap(*args, **kwargs):
        start_time = time()
        return_value = func_to_measure(*args, **kwargs)
        finish_time = time()
        log = "%s took %0.4f seconds. start_time = %0.4f - finish_time = %0.4f\n" % (func_to_measure.func_name,
                                                                                     finish_time - start_time,
                                                                                     start_time,
                                                                                     finish_time)
        print log
        return return_value
    return wrap
681951
def do_timeout(self, args):
        

        if not self.current:
            print('There are no resources in use. Use the command "open".')
            return

        args = args.strip()

        if not args:
            try:
                print('Timeout: {}ms'.format(self.current.timeout))
            except Exception as e:
                print(e)
        else:        
            args = args.split(' ')
            try:
                self.current.timeout = float(args[0])
                print('Done')
            except Exception as e:
                print(e)
1358791
def catch_timeout(f):
    
    def new_f(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except (requests.exceptions.ReadTimeout,
                requests.packages.urllib3.exceptions.ReadTimeoutError) as e:
            log.warning("caught read timeout: %s", e)
            self.connect()
            return f(self, *args, **kwargs)
    return new_f
1097444
def _days_to_seconds(cls, val, **kwargs):
        '''
        
        '''
        zero_value = kwargs.get('zero_value', 0)
        if val is not None:
            if val == 0:
                return zero_value
            return val * 86400
        else:
            return 'Not Defined'
398245
def timeit (func, log, limit):
    """"""

    def newfunc (*args, **kwargs):
        """Execute function and print execution time."""
        t = time.time()
        res = func(*args, **kwargs)
        duration = time.time() - t
        if duration > limit:
            print(func.__name__, "took %0.2f seconds" % duration, file=log)
            print(args, file=log)
            print(kwargs, file=log)
        return res
    return update_func_meta(newfunc, func)
33852
def wrap(self, func, delay=0):
        '''
        
        '''
        def wrapped():
            self.start()
            if delay:
                self.sleep(delay)
            x = None
            try:
                x = func()
            except OSError as oserror:
                log.debug('OSError exception:%s', oserror)
                self.oserror = oserror
                raise EasyProcessError(self, 'wrap error!')
            finally:
                self.stop()
            return x
        return wrapped
662339
def timeout(self, timeout):
        

        if timeout is None:
            self._timeout = None  # no timeout
            return
        self._timeout = float(timeout)
905204
def timed (log=sys.stderr, limit=2.0):
    """"""
    return lambda func: timeit(func, log, limit)
1238628
def timelimit(timeout):
    """"""
    def _1(function):
        def _2(*args, **kw):
            class Dispatch(threading.Thread):
                def __init__(self):
                    threading.Thread.__init__(self)
                    self.result = None
                    self.error = None

                    self.setDaemon(True)
                    self.start()

                def run(self):
                    try:
                        self.result = function(*args, **kw)
                    except:
                        self.error = sys.exc_info()

            c = Dispatch()
            c.join(timeout)
            if c.isAlive():
                raise TimeoutError, 'took too long'
            if c.error:
                raise c.error[0], c.error[1]
            return c.result
        return _2
    return _1
393594
def _timeout(self, timeout, handler, *args, **kw):
        
        t = spawn_thread(target=handler, args=args, kw=kw)
        t.daemon = True
        t.start()
        t.join(timeout)

        if not t.is_alive():
            if t.exc_info:
                return t.exc_info
            return t.result
        else:
            try:
                msg = '[%s] Execution was forcefully terminated'
                raise RuntimeError(msg % t.name)
            except:
                return sys.exc_info()
575714
def execution_time(object):
    

    @functools.wraps(object)
    def execution_time_wrapper(*args, **kwargs):
        """
        Implements execution timing.

        :param \*args: Arguments.
        :type \*args: \*
        :param \*\*kwargs: Keywords arguments.
        :type \*\*kwargs: \*\*
        :return: Object.
        :rtype: object
        """

        start_time = time.time()

        value = object(*args, **kwargs)

        end_time = time.time()

        sys.stdout.write("{0} | '{1}' object processed during '{2:f}' ms!\n".format(__name__,
                                                                                    object.__name__,
                                                                                    (end_time - start_time) * 1000.0))

        return value

    return execution_time_wrapper
371211
def log_time(func: Callable[..., Any]) -> Callable[..., Any]:
    

    def wrapper(*args, **kwargs):
        start_time = time.time()
        log.info("%s starting...", func.__name__.title())
        ret = func(*args, **kwargs)
        log.info(
            "%s finished (%s)",
            func.__name__.title(),
            datetime.timedelta(seconds=int(time.time() - start_time)),
        )
        return ret

    return wrapper
478056
def decorator(func):
        """"""

        def function_timer(*args, **kwargs):
            """A nested function for timing other functions."""
            # Capture start time
            start = time.time()

            # Execute function with arguments
            value = func(*args, **kwargs)

            # Capture end time
            end = time.time()

            # Calculate run time
            runtime = end - start
            if runtime < 60:
                runtime = str('sec: ' + str('{:f}'.format(runtime)))
            else:
                runtime = str('min: ' + str('{:f}'.format(runtime / 60)))
            print('{func:50} --> {time}'.format(func=func.__qualname__, time=runtime))
            return value

        return function_timer
1059368
function timeout(opt) {

  var options = opt || Object.create(null);
  var my = {
    milliseconds: Number(options.milliseconds) || 5000,
    header: Boolean(options.header),
  };
  if (typeof options.callback == 'function') {
    my.callback = options.callback;
    my.data = options.data;
    return wrapper(my, true);
  }
  return wrapper(my, false);
}
814792
def rate_limited(max_per_hour: int, *args: Any) -> Callable[..., Any]:
    """"""
    min_interval = 3600.0 / float(max_per_hour)

    def _decorate(func: Callable[..., Any]) -> Callable[..., Any]:
        things = [func.__name__]
        things.extend(args)
        key = "".join(things)
        LOG.debug(f"Rate limiter called for '{key}'.")
        if key not in LAST_CALLED:
            LOG.debug(f"Initializing entry for '{key}'.")
            LAST_CALLED[key] = 0.0

        def _rate_limited_function(*args: Any, **kargs: Any) -> Any:
            last_called = LAST_CALLED[key]
            now = time.time()
            elapsed = now - last_called
            remaining = min_interval - elapsed
            LOG.debug(f"Rate limiter last called for '{key}' at {last_called}.")
            LOG.debug(f"Remaining cooldown time for '{key}' is {remaining}.")

            if remaining > 0 and last_called > 0.0:
                LOG.info(f"Self-enforced rate limit hit, sleeping {remaining} seconds.")
                for i in tui.progress.bar(range(math.ceil(remaining))):
                    time.sleep(1)

            LAST_CALLED[key] = time.time()
            ret = func(*args, **kargs)
            LOG.debug(f"Updating rate limiter last called for '{key}' to {now}.")
            return ret

        return _rate_limited_function
    return _decorate