Sort by label

Will sort descending by the label specified
Use the reverse flag or function for ascending results
343118
function sortByLabel(a, b) {
    if (a.sortval > b.sortval) return -1;
    else if (a.sortval == b.sortval) return 0;
    else return 1;
  }
775192
function label(label) {
    return function(s) {
      var delta = s.length - label.length;
      return strRepeat (' ', Math.floor (delta / 2)) + label +
             strRepeat (' ', Math.ceil (delta / 2));
    };
  }
52552
def filterrific_sorting_link_reverse_order(filterrific, new_sort_key, opts)
      # current sort column, toggle search_direction
      new_sort_direction = 'asc' == opts[:current_sort_direction] ? 'desc' : 'asc'
      new_sorting = safe_join([new_sort_key, new_sort_direction], '_')
      css_classes = safe_join([
        opts[:active_column_class],
        opts[:html_attrs].delete(:class)
      ].compact, ' ')
      new_filterrific_params = filterrific.to_hash
                                          .with_indifferent_access
                                          .merge(opts[:sorting_scope_name] => new_sorting)
      url_for_attrs = opts[:url_for_attrs].merge(:filterrific => new_filterrific_params)
      link_to(
        safe_join([opts[:label], opts[:current_sort_direction_indicator]], ' '),
        url_for(url_for_attrs),
        opts[:html_attrs].reverse_merge(:class => css_classes, :method => :get, :remote => true)
      )
    end
138260
def sort(m, reverse=False):
    """"""
    ty = type(m)
    if ty == matrix:
        m = list(m)
    m = sorted(m, reverse=reverse)
    if ty == matrix:
        m = matrix(m)
    return m
310443
function (sort) {
            var ret = {};
            sort = sort || [];
            for (var i = 0; i < sort.length; i++) {
                var sortElement = sort[i];
                ret[sortElement.field] = sortElement.direction;
            }
            return ret;
        }
664430
def sort(self, column_name=None, reverse=False):
        
        if not column_name and self.options.has_key('sorted_by'):
            column_name = self.options['sorted_by'].keys()[0]
        if column_name not in self.default_columns:
            raise ValueError("%s isn't a column in this table" % column_name)
        index = self.default_columns.index(column_name)
        self.table.sort(key = lambda row: row[index], reverse=reverse)
        self.options['sorted_by'] = {column_name: {'reverse': reverse}}
692111
def _order(self, value, is_reverse=None):
        

        def _dict_parser(dict_doc):
            """ dict ordered by:
            valueType_N -> key_N -> value_N
            """
            result = list()
            for key in dict_doc:
                data = self._order(dict_doc[key])
                res = (data[0], key, data[1])
                result.append(res)
            return tuple(result)

        def _list_parser(list_doc):
            """list will iter members to compare
            """
            result = list()
            for member in list_doc:
                result.append(self._order(member))
            return result

        # (TODO) include more data type
        if value is None or not isinstance(value, (dict,
                                                   list,
                                                   basestring,
                                                   bool,
                                                   float,
                                                   int)):
            # not support/sortable value type
            value = (0, None)

        elif isinstance(value, bool):
            value = (5, value)

        elif isinstance(value, (int, float)):
            value = (1, value)

        elif isinstance(value, basestring):
            value = (2, value)

        elif isinstance(value, dict):
            value = (3, _dict_parser(value))

        elif isinstance(value, list):
            if len(value) == 0:
                # [] less then None
                value = [(-1, [])]
            else:
                value = _list_parser(value)

            if is_reverse is not None:
                # list will firstly compare with other doc by it's smallest
                # or largest member
                value = max(value) if is_reverse else min(value)
            else:
                # if the smallest or largest member is a list
                # then compaer with it's sub-member in list index order
                value = (4, tuple(value))

        return value
73329
public static IntComparator rowComparator(Column<?> column, Sort.Order order) {
        IntComparator rowComparator = column.rowComparator();
        if (order == Sort.Order.DESCEND) {
            return ReversingIntComparator.reverse(rowComparator);
        } else {
            return rowComparator;
        }
    }
1217329
function (f, direction) {

        if (typeof (f) !== 'function') {
            var prop = f;
            // make unary function
            f = function (v1) {

                return v1[prop];
            };
        }
        if (f.length === 1) {
            // f is a unary function mapping a single item to its sort score
            var uf = f;
            f = function (v1, v2) {

                return uf(v1) < uf(v2) ? -1 : uf(v1) > uf(v2) ? 1 : 0;
            };
        }
        if (direction === -1) {
            return function (v1, v2) {

                return -f(v1, v2);
            };
        }
        return f;
    }
1305930
def sort_by(self, attr_or_key, direction='asc'):
        
        # work out the direction
        if direction in ('+', 'asc', gtk.SORT_ASCENDING):
            direction = gtk.SORT_ASCENDING
        elif direction in ('-', 'desc', gtk.SORT_DESCENDING):
            direction = gtk.SORT_DESCENDING
        else:
            raise AttributeError('unrecognised direction')
        if callable(attr_or_key):
            # is a key
            sort_func = self._key_sort_func
        else:
            # it's an attribute
            sort_func = self._attr_sort_func
        self.model.set_default_sort_func(sort_func, attr_or_key)
        self.model.set_sort_column_id(-1, direction)
1270283
function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
            var axis = this.axis,
              transA = axis.transA,
              reversed = axis.reversed,
              staggerLines = axis.staggerLines;

            x = x + labelOptions.x - (tickmarkOffset && horiz ?
              tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
            y = y + this.yOffset - (tickmarkOffset && !horiz ?
              tickmarkOffset * transA * (reversed ? 1 : -1) : 0);

            // Correct for staggered labels
            if (staggerLines) {
                label.line = (index / (step || 1) % staggerLines);
                y += label.line * (axis.labelOffset / staggerLines);
            }

            return {
                x: x,
                y: y
            };
        }
1159759
function ( a, b) {
        if (typeof reverse === 'boolean' && reverse === true) {
            if (a[colindex] < b[colindex]) {
                return 1;
            }
            else if (a[colindex] > b[colindex]) {
                return -1;
            }
            else {
                return 0;
            }
        }
        else {
            if (a[colindex] < b[colindex]) {
                return -1;
            }
            else if (a[colindex] > b[colindex]) {
                return 1;
            }
            else {
                return 0;
            }
        }
    }
532690
function sortResults(val, results) {
  const sortPopularity = (a, b) => {
    if (a.reviews.count < b.reviews.count) {
      return 1;
    } else if (a.reviews.count > b.reviews.count) {
      return -1;
    }
    return 0;
  };

  const sortRating = (a, b) => {
    if (a.reviews.averageRating.value < b.reviews.averageRating.value) {
      return 1;
    } else if (a.reviews.averageRating.value > b.reviews.averageRating.value) {
      return -1;
    }

    return sortPopularity(a, b);
  };

  const sortPrice = (a, b) => {
    if (a.price.value > b.price.value) {
      return 1;
    } else if (a.price.value < b.price.value) {
      return -1;
    }

    return sortRating(a, b);
  };

  const sortNew = (a, b) => {
    if (!a.flags.new && b.flags.new) {
      return 1;
    } else if (a.flags.new && !b.flags.new) {
      return -1;
    }

    return sortRating(a, b);
  };

  switch (val.toLowerCase()) {
    case "popularity-desc":
      return results.slice().sort(sortPopularity);

    case "rating-desc":
      return results.slice().sort(sortRating);

    case "age-asc":
      return results.slice().sort(sortNew);

    case "price-asc":
      return results.slice().sort(sortPrice);

    default:
      return results;
  }
}
298637
function orderBy(array, sortPredicate, reverseOrder) {
  if (!isArrayLike(array)) {
    return array;
  }
  sortPredicate = isArray(sortPredicate) ? sortPredicate : [sortPredicate];
  if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  sortPredicate = sortPredicate.map(function(predicate) {
    var descending = false;
    var get = predicate || value;
    if (isString(predicate)) {
      if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
        descending = predicate.charAt(0) == '-';
        predicate = predicate.substring(1);
      }
      if (predicate === '') {
        // Effectively no predicate was passed so we compare identity
        return reverseComparator(function(a, b) {
          return compare(a, b);
        }, descending);
      }
      get = $parse(predicate);
      if (get.constant) {
        var key = get();
        return reverseComparator(function(a, b) {
          return compare(a[key], b[key]);
        }, descending);
      }
    }
    return reverseComparator(function(a, b) {
      return compare(get(a),get(b));
    }, descending);
  });
  var arrayCopy = [];
  for (var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  return arrayCopy.sort(reverseComparator(comparator, reverseOrder));

  function comparator(o1, o2) {
    for (var i = 0; i < sortPredicate.length; i++) {
      var comp = sortPredicate[i](o1, o2);
      if (comp !== 0) break;
    }
    return comp;
  }
  function reverseComparator(comp, descending) {
    return descending
      ? function(a, b) {return comp(b,a);}
      : comp;
  }
  function compare(v1, v2) {
    var t1 = typeof v1;
    var t2 = typeof v2;
    if (t1 == t2) {
      if (isDate(v1) && isDate(v2)) {
        v1 = v1.valueOf();
        v2 = v2.valueOf();
      }
      if (t1 == "string") {
        v1 = v1.toLowerCase();
        v2 = v2.toLowerCase();
      }
      if (v1 === v2) return 0;
      return v1 < v2 ? -1 : 1;
    } else {
      return t1 < t2 ? -1 : 1;
    }
  }
}
43071
def _apply_sort(cursor, sort_by, sort_direction):
        
        if sort_direction is not None and sort_direction.lower() == "desc":
            sort = pymongo.DESCENDING
        else:
            sort = pymongo.ASCENDING
        return cursor.sort(sort_by, sort)
751218
function sort(children, sortOrder) {
    if (typeof sortOrder === 'function') {
        return children.sort(sortOrder);
    }
    else {
        var isAsc = sortOrder === 'asc';
        return children.sort(function (a, b) {
            var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
            return diff === 0
                ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
                : diff;
        });
    }
}
1020781
def sort_and_print_entries(entries, args):
    """"""

    # Extract the proper number type.
    is_float = args.number_type in ("float", "real", "f", "r")
    signed = args.signed or args.number_type in ("real", "r")
    alg = (
        natsort.ns.FLOAT * is_float
        | natsort.ns.SIGNED * signed
        | natsort.ns.NOEXP * (not args.exp)
        | natsort.ns.PATH * args.paths
        | natsort.ns.LOCALE * args.locale
    )

    # Pre-remove entries that don't pass the filtering criteria
    # Make sure we use the same searching algorithm for filtering
    # as for sorting.
    do_filter = args.filter is not None or args.reverse_filter is not None
    if do_filter or args.exclude:
        inp_options = (
            natsort.ns.FLOAT * is_float
            | natsort.ns.SIGNED * signed
            | natsort.ns.NOEXP * (not args.exp)
        )
        regex = regex_chooser(inp_options)
        if args.filter is not None:
            lows, highs = ([f[0] for f in args.filter], [f[1] for f in args.filter])
            entries = [
                entry
                for entry in entries
                if keep_entry_range(entry, lows, highs, float, regex)
            ]
        if args.reverse_filter is not None:
            lows, highs = (
                [f[0] for f in args.reverse_filter],
                [f[1] for f in args.reverse_filter],
            )
            entries = [
                entry
                for entry in entries
                if not keep_entry_range(entry, lows, highs, float, regex)
            ]
        if args.exclude:
            exclude = set(args.exclude)
            entries = [
                entry
                for entry in entries
                if keep_entry_value(entry, exclude, float, regex)
            ]

    # Print off the sorted results
    for entry in natsort.natsorted(entries, reverse=args.reverse, alg=alg):
        print(entry)