Count the resources requested and fail the job if they are above the limit

@param requestList List of resource requests to check
193758
protected void checkResourceRequestLimit(
      List<ResourceRequest> requestList, String handle)
      throws InvalidSessionHandle {
    ConfigManager configManager = getScheduler().getConfigManager();
    Session session = sessionManager.getSession(handle);
    PoolInfo poolInfo = session.getPoolInfo();

    // Only check the resource requests if this pool is configured to not
    // accept more than a fixed number of requests at the same time
    if (!configManager.useRequestMax(poolInfo)) {
      return;
    }

    // Count the resources by type
    ResourceTypeCounter resourceTypeCounter = new ResourceTypeCounter();
    for (ResourceRequest req : requestList) {
      resourceTypeCounter.incr(req.type);
    }

    // No resource type request should exceed the maximum
    for (ResourceType resourceType : ResourceType.values()) {
      if (configManager.getPoolMaximum(poolInfo, resourceType) <
          resourceTypeCounter.getCount(resourceType)) {
        String failureMessage =
            "Session " + handle + " requested " +
                resourceTypeCounter.getCount(resourceType) +
                " resources for resource type " +
                resourceType + " but was only allowed " +
                configManager.getPoolMaximum(poolInfo, resourceType) + ", " +
                "so failing the job";
        LOG.error(failureMessage);
        throw new InvalidSessionHandle(failureMessage);
      }
    }
  }
697039
private List<FailedBatch> writeOneBatch(
            StringListMap<WriteRequest> batch,
            BatchWriteRetryStrategy batchWriteRetryStrategy) {

        List<FailedBatch> failedBatches = new LinkedList<FailedBatch>();
        FailedBatch failedBatch = doBatchWriteItemWithRetry(batch, batchWriteRetryStrategy);

        if (failedBatch != null) {
            // If the exception is request entity too large, we divide the batch
            // into smaller parts.

            if (failedBatch.isRequestEntityTooLarge()) {

                // If only one item left, the item size must beyond 64k, which
                // exceedes the limit.

                if (failedBatch.size() == 1) {
                    failedBatches.add(failedBatch);
                } else {
                    for (final StringListMap<WriteRequest> subBatch : batch.subMaps(2, false)) {
                        failedBatches.addAll(writeOneBatch(subBatch, batchWriteRetryStrategy));
                    }
                }

            } else {
                failedBatches.add(failedBatch);
            }

        }
        return failedBatches;
    }
1049209
public List<ISubmission> getSubmissions(String resourceUrl) throws Exception{
		ParadataFetcher fetcher = new ParadataFetcher(node, resourceUrl);
		return fetcher.getSubmissions();
	}
460486
function(list) {

        var i = self.tasksCount;

        if (i > list.length-1) {
            process.exit(0)
        }

        var err = false;
        var cb = ( typeof(list[i].cb) != 'undefined' ) ? list[i].cb : false;

        if (cb) {
            list[i].func( function done(err, data) {
                if (err) {
                    console.error(err.stack||err.message);
                    process.exit(1)
                } else {
                    if (data) {
                        //var str = data.toString();
                        console.info(data);
                    }
                    ++self.tasksCount;
                    run(list)
                }

            })
        } else {
            try {
                list[i].func();
                ++self.tasksCount;
                run(list)
            } catch (err) {
                console.error(err.stack);
                process.exit(1)
            }
        }
    }
594868
public void setProvisionedCapacityList(java.util.Collection<ProvisionedCapacityDescription> provisionedCapacityList) {
        if (provisionedCapacityList == null) {
            this.provisionedCapacityList = null;
            return;
        }

        this.provisionedCapacityList = new java.util.ArrayList<ProvisionedCapacityDescription>(provisionedCapacityList);
    }
1012646
public int getRegisteredResourceRequestCount(K key) {
        if(requestQueueMap.containsKey(key)) {
            Queue<AsyncResourceRequest<V>> requestQueue = getRequestQueueForExistingKey(key);
            // FYI: .size() is not constant time in the next call. ;)
            if(requestQueue != null) {
                return requestQueue.size();
            }
        }
        return 0;
    }
483356
func (c *Client) List(resource string, resp interface{}, options ...RequestOptions) (count, total int, err error) {
	url := buildURL(c.apiBase, &Request{Resource: resource})
	req, err := createRequest("GET", url, nil, nil, options...)
	if err != nil {
		return count, total, err
	}

	c.Lock()
	defer c.Unlock()
	return c.httpClient.Send(req).Read(resp).Call()
}
1321973
private void checkChildLocks(HttpServletRequest req, String path, Hashtable<String, Integer> errorList) {

        List<I_CmsRepositoryItem> list = null;
        try {
            list = m_session.list(path);
        } catch (CmsException e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(Messages.get().getBundle().key(Messages.LOG_LIST_ITEMS_ERROR_1, path), e);
            }
            errorList.put(path, new Integer(CmsWebdavStatus.SC_INTERNAL_SERVER_ERROR));
            return;
        }

        Iterator<I_CmsRepositoryItem> iter = list.iterator();
        while (iter.hasNext()) {
            I_CmsRepositoryItem element = iter.next();

            if (isLocked(element.getName())) {
                errorList.put(element.getName(), new Integer(CmsWebdavStatus.SC_LOCKED));
            } else {
                if (element.isCollection()) {
                    checkChildLocks(req, element.getName(), errorList);
                }
            }
        }
    }
161642
public void executeQueriesList(List<String> queriesList) {

        for (String query : queriesList) {
            this.session.execute(query);
        }
    }
1151752
public List<RpcResponse> request(List<RpcRequest> reqList) {
        for (RpcRequest req : reqList) {
            this.reqList.add(req);
        }

        return null;
    }
36147
private void doList() throws PageException {
	// if(tr ue) throw new PageRuntimeException("qqq");
	ScheduleTask[] tasks = scheduler.getAllScheduleTasks();
	final String v = "VARCHAR";
	String[] cols = new String[] { "task", "path", "file", "startdate", "starttime", "enddate", "endtime", "url", "port", "interval", "timeout", "username", "password",
		"proxyserver", "proxyport", "proxyuser", "proxypassword", "resolveurl", "publish", "valid", "paused", "autoDelete" };
	String[] types = new String[] { v, v, v, "DATE", "OTHER", "DATE", "OTHER", v, v, v, v, v, v, v, v, v, v, v, "BOOLEAN", v, "BOOLEAN", "BOOLEAN" };
	lucee.runtime.type.Query query = new QueryImpl(cols, types, tasks.length, "query");
	try {
	    for (int i = 0; i < tasks.length; i++) {
		int row = i + 1;
		ScheduleTask task = tasks[i];
		query.setAt(KeyConstants._task, row, task.getTask());
		if (task.getResource() != null) {
		    query.setAt(KeyConstants._path, row, task.getResource().getParent());
		    query.setAt(KeyConstants._file, row, task.getResource().getName());
		}
		query.setAt("publish", row, Caster.toBoolean(task.isPublish()));
		query.setAt("startdate", row, task.getStartDate());
		query.setAt("starttime", row, task.getStartTime());
		query.setAt("enddate", row, task.getEndDate());
		query.setAt("endtime", row, task.getEndTime());
		query.setAt(KeyConstants._url, row, printUrl(task.getUrl()));
		query.setAt(KeyConstants._port, row, Caster.toString(HTTPUtil.getPort(task.getUrl())));
		query.setAt("interval", row, task.getStringInterval());
		query.setAt("timeout", row, Caster.toString(task.getTimeout() / 1000));
		query.setAt("valid", row, Caster.toString(task.isValid()));
		if (task.hasCredentials()) {
		    query.setAt("username", row, task.getCredentials().getUsername());
		    query.setAt("password", row, task.getCredentials().getPassword());
		}
		ProxyData pd = task.getProxyData();
		if (ProxyDataImpl.isValid(pd)) {
		    query.setAt("proxyserver", row, pd.getServer());
		    if (pd.getPort() > 0) query.setAt("proxyport", row, Caster.toString(pd.getPort()));
		    if (ProxyDataImpl.hasCredentials(pd)) {
			query.setAt("proxyuser", row, pd.getUsername());
			query.setAt("proxypassword", row, pd.getPassword());
		    }
		}
		query.setAt("resolveurl", row, Caster.toString(task.isResolveURL()));

		query.setAt("paused", row, Caster.toBoolean(task.isPaused()));
		query.setAt("autoDelete", row, Caster.toBoolean(((ScheduleTaskImpl) task).isAutoDelete()));

	    }
	    pageContext.setVariable(result, query);
	}
	catch (DatabaseException e) {}

    }
87478
private void postStatementList(List<LrsStatement> list) {
        try {
            ResponseEntity<Object> response =
                    sendRequest(
                            STATEMENTS_REST_ENDPOINT, HttpMethod.POST, null, list, Object.class);
            if (response.getStatusCode().series() == Series.SUCCESSFUL) {
                logger.trace(
                        "LRS provider successfully sent to {}, statement list: {}",
                        getLRSUrl(),
                        list);
                logger.trace("Sent batch statement.  RESULTS: " + response.getBody().toString());
            } else {
                logger.error(
                        "LRS provider failed to send to {}, statement list: {}", getLRSUrl(), list);
                logger.error("- Response: {}", response);
            }
            // todo: Need to think through a strategy for handling errors submitting
            // to the LRS.
        } catch (HttpClientErrorException e) {
            // log some additional info in this case...
            logger.error(
                    "LRS provider for URL " + getLRSUrl() + " failed to send statement list", e);
            logger.error(
                    "- Status: {}, Response: {}", e.getStatusCode(), e.getResponseBodyAsString());

        } catch (Exception e) {
            logger.error(
                    "LRS provider for URL " + getLRSUrl() + " failed to send statement list", e);
        }
    }
1358717
public List<ResourceRequest> getWantedResources() {
    List<ResourceRequest> wanted = new ArrayList<ResourceRequest>();
    synchronized(lockObject) {
      for (Integer requestId:
        setDifference(requestMap.keySet(), requestedResources.keySet())) {
        ResourceRequest req = requestMap.get(requestId);
        LOG.info("Filing request for resource " + requestId);
        requestedResources.put(requestId, req);
        wanted.add(req);
      }
    }
    return wanted;
  }
913030
private void failRequests() {
    final Set<OngoingRequest> requests = ImmutableSet.copyOf(outstanding);
    for (OngoingRequest id : requests) {
      final boolean removed = outstanding.remove(id);
      if (removed) {
        id.reply(Response.forStatus(Status.SERVICE_UNAVAILABLE));
      }
    }
  }
956658
public static long count(nitro_service service) throws Exception{
		service obj = new service();
		options option = new options();
		option.set_count(true);
		service[] response = (service[])obj.get_resources(service, option);
		if (response != null) {
			return response[0].__count;
		}
		return 0;
	}
72441
private void validateNumberOfTasks(int splits, int reduceTasks, JobConf conf) 
    throws IOException {
    int maxTasks = conf.getInt("mapred.jobtracker.maxtasks.per.job", -1);
    int totalTasks = splits + reduceTasks;

    if ((maxTasks!= -1) && (totalTasks > maxTasks)) {
      throw new IOException(
                "The number of tasks for this job " +
                totalTasks +
                " exceeds the configured limit " + maxTasks);
    }
  }
1252624
def list(self, request, project):
        
        MAX_JOBS_COUNT = 2000

        # make a mutable copy of these params
        filter_params = request.query_params.copy()

        # various hacks to ensure API backwards compatibility
        for param_key in filter_params.keys():
            # replace `result_set_id` with `push_id`
            if param_key.startswith('result_set_id'):
                new_param_key = param_key.replace('result_set_id', 'push_id')
                filter_params[new_param_key] = filter_params[param_key]
                del filter_params[param_key]
            # convert legacy timestamp parameters to time ones
            elif param_key in ['submit_timestamp', 'start_timestamp',
                               'end_timestamp']:
                new_param_key = param_key.replace('timestamp', 'time')
                filter_params[new_param_key] = datetime.datetime.fromtimestamp(
                    float(filter_params[param_key]))
                del filter_params[param_key]
            # sanity check 'last modified'
            elif param_key.startswith('last_modified'):
                datestr = filter_params[param_key]
                try:
                    parser.parse(datestr)
                except ValueError:
                    return Response(
                        "Invalid date value for `last_modified`: {}".format(datestr),
                        status=HTTP_400_BAD_REQUEST)

        try:
            offset = int(filter_params.get("offset", 0))
            count = int(filter_params.get("count", 10))
        except ValueError:
            return Response(
                "Invalid value for offset or count",
                status=HTTP_400_BAD_REQUEST)
        return_type = filter_params.get("return_type", "dict").lower()

        if count > MAX_JOBS_COUNT:
            msg = "Specified count exceeds API MAX_JOBS_COUNT value: {}".format(MAX_JOBS_COUNT)
            return Response({"detail": msg}, status=HTTP_400_BAD_REQUEST)

        try:
            repository = Repository.objects.get(name=project)
        except Repository.DoesNotExist:
            return Response({
                "detail": "No project with name {}".format(project)
            }, status=HTTP_404_NOT_FOUND)
        jobs = JobFilter({k: v for (k, v) in filter_params.items()},
                         queryset=Job.objects.filter(
                             repository=repository).select_related(
                                 *self._default_select_related)).qs

        response_body = self._get_job_list_response(jobs, offset, count,
                                                    return_type)
        response_body["meta"] = dict(repository=project, offset=offset,
                                     count=count)

        return Response(response_body)