Sort query results if necessary
188714
function sortQueryresults(matches, order) {
  const orderArray = order.split(',').map(k => {
    let dir = 'asc';
    let key = k;

    if (k.charAt(0) === '-') {
      key = k.substring(1);
      dir = 'desc';
    }

    return [item => deserializeQueryParam(item[key]), dir];
  });

  const keys = orderArray.map(_.first);
  const orders = orderArray.map(_.last);

  return _.orderBy(matches, keys, orders);
}
97998
def _pull_query_results(resultset):
    '''
    
    '''
    _results = collections.defaultdict(lambda: {})
    for _header, _values in resultset.items():
        _header, _group_tags = _header
        if _group_tags:
            _results[_header][salt.utils.json.dumps(_group_tags)] = [_value for _value in _values]
        else:
            _results[_header] = [_value for _value in _values]
    return dict(sorted(_results.items()))
63407
function (query, items) {
            var sortExpressions = query.query.sort,
                self = this;

            if(sortExpressions){
                return items.sort(function (a, b) {
                    var sortExpression,
                        ret = 0;
                    for (var i = 0; i < sortExpressions.length; i++) {
                        sortExpression = sortExpressions[i];
                        ret = self._compareExpression(a, b, sortExpression);
                        if (ret !== 0) {
                            return ret;
                        }
                    }
                    return ret;
                });
            } else {
                return items;
            }

        }
1267691
public function sort_columns($query)
    {
        // Bail if we are not on the correct admin page.
        if (! $query->is_main_query() || ! is_admin() || $query->get('post_type') !== $this->get_name()) {
            return;
        }

        $order_by = $query->get('orderby');

        // Check if the current sorted column has a sort callback defined.
        if (isset($this->sortable_columns[ $order_by ])) {
            $callback = "sort_{$order_by}_column";
            $this->{$callback}($query);
        }
    }
57999
def sort_query(self, query, sort_info):
        
        for sort_opt in sort_info:
            field = sort_opt['field']
            if not hasattr(self.model, field):
                raise InvalidSort("{} has no attribute {}".format(self.model.__name__, field))
            query = query.order_by(getattr(getattr(self.model, field), sort_opt['order'])())
        return query
555904
def sort_pattern(self):
        """"""
        if not self._sort_pattern:

            # trigger evaluation of operation
            if self.operation in ['query', 'getmore']:
                self._sort_pattern = self._find_pattern('orderby: ')

        return self._sort_pattern
347867
def sort(records: Sequence[Record]) -> List[Record]:
    ""
    return sorted(records, key=_record_key)
188689
def _sortObjects(orderby='created', **kwargs):
    """"""
    o = []
    
    for m in kwargs.values():
        for l in iter(m):
            o.append(l)
    o = list(set(o))
    sortfunc = _sortByCreated if orderby == 'created' else _sortByModified
    if six.PY2:
        o.sort(sortfunc)
    else:
        o.sort(key=functools.cmp_to_key(sortfunc))

    return o
424934
def unsorted_query
      records = scope
      # Text Search
      if search_term
        escaped = Regexp.escape(search_term)
        regexp  = Regexp.new(escaped, Regexp::IGNORECASE)
        if search_columns.size == 1
          records = records.where(search_columns.first => regexp)
        else
          cols    = search_columns.collect { |col| {col => regexp} }
          records = records.where('$or' => cols)
        end
      end

      # Pagination
      if start && page_size
        records = records.skip(start).limit(page_size)
      end
      records
    end
296873
function orderResults (results) {
    // get id column names
    var idColumn = this.model.defaultColumnsInverse.id
    // require id column for model
    if (!defined(idColumn)) {
        return results
    }
    // get id column name that was used for query
    var queryIdColumn = defined(this.args.where.id)
        ? 'id'
        : defined(this.args.where[idColumn])
            ? idColumn
            : undefined
    // if query was not on id column then do not reorder
    if (!defined(queryIdColumn)) {
        return results
    }
    // list of ids as querired
    var queryIds
    // if id property is array then get ids
    if (Array.isArray(this.args.where[queryIdColumn])) {
        queryIds = this.args.where[queryIdColumn]
    }
    // if id has an in query with array then get ids
    else if (typeof this.args.where[queryIdColumn] === 'object' && Array.isArray(this.args.where[queryIdColumn].in)) {
        queryIds = this.args.where[queryIdColumn].in
    }
    // if query is not by list of ids then do not reorder
    if (!defined(queryIds)) {
        return results
    }
    // group results by id - if current record was queried then must use
    // the id that column was selected by instead of record id
    var resultsById = _.keyBy(results, this.args.current ? idColumn+'Select' : idColumn)
    // ordered result set
    var orderedRes = []
    // iterate over queried ids and add to ordered result set
    _.each(queryIds, queryId => {
        if (defined(resultsById[queryId])) {
            orderedRes.push(resultsById[queryId])
        }
    })

    return orderedRes
}
760401
protected function sortRecords(&$results, ReadQuery $query)
    {
        if (list($sortField, $sortDirection) = $query->getSortBy()) {
            usort($results, function($a, $b) use ($sortField, $sortDirection) {

                $leftValue = $this->getRecordField($a, $sortField);
                $rightValue = $this->getRecordField($b, $sortField);

                if ($sortDirection == 'DESC') {
                    return strcmp((string) $rightValue, (string) $leftValue);
                } else {
                    return strcmp((string) $leftValue, (string) $rightValue);
                }
            });
        }
    }
745088
function swagSort(sort) {

	// TODO unstable sorts

	var param = {};
	for (var p in params) {
		if (params[p].name == 'sort') {
			param = params[p];
		}
	}
	if (!param.name) {
		param.name = 'sort';
		param.in = 'query';
		param.description = 'Sorts:\n';
		param.schema = {};
		param.schema.type = 'string';
		param.required = false;
		param.schema.enum = [];
		params.push(param);
	}
	param.schema.enum.push(sort.name);
	param.description += '* '+sort.name+': '+sort.title+'\n';
}
141357
function mergeQueries(query, options) {
  if (options == null) {
    return query;
  }

  Object.keys(options).forEach(key => {
    let label = key;
    let value = options[key];

    validateProp(key, value);

    switch (key) {
    case 'orderByKey':
      label = orderedBy;
      value = orderByKey;
      break;

    case 'orderByPriority':
      label = orderedBy;
      value = orderByPriority;
      break;

    case 'orderByValue':
      label = orderedBy;
      value = orderByValue;
      break;

    case 'orderByChild':
      label = orderedBy;
      break;

    default:
      break;
    }

    query[label] = value;
  });

  return query;
}
18965
public function sort_columns($query)
    {
        // Bail if we are not on the correct admin page.
        if (! \is_admin() || !\in_array($this->name, $query->query_vars['taxonomy'])) {
            return;
        }

        $order_by = $query->get('orderby');

        // Check if the current sorted column has a sort callback defined.
        if (isset($this->sortable_columns[ $order_by ])) {
            $callback = "sort_{$order_by}_column";
            $this->{$callback}($query);
        }
    }
1246517
def resolve_sorting(self, query):
        
        sorting = {}

        # Sort on
        sort_on = query.get("sidx", None)
        sort_on = sort_on or query.get("sort_on", None)
        sort_on = sort_on == "Title" and "sortable_title" or sort_on
        if sort_on:
            sorting["sort_on"] = sort_on

            # Sort order
            sort_order = query.get("sord", None)
            sort_order = sort_order or query.get("sort_order", None)
            if sort_order in ["desc", "reverse", "rev", "descending"]:
                sorting["sort_order"] = "descending"
            else:
                sorting["sort_order"] = "ascending"

            # Sort limit
            sort_limit = api.to_int(query.get("limit", 30), default=30)
            if sort_limit:
                sorting["sort_limit"] = sort_limit

        return sorting
416198
function (db, index, whereClause, sortBys, cb) {
			var query = encodeURIComponent(whereClause);
			var url = host +
				'databases/' + db +
				'/indexes/' + index +
				'?query=' + query +
				'&operator=AND&pageSize=0&start=0';
			var urlPartSort = sortBys.map(function (prop) {
				return '&sort=' + prop;
			}).join('');
			request(url, function (error, response, body) {
				if (!error && response.statusCode === 200) {
					var result = JSON.parse(body);
					var pageSize = 1024;
					var stats = _.reduce(result, function (memo, value, key) {
						if (key !== "Results") {
							memo[key] = value;
						}
						return memo;
					}, {});
					var totalResults = stats.TotalResults;
					var pageCount = parseInt(totalResults / pageSize);
					var delta = totalResults - pageCount * pageSize;
					if (delta > 0)
						pageCount++;
					var requests = [];
					for (var i = 0; i < pageCount; i++) {
						requests.push({
							Url: '/indexes/' + index,
							Query: 'start=' + i * pageSize + '&pageSize=' + pageSize + '&query=' + query + urlPartSort
						});
					}
					var multiGetBody = JSON.stringify(requests);
					var multiGetUrl = host + 'databases/' + db + '/multi_get';
					request.post({
							url: multiGetUrl,
							body: multiGetBody
						},
						function (err, resp, multiGetResponseBody) {
							if (!err && resp.statusCode === 200) {
								var multiGetResponse = JSON.parse(multiGetResponseBody);
								var results =
									_.flatten(_.reduce(multiGetResponse
										, function (memo, val) {
											if (val.Result && val.Result.Results)
												memo.push(val.Result.Results);
											return memo;
										}
										, []));
								cb(null, results);
							} else {
								cb(err || new Error(resp.statusCode), null);
							}
						});
				}
				else {
					cb(error || new Error(response.statusCode), null);
				}
			});
		}
615211
def sort_by(self, name, sort_dir='asc'):
        """"""
        logger.log(5, "Sort by `%s` %s.", name, sort_dir)
        self.eval_js('table.sortBy("{}", "{}");'.format(name, sort_dir))