Set X-Total-Count for all search requests
977007
function (ctx, next) {
    var filter;
    if (ctx.args && ctx.args.filter) {
      filter = ctx.args.filter.where;
    }

    if (!ctx.res._headerSent) {
      this.count(filter, function (err, count) {
        ctx.res.set('X-Total-Count', count);
        next();
      });
    } else {
      next();
    }
  }
1005169
def set_total_count(self, value):
        """"""
        if not self.total_count_flag and value:
            self._count.append(int(value))
            self.total_count_flag = True
822729
def CountHuntFlows(self,
                     hunt_id,
                     filter_condition=db.HuntFlowsCondition.UNSET,
                     cursor=None):
    """"""
    hunt_id_int = db_utils.HuntIDToInt(hunt_id)

    query = ("SELECT COUNT(*) FROM flows "
             "FORCE INDEX(flows_by_hunt) "
             "WHERE parent_hunt_id = %s AND parent_flow_id IS NULL "
             "{filter_condition}")

    filter_query, extra_args = self._HuntFlowCondition(filter_condition)
    args = [hunt_id_int] + extra_args
    query = query.format(filter_condition=filter_query)
    cursor.execute(query, args)
    return cursor.fetchone()[0]
1370821
def all_requests_view(request):
    '''
    
    '''
    # Pseudo-dictionary, actually a list with items of form
    # (request_type.name.title(), number_of_type_requests, name, enabled,
    # glyphicon)
    types_dict = list()
    for request_type in RequestType.objects.all():
        requests = Request.objects.filter(request_type=request_type)
        # Hide the count for private requests
        if not request_type.managers.filter(incumbent__user=request.user):
            requests = requests.exclude(
                ~Q(owner__user=request.user), private=True,
                )

        number_of_requests = requests.count()
        types_dict.append((
            request_type.name.title(), number_of_requests,
            request_type.url_name, request_type.enabled,
            request_type.glyphicon,
            ))
    return render_to_response('all_requests.html', {
        'page_name': "Archives - All Requests",
        'types_dict': types_dict,
        }, context_instance=RequestContext(request))
242328
def __get_search_results(self, url, limit, order_by, sort_order, filter):
        

        order_by_options = ['search_rank', 'series_id', 'title', 'units', 'frequency',
                            'seasonal_adjustment', 'realtime_start', 'realtime_end', 'last_updated',
                            'observation_start', 'observation_end', 'popularity']
        if order_by is not None:
            if order_by in order_by_options:
                url = url + '&order_by=' + order_by
            else:
                raise ValueError('%s is not in the valid list of order_by options: %s' % (order_by, str(order_by_options)))

        if filter is not None:
            if len(filter) == 2:
                url = url + '&filter_variable=%s&filter_value=%s' % (filter[0], filter[1])
            else:
                raise ValueError('Filter should be a 2 item tuple like (filter_variable, filter_value)')

        sort_order_options = ['asc', 'desc']
        if sort_order is not None:
            if sort_order in sort_order_options:
                url = url + '&sort_order=' + sort_order
            else:
                raise ValueError('%s is not in the valid list of sort_order options: %s' % (sort_order, str(sort_order_options)))

        data, num_results_total = self.__do_series_search(url)
        if data is None:
            return data

        if limit == 0:
            max_results_needed = num_results_total
        else:
            max_results_needed = limit

        if max_results_needed > self.max_results_per_request:
            for i in range(1, max_results_needed // self.max_results_per_request + 1):
                offset = i * self.max_results_per_request
                next_data, _ = self.__do_series_search(url + '&offset=' + str(offset))
                data = data.append(next_data)
        return data.head(max_results_needed)
760088
def _paginate(url, topkey, *args, **kwargs):
    '''
    
    '''

    ret = salt.utils.http.query(url, **kwargs)
    if 'errors' in ret['dict']:
        return ret['dict']

    lim = int(ret['dict']['page']['limit'])
    total = int(ret['dict']['page']['total'])

    if total == 0:
        return {}

    numpages = (total / lim) + 1

    # If the count returned is less than the page size, just return the dict
    if numpages == 1:
        return ret['dict'][topkey]

    aggregate_ret = ret['dict'][topkey]
    url = args[0]
    for p in range(2, numpages):
        param_url = url + '?offset={0}'.format(lim * (p - 1))
        next_ret = salt.utils.http.query(param_url, kwargs)
        aggregate_ret[topkey].extend(next_ret['dict'][topkey])

    return aggregate_ret
351101
def op_count(cls, crawler, stage=None):
        """"""
        if stage:
            total_ops = conn.get(make_key(crawler, stage))
        else:
            total_ops = conn.get(make_key(crawler, "total_ops"))
        return unpack_int(total_ops)
1137761
public SearchResponse searchAllWithTargetCount(String index, String type,
            QueryBuilder filterQueryBuilder,
            AggregationBuilder[] aggregationBuilders) {
        return searchAllWithTargetCount(JMArrays.buildArray(index),
                JMArrays.buildArray(type), filterQueryBuilder,
                aggregationBuilders);
    }
200257
def search_results_total(html, xpath, check, delimiter):
    
    for container in html.findall(xpath):
        if check in container.findtext('.'):
            text = container.findtext('.').split(delimiter)
            total = int(text[-1].strip())
            return total
448884
private function countLogs($installed = true, $upcoming = false, $search = null)
	{
		$total     = 0;
		$countArgs = array('--count');

		if (isset($search))
		{
			$countArgs[] = '-i';
			$countArgs[] = '--grep=' . escapeshellarg($search);
		}

		if ($installed)
		{
			$installedArgs = $countArgs;
			array_unshift($installedArgs, 'HEAD');
			$total = $this->call('rev-list', $installedArgs);
			$total = trim($total);
		}

		if ($upcoming)
		{
			$upcomingArgs = $countArgs;
			array_unshift($upcomingArgs, "HEAD..{$this->upstream}");
			$upcomingTotal = $this->call('rev-list', $upcomingArgs);
			$upcomingTotal = trim($upcomingTotal);
			$total += $upcomingTotal;
		}

		return trim($total);
	}
1223625
def _graphql_request_count_per_sliding_window(self, query_hash: str) -> int:
        """"""
        if self.is_logged_in:
            max_reqs = {'1cb6ec562846122743b61e492c85999f': 20, '33ba35852cb50da46f5b5e889df7d159': 20}
        else:
            max_reqs = {'1cb6ec562846122743b61e492c85999f': 200, '33ba35852cb50da46f5b5e889df7d159': 200}
        return max_reqs.get(query_hash) or min(max_reqs.values())
25516
function buildCount (opts) {
  // eslint-disable-next-line no-unused-vars
  const { makeRequest, ConfigurationError, handleError, snakeCaseKeys } = opts
  /**
   * Perform a [count](http://www.elastic.co/guide/en/elasticsearch/reference/master/search-count.html) request
   *
   * @param {list} index - A comma-separated list of indices to restrict the results
   * @param {list} type - A comma-separated list of types to restrict the results
   * @param {boolean} ignore_unavailable - Whether specified concrete indices should be ignored when unavailable (missing or closed)
   * @param {boolean} ignore_throttled - Whether specified concrete, expanded or aliased indices should be ignored when throttled
   * @param {boolean} allow_no_indices - Whether to ignore if a wildcard indices expression resolves into no concrete indices. (This includes `_all` string or when no indices have been specified)
   * @param {enum} expand_wildcards - Whether to expand wildcard expression to concrete indices that are open, closed or both.
   * @param {number} min_score - Include only documents with a specific `_score` value in the result
   * @param {string} preference - Specify the node or shard the operation should be performed on (default: random)
   * @param {list} routing - A comma-separated list of specific routing values
   * @param {string} q - Query in the Lucene query string syntax
   * @param {string} analyzer - The analyzer to use for the query string
   * @param {boolean} analyze_wildcard - Specify whether wildcard and prefix queries should be analyzed (default: false)
   * @param {enum} default_operator - The default operator for query string query (AND or OR)
   * @param {string} df - The field to use as default where no field prefix is given in the query string
   * @param {boolean} lenient - Specify whether format-based query failures (such as providing text to a numeric field) should be ignored
   * @param {number} terminate_after - The maximum count for each shard, upon reaching which the query execution will terminate early
   * @param {object} body - A query to restrict the results specified with the Query DSL (optional)
   */

  const acceptedQuerystring = [
    'ignore_unavailable',
    'ignore_throttled',
    'allow_no_indices',
    'expand_wildcards',
    'min_score',
    'preference',
    'routing',
    'q',
    'analyzer',
    'analyze_wildcard',
    'default_operator',
    'df',
    'lenient',
    'terminate_after',
    'pretty',
    'human',
    'error_trace',
    'source',
    'filter_path'
  ]

  const snakeCase = {
    ignoreUnavailable: 'ignore_unavailable',
    ignoreThrottled: 'ignore_throttled',
    allowNoIndices: 'allow_no_indices',
    expandWildcards: 'expand_wildcards',
    minScore: 'min_score',
    analyzeWildcard: 'analyze_wildcard',
    defaultOperator: 'default_operator',
    terminateAfter: 'terminate_after',
    errorTrace: 'error_trace',
    filterPath: 'filter_path'
  }

  return function count (params, options, callback) {
    options = options || {}
    if (typeof options === 'function') {
      callback = options
      options = {}
    }
    if (typeof params === 'function' || params == null) {
      callback = params
      params = {}
      options = {}
    }

    // check required url components
    if (params['type'] != null && (params['index'] == null)) {
      const err = new ConfigurationError('Missing required parameter of the url: index')
      return handleError(err, callback)
    }

    // validate headers object
    if (options.headers != null && typeof options.headers !== 'object') {
      const err = new ConfigurationError(`Headers should be an object, instead got: ${typeof options.headers}`)
      return handleError(err, callback)
    }

    var warnings = []
    var { method, body, index, type, ...querystring } = params
    querystring = snakeCaseKeys(acceptedQuerystring, snakeCase, querystring, warnings)

    if (method == null) {
      method = body == null ? 'GET' : 'POST'
    }

    var ignore = options.ignore
    if (typeof ignore === 'number') {
      options.ignore = [ignore]
    }

    var path = ''

    if ((index) != null && (type) != null) {
      path = '/' + encodeURIComponent(index) + '/' + encodeURIComponent(type) + '/' + '_count'
    } else if ((index) != null) {
      path = '/' + encodeURIComponent(index) + '/' + '_count'
    } else {
      path = '/' + '_count'
    }

    // build request object
    const request = {
      method,
      path,
      body: body || '',
      querystring
    }

    options.warnings = warnings.length === 0 ? null : warnings
    return makeRequest(request, options, callback)
  }
}
239854
def query_count():
        '''
        
        '''
        recs = TabPost2Tag.select(
            TabPost2Tag.tag_id,
            peewee.fn.COUNT(TabPost2Tag.tag_id).alias('num')
        ).group_by(
            TabPost2Tag.tag_id
        )
        return recs
1336904
function PageResultInfinite(items, totalCount, requestIndex, nextIndex, baseUrl) {
      this.items = items != null ? items : [];
      this.totalCount = totalCount != null ? totalCount : 0;
      this.requestIndex = requestIndex;
      this.nextIndex = nextIndex != null ? nextIndex : null;
      this.baseUrl = baseUrl != null ? baseUrl : null;
      this.toRest = __bind(this.toRest, this);

    }
993812
public function getAllUsers($count=1000, $offset=0, $searchToken=null) {
        global $logger;
        $path    = 'users';
        $request = $this->_remoteServer->get($path);
        if(!empty($searchToken)) {
            $request->getQuery()->set('searchToken', $searchToken);
        }
        $request->getQuery()->set('numUsers', $count);
        $request->getQuery()->set('offset', $offset);
        try {
            $response = $request->send();
        } catch(\Guzzle\Http\Exception\BadResponseException $e) {
            $logger->info($e->getResponse()->getBody('true'), array());
            return false;
        }

        return $response->json();
    }
338099
function(resp){	

	// Update the bar.
	requests_done++;
	jQuery('#progress-bar').progressbar({ value: requests_done });
	jQuery("#progress-count").empty();
	jQuery("#progress-count").append(requests_done);

	// Count is easy.
	var count = resp.total_documents();
	if( count > max_count ){
	    max_count = count;
	}

	// Now let's try and fiqure out which terms we were looking
	// at...
	var fqs = resp.query_filters();
	//console.log(resp);
	var fprops = fqs[closure_type];

	var axes = [];
	us.each(fprops, function(fval, fkey){
	    axes.push(fkey);
	});	
	var axis1 = axes[0];
	var axis2 = axes[1] || axis1; // the reflexive case

	ll(' Data from: (' + axis1 + ', ' + axis2 + '); ' + count);

	// Structure for the links we've seen, level 1.
	if( typeof(seen_links[axis1]) === 'undefined' ){
	    seen_links[axis1] = {}; }
	if( typeof(seen_links[axis2]) === 'undefined' ){
	    seen_links[axis2] = {}; }
	// Mark the links we've seen, level 2.
	if( typeof(seen_links[axis2][axis1]) === 'undefined' ){
	    seen_links[axis2][axis1] = count; }
	if( typeof(seen_links[axis1][axis2]) === 'undefined' ){
	    seen_links[axis1][axis2] = count; }
    }
1018480
async def list(self, *args, **kwargs):
        '''
        
        '''
        limit = int(kwargs.pop('limit', self.limit))
        limit = 1000 if limit == 0 else limit  # lets not go crazy here
        offset = int(kwargs.pop('offset', self.offset))
        projection = None
        # perform full text search or standard filtering
        if self._meta.fts_operator in kwargs.keys():
            filters = {
                '$text': {'$search': kwargs[self._meta.fts_operator]}
            }
            projection = {'score': {'$meta': 'textScore'}}
            sort = [('score', {'$meta': 'textScore'}, )]
        else:
            # build filters from query parameters
            filters = self.build_filters(**kwargs)
            # add custom query defined in resource meta, if exists
            if isinstance(self._meta.query, dict):
                filters.update(self._meta.query)
            # build sorts from query parameters
            sort = self.build_sort(**kwargs)
            if isinstance(self._meta.sort, list):
                sort.extend(self._meta.sort)
        cursor = self._meta.object_class.get_cursor(db=self.db, query=filters, projection=projection, sort=sort)
        cursor.skip(offset)
        cursor.limit(limit)
        total_count = await self._meta.object_class.count(db=self.db, filters=filters)
        object_list = await self._meta.object_class.find(cursor)
        # serialize results
        serialized_objects = await asyncio.gather(*[obj.serialize() for obj in object_list])
        # signal post list
        asyncio.ensure_future(resource_post_list.send(
            sender=self._meta.object_class,
            db=self.db,
            instances=object_list)
        )
        return {
            'meta': {
                'total_count': total_count,
                'limit': limit,
                'offset': offset
            },
            'objects': serialized_objects
        }