Verifying the API limits
774515
def _rate_limit_status(self, api=None, mode=None):
        
        if api == None:
            api = self.connectToAPI()

        if mode == None:
            print json.dumps(api.rate_limit_status(), indent=2)
            raw_input("<Press ENTER>")
        else:
            # Testing if we have enough queries
            while True:
                allLimits = api.rate_limit_status()
                if mode == "get_user":
                    limit = allLimits["resources"]["users"]["/users/show/:id"]["limit"]
                    remaining = allLimits["resources"]["users"]["/users/show/:id"]["remaining"]
                    reset = allLimits["resources"]["users"]["/users/show/:id"]["reset"]
                elif mode == "get_followers":
                    limit = allLimits["resources"]["followers"]["/followers/ids"]["limit"]
                    remaining = allLimits["resources"]["followers"]["/followers/ids"]["remaining"]
                    reset = allLimits["resources"]["followers"]["/followers/ids"]["reset"]
                elif mode == "get_friends":
                    limit = allLimits["resources"]["friends"]["/friends/ids"]["limit"]
                    remaining = allLimits["resources"]["friends"]["/friends/ids"]["remaining"]
                    reset = allLimits["resources"]["friends"]["/friends/ids"]["reset"]
                elif mode == "search_users":
                    limit = allLimits["resources"]["users"]["/users/search"]["limit"]
                    remaining = allLimits["resources"]["users"]["/users/search"]["remaining"]
                    reset = allLimits["resources"]["users"]["/users/search"]["reset"]
                else:
                    remaining = 1
                """elif mode == "get_all_docs":
                    limit = allLimits["resources"]REPLACEME["limit"]
                    remaining = allLimits["resources"]REPLACEME["remaining"]
                    reset = allLimits["resources"]REPLACEME["reset"]elif mode == "get_users":
                    limit = allLimits["resources"]REPLACEME["limit"]
                    remaining = allLimits["resources"]REPLACEME["remaining"]
                    reset = allLimits["resources"]REPLACEME["reset"] else:
                    remaining = 1"""
                # Checking if we have enough remaining queries
                if remaining > 0:
                    #raw_input(str(remaining) + " queries yet...")
                    break
                else:
                    waitTime = 60
                    print "No more queries remaining, sleeping for " + str(waitTime) +" seconds..."
                    time.sleep(waitTime)

        return 0
82888
def _update_limits_from_api(self):
        
        logger.debug('Setting DirectoryService limits from API')
        self.connect()
        resp = self.conn.get_directory_limits()
        directory_limits = resp['DirectoryLimits']
        self.limits['CloudOnlyDirectories']._set_api_limit(
            directory_limits['CloudOnlyDirectoriesLimit']
        )
        self.limits['CloudOnlyMicrosoftAD']._set_api_limit(
            directory_limits['CloudOnlyMicrosoftADLimit']
        )
        self.limits['ConnectedDirectories']._set_api_limit(
            directory_limits['ConnectedDirectoriesLimit']
        )
751747
protected function validateLimit(): void
    {
        $limit = $this->getArrayValue($this->joryArray, ['lmt', 'limit']);

        // No limit set, that's ok. return.
        if ($limit === null) {
            return;
        }

        if (! is_int($limit)) {
            throw new JoryException('The limit parameter should be an integer value. (Location: '.$this->address.'limit)');
        }
    }
167340
def _check_items_limit(self):
        
        if self.items_limit and self.items_limit == self.get_metadata('items_count'):
            raise ItemsLimitReached('Finishing job after items_limit reached:'
                                    ' {} items written.'.format(self.get_metadata('items_count')))
1333493
public function canCall( string $api_key, string $region, string $resource, string $endpoint): bool
	{
		$appLimits = $this->getAppLimits($api_key, $region);
		if (is_array($appLimits) && $resource != LeagueAPI::RESOURCE_STATICDATA)
		{
			foreach ($appLimits as $timeInterval => $limits)
			{
				//  Check all saved intervals for this region
				if ($limits['used'] >= $limits['limit'] && $limits['expires'] > time())
					return false;
			}
		}

		$methodLimits = $this->getMethodLimits($api_key, $region, $endpoint);
		if (is_array($methodLimits))
		{
			foreach ($methodLimits as $timeInterval => $limits)
			{
				//  Check all saved intervals for this endpoint
				if ($limits['used'] >= $limits['limit'] && $limits['expires'] > time())
					return false;
			}
		}

		return true;
	}
715983
protected void checkLimits() throws RecorderIOException {
        // too much material before finding end of headers? 
        if (messageBodyBeginMark<0) {
            // no mark yet
            if(position>MAX_HEADER_MATERIAL) {
                throw new RecorderTooMuchHeaderException();
            }
        }
        // overlong?
        if(position>maxLength) {
            throw new RecorderLengthExceededException(); 
        }
        // taking too long? 
        long duration = System.currentTimeMillis() - startTime; 
        duration = Math.max(duration,1); // !divzero
        if(duration>timeoutMs) {
            throw new RecorderTimeoutException(); 
        }
        // need to throttle reading to hit max configured rate? 
        if(position/duration >= maxRateBytesPerMs) {
            long desiredDuration = position / maxRateBytesPerMs;
            try {
                Thread.sleep(desiredDuration-duration);
            } catch (InterruptedException e) {
                logger.log(Level.WARNING,
                        "bandwidth throttling sleep interrupted", e);
            } 
        }
    }
36158
private boolean incSlotLimit(JobInfo info, TaskType type, LimitType limit) {
    switch (limit) {
      case MIN:
        if (type == TaskType.MAP) {
          if (info.minMaps < runnableTasks(info, type)) {
            info.minMaps += 1;
            return true;
          }
        } else {
          if (info.minReduces < runnableTasks(info, type)) {
            info.minReduces += 1;
            return true;
          }
        }
        return false;
      case MAX:
        if (type == TaskType.MAP) {
          if (info.maxMaps < runnableTasks(info, type)) {
            info.maxMaps += 1;
            return true;
          }
        } else {
          if (info.maxReduces < runnableTasks(info, type)) {
            info.maxReduces += 1;
            return true;
          }
        }
        return false;
    }
    // Never come here
    return false;
  }
352593
def is_within_content_length_limit(payload, api_config):
        
        length_limit = api_config.get('content_length_limit')
        if (length_limit is not None) and (payload["content"] is not None):
            content_length = len(payload["content"])
            if content_length > length_limit:
                return "Payload content too long: %s > %s" % (
                    content_length, length_limit)
        return None
773874
def api_params(service, file_id, owner_token, download_limit):
    """"""
    service += 'api/params/%s' % file_id
    r = requests.post(service, json={'owner_token': owner_token, 'dlimit': download_limit})
    r.raise_for_status()

    if r.text == 'OK':
        return True
    return False
425336
def _EnforceProcessMemoryLimit(self, memory_limit):
    
    # Resource is not supported on Windows.
    if resource:
      if memory_limit is None:
        memory_limit = 4 * 1024 * 1024 * 1024
      elif memory_limit == 0:
        memory_limit = resource.RLIM_INFINITY

      resource.setrlimit(resource.RLIMIT_DATA, (memory_limit, memory_limit))
455849
def isBelowLowerDetectionLimit(self):
        
        if self.isLowerDetectionLimit():
            return True

        result = self.getResult()
        if result and str(result).strip().startswith(LDL):
            return True

        if api.is_floatable(result):
            return api.to_float(result) < self.getLowerDetectionLimit()

        return False
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)
1693
public function registerAppLimits( string $api_key, string $region, string $app_header )
	{
		$limits = self::parseLimitHeaders($app_header);
		$this->initApp($api_key, $region, $limits);
	}
918099
def rate_limits(self):
        """"""
        if not self._rate_limits:
            self._rate_limits = utilities.get_rate_limits(self._response)
        return self._rate_limits
187802
def recheck_limits(self):
        

        limit_data = self.control_daemon.get_limits()

        try:
            # Get the new checksum and list of limits
            new_sum, new_limits = limit_data.get_limits(self.limit_sum)

            # Convert the limits list into a list of objects
            lims = database.limits_hydrate(self.db, new_limits)

            # Save the new data
            self.limits = lims
            self.limit_map = dict((lim.uuid, lim) for lim in lims)
            self.limit_sum = new_sum
        except control.NoChangeException:
            # No changes to process; just keep going...
            return
        except Exception:
            # Log an error
            LOG.exception("Could not load limits")

            # Get our error set and publish channel
            control_args = self.conf['control']
            error_key = control_args.get('errors_key', 'errors')
            error_channel = control_args.get('errors_channel', 'errors')

            # Get an informative message
            msg = "Failed to load limits: " + traceback.format_exc()

            # Store the message into the error set.  We use a set
            # here because it's likely that more than one node
            # will generate the same message if there is an error,
            # and this avoids an explosion in the size of the set.
            with utils.ignore_except():
                self.db.sadd(error_key, msg)

            # Publish the message to a channel
            with utils.ignore_except():
                self.db.publish(error_channel, msg)
1106353
def validate_api_compatibility(args):
  
  if args.api_version and args.api_version < MINIMUM_SUPPORTED_API_VERSION:
    print("ERROR: Given API version: {0}. Minimum supported API version: {1}"
          .format(args.api_version, MINIMUM_SUPPORTED_API_VERSION))
808905
private void verifyArguments(JmxExecRequest request, OperationAndParamType pTypes, int pNrParams, List<Object> pArgs) {
        if ( (pNrParams > 0 && pArgs == null) || (pArgs != null && pArgs.size() != pNrParams)) {
            throw new IllegalArgumentException("Invalid number of operation arguments. Operation " +
                    request.getOperation() + " on " + request.getObjectName() + " requires " + pTypes.paramClasses.length +
                    " parameters, not " + (pArgs == null ? 0 : pArgs.size()) + " as given");
        }
    }