/*
RateLimiter - an object that encapsulates the logic for counting items sent to Rollbar

@param options - the same options that are accepted by configureGlobal offered as a convenience
546446
function RateLimiter(options) {
  this.startTime = _.now();
  this.counter = 0;
  this.perMinCounter = 0;
  this.platform = null;
  this.platformOptions = {};
  this.configureGlobal(options);
}
107005
public static RateLimiterExports ofIterable(String prefix, Iterable<RateLimiter> rateLimiters) {
        return new RateLimiterExports(prefix, rateLimiters);
    }
262869
@Override
  public DurationFormatterFactory setFallbackLimit(long fallbackLimit) {
    if (fallbackLimit < 0) {
      fallbackLimit = 0;
    }
    if (fallbackLimit != this.fallbackLimit) {
      this.fallbackLimit = fallbackLimit;
      reset();
    }
    return this;
  }
520896
@Override
    public Function<Service<HttpRequest, HttpResponse>,
            ? extends Service<HttpRequest, HttpResponse>> newDecorator(RateLimitingDecorator parameter) {
        return ThrottlingHttpService.newDecorator(new RateLimitingThrottlingStrategy<>(
                parameter.value(), DefaultValues.isSpecified(parameter.name()) ? parameter.name() : null));
    }
128323
def _rate_limit(self):
        """"""
        self.limits_set = True
        for product in self.account_information():
            self.limits[product['id']] = {'interval': timedelta(seconds=60 / float(product['per_minute_limit']))}
1070082
def rates(ctx, opts):
    """"""
    click.echo("Retrieving rate limits ... ", nl=False)

    context_msg = "Failed to retrieve status!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            resources_limits = get_rate_limits()

    click.secho("OK", fg="green")

    headers = ["Resource", "Throttled", "Remaining", "Interval (Seconds)", "Reset"]

    rows = []
    for resource, limits in six.iteritems(resources_limits):
        rows.append(
            [
                click.style(resource, fg="cyan"),
                click.style(
                    "Yes" if limits.throttled else "No",
                    fg="red" if limits.throttled else "green",
                ),
                "%(remaining)s/%(limit)s"
                % {
                    "remaining": click.style(
                        six.text_type(limits.remaining), fg="yellow"
                    ),
                    "limit": click.style(six.text_type(limits.limit), fg="yellow"),
                },
                click.style(six.text_type(limits.interval), fg="blue"),
                click.style(six.text_type(limits.reset), fg="magenta"),
            ]
        )

    if resources_limits:
        click.echo()
        utils.pretty_print_table(headers, rows)

    click.echo()

    num_results = len(resources_limits)
    list_suffix = "resource%s" % ("s" if num_results != 1 else "")
    utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix)
346034
protected <T extends HttpResponseAware> T updateRateLimit(Supplier<T> httpResponseAwareSupplier) {
    if (rateLimitReset != null) {
      long waitMillis = rateLimitReset * 1000 - System.currentTimeMillis();
      if (rateLimitRemaining <= 0 && waitMillis >= 0) {
        throw new ExchangeException(
            "The request is not executed due to rate limit, please wait for "
                + (waitMillis / 1000)
                + " seconds, limit:"
                + rateLimit
                + ", reset: "
                + new Date(rateLimitReset * 1000));
      } else {
        rateLimitRemaining--;
      }
    }
    HttpResponseAware responseAware = null;
    boolean rateLimitsUpdated = false;
    try {
      T result = httpResponseAwareSupplier.get();
      responseAware = result;
      return result;
    } catch (BitmexException e) {
      if (e.getHttpStatusCode() == 429) {
        // we are warned !
        try {
          Integer retryAfter = Integer.valueOf(e.getResponseHeaders().get("Retry-After").get(0));
          rateLimitRemaining = 0;
          rateLimitReset = System.currentTimeMillis() / 1000 + retryAfter;
          rateLimitsUpdated = true;
        } catch (Throwable ignored) {
        }
      } else if (e.getHttpStatusCode() == 403) {
        // we are banned now !
        rateLimitRemaining = 0;
        rateLimitReset = System.currentTimeMillis() / 1000 + 5; // lets be quiet for 5 sec
      }
      responseAware = e;
      throw handleError(e);
    } catch (Exception e) {
      throw handleError(e);
    } finally {
      if (responseAware != null && !rateLimitsUpdated) {
        Map<String, List<String>> responseHeaders = responseAware.getResponseHeaders();
        rateLimit = Integer.valueOf(responseHeaders.get("X-RateLimit-Limit").get(0));
        rateLimitRemaining = Integer.valueOf(responseHeaders.get("X-RateLimit-Remaining").get(0));
        rateLimitReset = Long.valueOf(responseHeaders.get("X-RateLimit-Reset").get(0));
        rateLimitsUpdated = true;
      }
      if (rateLimitsUpdated) {
        RateLimitUpdateListener rateLimitUpdateListener = exchange.getRateLimitUpdateListener();
        if (rateLimitUpdateListener != null) {
          rateLimitUpdateListener.rateLimitUpdate(rateLimit, rateLimitRemaining, rateLimitReset);
        }
      }
    }
  }
1297718
public void setLimit(int limit) {
        FailureInterpreter fi = getFailureInterpreter();
        if (!(fi instanceof DefaultFailureInterpreter)) {
            throw new IllegalStateException("setLimit() not supported: this CircuitBreaker's FailureInterpreter isn't a DefaultFailureInterpreter.");
        }
        ((DefaultFailureInterpreter)fi).setLimit(limit);
    }
1001232
func (o *Enterprise) CreateRateLimiter(child *RateLimiter) *bambou.Error {

	return bambou.CurrentSession().CreateChild(o, child)
}
1323396
public static RateLimiterExports ofRateLimiter(String prefix, RateLimiter rateLimiter) {
        return new RateLimiterExports(prefix, Array.of(rateLimiter));
    }
884490
function execute(?\CharlotteDunois\Yasmin\Interfaces\RatelimitBucketInterface $ratelimit = null) {
        $request = $this->request();
        
        return \CharlotteDunois\Yasmin\Utils\URLHelpers::makeRequest($request, $request->requestOptions)->then(function ($response) use ($ratelimit) {
            if(!$response) {
                return -1;
            }
            
            $status = $response->getStatusCode();
            $this->api->client->emit('debug', 'Got response for item "'.$this->endpoint.'" with HTTP status code '.$status);
            
            $this->api->handleRatelimit($response, $ratelimit, $this->isReactionEndpoint());
            
            if($status === 204) {
                return 0;
            }
            
            $body = self::decodeBody($response);
            
            if($status >= 400) {
                $error = $this->handleAPIError($response, $body, $ratelimit);
                if($error === null) {
                    return -1;
                }
                
                throw $error;
            }
            
            return $body;
        });
    }
1371266
def set_rate(rate):
    
    if not (isinstance(rate, int) or isinstance(rate, float)):
        raise TypeError("argument to set_rate is expected to be int or float")
    global loop_duration
    loop_duration = 1.0/rate
581900
function normalizeLimit (options) {
  const limit = options.limit || options.resultRecordCount || options.count || options.maxFeatures
  // If there is a limit, add 1 to it so we can later calculate a limitExceeded. The result set will be resized accordingly, post SQL
  if (limit) return limit + 1
}
1340995
public static RateLimiterMetrics ofIterable(String prefix, Iterable<RateLimiter> rateLimiters) {
        return new RateLimiterMetrics(prefix, rateLimiters);
    }
933256
private void checkLimitRange(int limit) {
    int minLimit = offsetPaginationConfiguration.allowZeroLimit() ? 0 : 1;

    if (limit < minLimit || limit > offsetPaginationConfiguration.maxLimit()) {
      throw InvalidParameterException.create(
          "Invalid value for '" + this.getParameterFieldName() + "': " + limit
              + "  - value between " + minLimit + " and " + offsetPaginationConfiguration.maxLimit()
              + " is required.");
    }
  }
579319
private String formatRate(Rate value)
   {
      String result = null;
      if (value != null)
      {
         StringBuilder buffer = new StringBuilder(m_formats.getCurrencyFormat().format(value.getAmount()));
         buffer.append("/");
         buffer.append(formatTimeUnit(value.getUnits()));
         result = buffer.toString();
      }
      return (result);
   }
953884
func RateLimitedReader(r io.Reader, size int, duration time.Duration) io.ReadCloser {
	rl := &rateLimiter{
		action: func(p []byte) (int, error) {
			return r.Read(p)
		},
		limit:     size,
		remaining: size,
		stop:      make(chan bool),
		worker:    make(chan *operation),
	}
	go rl.run(duration)
	return rl
}