Returns an ordered list of eligable matches.
 Orders matches based on media_type, ensuring priority and definition order are respected appropriately.
 Sorts by mapping priority first, media type appropriateness second, and definition order third.
488262
def eligable_matches
      @_eligable_matches ||= begin
        matches.select { |m| m.failed_condition.nil? }.each_with_index.sort_by do |m,idx|
          priority = m.mapping[:priority] || 0
          media_type_rank = [*m.mapping[:conditions][:media_type]].map { |type|
            env['scorched.accept'][:accept].rank(type, true)
          }.max || 0
          order = -idx
          [priority, media_type_rank, order]
        end.reverse
      end
    end
908940
def order(self):
        
        return [x.val for theclass in self.classes for x in theclass.items]
1071827
def try_matches
      eligable_matches.each do |match,idx|
        request.breadcrumb << match
        catch(:pass) {
          dispatch(match)
          return true
        }
        request.breadcrumb.pop # Current match passed, so pop the breadcrumb before the next iteration.
      end
      response.status = (!matches.empty? && eligable_matches.empty?) ? 403 : 404
    end
1333573
def sort_order(options = {})
      [[prefix, last].compact.join(' '), suffix, options[:initials] ? initials : first].compact.join(', ')
    end
654866
def find_mime_type_matches(q_value_header, available)
      find_q_matches(q_value_header, available) do |a, b|
        match_mime_type?(a, b)
      end
    end
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);
}
701469
def _get_media(media_types):
    """"""
    get_mapped_media = (lambda x: maps.VIRTUAL_MEDIA_TYPES_MAP[x]
                        if x in maps.VIRTUAL_MEDIA_TYPES_MAP else None)
    return list(map(get_mapped_media, media_types))
197240
def order_by(self, *field_names):
        
        if not self._search_ordered:
            self._search_ordered = len(self._search_terms) > 0
        return super(SearchableQuerySet, self).order_by(*field_names)
752011
def get_all_supported_types_for_ext(self, ext_to_match: str, strict_type_matching: bool = False) -> Set[Type]:
        
        matching = self.find_all_matching_parsers(required_ext=ext_to_match, strict=strict_type_matching)[0]
        return {typ for types in [p.supported_types for p in (matching[0] + matching[1] + matching[2])]
                for typ in types}
1280294
private static <T extends Storable> OrderingList<T>
        expectedOrdering(StorageAccess<T> access, Filter<T> filter, OrderingList<T> ordering)
    {
        List<Filter<T>> split;
        if (filter == null) {
            split = Filter.getOpenFilter(access.getStorableType()).disjunctiveNormalFormSplit();
        } else {
            split = filter.disjunctiveNormalFormSplit();
        }

        Comparator comparator = CompositeScore.fullComparator();

        CompositeScore bestScore = null;
        for (StorableIndex<T> index : access.getAllIndexes()) {
            for (Filter<T> sub : split) {
                CompositeScore candidateScore = CompositeScore.evaluate(index, sub, ordering);
                if (bestScore == null || comparator.compare(candidateScore, bestScore) < 0) {
                    bestScore = candidateScore;
                }
            }
        }

        // Reduce source ordering to that which can be handled for
        // free. Otherwise, a sort would be performed which is a waste of time
        // if some source results will later be filtered out.
        int handledCount = bestScore == null ? 0 : bestScore.getOrderingScore().getHandledCount();
        return ordering.subList(0, handledCount);
    }
1069625
def lookup_field_orderable(self, field):
        
        try:
            self.model._meta.get_field_by_name(field)
            return True
        except Exception:
            # that field doesn't exist, so not sortable
            return False
1155575
def parse_accept_header(accept):
    

    def parse_media_range(accept_item):
        """ Parse media range and subtype """

        return accept_item.split('/', 1)

    def comparator(a, b):
        """ Compare accept items a and b """

        # first compare q values
        result = -cmp(a[2], b[2])
        if result is not 0:
            # q values differ, no need to compare media types
            return result

        # parse media types and compare them (asterisks are lower in precedence)
        mtype_a, subtype_a = parse_media_range(a[0])
        mtype_b, subtype_b = parse_media_range(b[0])
        if mtype_a == '*' and subtype_a == '*':
            return 1
        if mtype_b == '*' and subtype_b == '*':
            return -1
        if subtype_a == '*':
            return 1
        if subtype_b == '*':
            return -1
        return 0

    if not accept:
        return []

    result = []
    for media_range in accept.split(","):
        parts = media_range.split(";")
        media_type = parts.pop(0).strip()
        media_params = []
        q = 1.0
        for part in parts:
            (key, value) = part.lstrip().split("=", 1)
            if key == "q":
                q = float(value)
            else:
                media_params.append((key, value))
        result.append((media_type, tuple(media_params), q))
    result.sort(comparator)
    return result
650179
def ordered_tags(self):
        
        tags = list(self.tags.all())
        return sorted(
            tags,
            key=lambda tag: ((type(tag) != Tag) * 100000) + tag.count(),
            reverse=True
        )
825812
def arrangeByType(service_list, preferred_types):
    """"""

    def enumerate(elts):
        """Return an iterable that pairs the index of an element with
        that element.

        For Python 2.2 compatibility"""
        return zip(range(len(elts)), elts)

    def bestMatchingService(service):
        """Return the index of the first matching type, or something
        higher if no type matches.

        This provides an ordering in which service elements that
        contain a type that comes earlier in the preferred types list
        come before service elements that come later. If a service
        element has more than one type, the most preferred one wins.
        """
        for i, t in enumerate(preferred_types):
            if preferred_types[i] in service.type_uris:
                return i

        return len(preferred_types)

    # Build a list with the service elements in tuples whose
    # comparison will prefer the one with the best matching service
    prio_services = [(bestMatchingService(s), orig_index, s)
                     for (orig_index, s) in enumerate(service_list)]
    prio_services.sort()

    # Now that the services are sorted by priority, remove the sort
    # keys from the list.
    for i in range(len(prio_services)):
        prio_services[i] = prio_services[i][2]

    return prio_services
575301
def matches(media_type)
      type, subtype, params = parse_media_type(media_type)
      values.select {|v|
        if v == media_type || v == '*/*'
          true
        else
          t, s, p = parse_media_type(v)
          t == type && (s == '*' || s == subtype) && (p == '' || params_match?(params, p))
        end
      }.sort_by {|v|
        # Most specific gets precedence.
        v.length
      }.reverse
    end
728173
def _priority(s):
    """"""
    if type(s) in (list, tuple, set, frozenset):
        return ITERABLE
    if type(s) is dict:
        return DICT
    if issubclass(type(s), type):
        return TYPE
    if hasattr(s, "validate"):
        return VALIDATOR
    if callable(s):
        return CALLABLE
    else:
        return COMPARABLE
602268
public static void sortBySpecificityAndQuality(List<MediaType> mediaTypes) {
        checkNotNull(mediaTypes, "'mediaTypes' must not be null");
        if (mediaTypes.size() > 1) {
            Collections.sort(mediaTypes, Ordering.compound(
                    ImmutableList.of(MediaType.SPECIFICITY_COMPARATOR, MediaType.QUALITY_VALUE_COMPARATOR)));
        }
    }