Adds comparators to a type. They are stored like: Type[@can.setComparisons] = Map({ [type1]: Map({[type2]: {union, different, intersection}}) })  Why do we need the outer object?
960047
function addComparators(type1, type2, comparators) {
	var comparisons = type1[setComparisonsSymbol];
	if (!type1[setComparisonsSymbol]) {
		comparisons = type1[setComparisonsSymbol] = new Map();
	}
	var subMap = comparisons.get(type1);

	if (!subMap) {
		subMap = new Map();
		comparisons.set(type1, subMap);
	}
	var existingComparators = subMap.get(type2);
	if (existingComparators) {
		for (var prop in comparators) {
			if (existingComparators.hasOwnProperty(prop)) {
				console.warn("Overwriting " + type1.name + " " + prop + " " + type2.name + " comparitor");
			}
			existingComparators[prop] = comparators[prop];
		}
	} else {
		subMap.set(type2, comparators);
	}
}
696160
public Comparator<T> thenComparing(final java.util.Comparator<? super T> other) {
            final Comparator<T> me = this;
            return new Comparator<T>() {
                @Override
                public int compare(T o1, T o2) {
                    int ret = (me.compare(o1, o2));
                    return (0 == ret) ? other.compare(o1, o2) : ret;
                }
            };
        }
918353
function Union () {
  debug('defining new union "type"')

  function UnionType (arg, data) {
    if (!(this instanceof UnionType)) {
      return new UnionType(arg, data)
    }
    debug('creating new union instance')
    var store
    if (Buffer.isBuffer(arg)) {
      debug('using passed-in Buffer instance to back the union', arg)
      assert(arg.length >= UnionType.size, 'Buffer instance must be at least '
          + UnionType.size + ' bytes to back this untion type')
      store = arg
      arg = data
    } else {
      debug('creating new Buffer instance to back the union (size: %d)', UnionType.size)
      store = new Buffer(UnionType.size)
    }

    // set the backing Buffer store
    store.type = UnionType
    this['ref.buffer'] = store

    // initialise the union with values supplied
    if (arg) {
      //TODO: Sanity check - e.g. (Object.keys(arg).length == 1)
      for (var key in arg) {
        // hopefully hit the union setters
        this[key] = arg[key]
      }
    }
    UnionType._instanceCreated = true
  }

  // make instances inherit from `proto`
  UnionType.prototype = Object.create(proto, {
    constructor: {
        value: UnionType
      , enumerable: false
      , writable: true
      , configurable: true
    }
  })

  UnionType.defineProperty = defineProperty
  UnionType.toString = toString
  UnionType.fields = {}

  // comply with ref's "type" interface
  UnionType.size = 0
  UnionType.alignment = 0
  UnionType.indirection = 1
  UnionType.get = get
  UnionType.set = set

  // Read the fields list
  var arg = arguments[0]
  if (typeof arg === 'object') {
    Object.keys(arg).forEach(function (name) {
      var type = arg[name];
      UnionType.defineProperty(name, type);
    })
  }

  return UnionType
}
63759
def add(self, type):
        # type: (InternalType) -> None
        
        try:
            if isinstance(type, SetType):
                if EMPTY_SET_TYPE in self.types_hashable:
                    self.types_hashable.remove(EMPTY_SET_TYPE)
            elif isinstance(type, ListType):
                if EMPTY_LIST_TYPE in self.types_hashable:
                    self.types_hashable.remove(EMPTY_LIST_TYPE)
            elif isinstance(type, IteratorType):
                if EMPTY_ITERATOR_TYPE in self.types_hashable:
                    self.types_hashable.remove(EMPTY_ITERATOR_TYPE)
            elif isinstance(type, DictType):
                if EMPTY_DICT_TYPE in self.types_hashable:
                    self.types_hashable.remove(EMPTY_DICT_TYPE)
                for item in self.types_hashable:
                    if isinstance(item, DictType):
                        if item.key_type == type.key_type:
                            item.val_type.merge(type.val_type)
                            return
            self.types_hashable.add(type)

        except (TypeError, AttributeError):
            try:
                if type not in self.types:
                    self.types.append(type)
            except AttributeError:
                if TypeWasIncomparable not in self.types:
                    self.types.append(TypeWasIncomparable)
385384
public static <K extends Comparable< ? super K>,V extends Comparable< ? super V>> List<Entry<K,V>>
            sortKeyValuePairByValue(Map<K,V> map) {
        List<Map.Entry<K,V>> entries = new ArrayList<Map.Entry<K,V>>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {
            @Override
            public int compare(Entry<K,V> o1, Entry<K,V> o2) {
                if (!o1.getValue().equals(o2.getValue())) {
                    return (o1.getValue()).compareTo(o2.getValue());
                }
                return o1.getKey().compareTo(o2.getKey());
            }
        } );
        return entries;
    }
585699
function(Type){
        return Type && canReflect.isConstructorLike(Type) &&
            !set.hasComparisons(Type) &&
            !Type[canSymbol.for("can.SetType")] &&
            Type.prototype.valueOf && Type.prototype.valueOf !== Object.prototype.valueOf;
    }
938282
def _comparator(func):
    
    def comparator_wrapper(self, other):
        try:
            # [PATCH] The code was originally the following:
            #
            #     assert self.enumtype == other.enumtype
            #     result = func(self.index, other.index)
            #
            # which first statement causes an issue when serializing/unserializing object
            # from/to memcached using pylibmc, which built a new instance of the
            # enumeration.  Therefore two items are stated different while semantically
            # the same.
            #
            # These two lines are replaced by the following, which relies on the fact that
            # developers are not likely naming two items of distinct enumerations the same
            # way, and less likely to compare two items of two distinct enumerations.
            #
            # (Daniel CAUNE; daniel.caune@gmail.com; 2012-05-11)
            result = func(self.key, other.key)
        except (AssertionError, AttributeError):
            result = NotImplemented

        return result
    comparator_wrapper.__name__ = func.__name__
    comparator_wrapper.__doc__ = getattr(float, func.__name__).__doc__
    return comparator_wrapper
1371228
@SuppressWarnings("unchecked")
  private Object union(Linker linker, Object a, Object b) {
    if (a instanceof List) {
      return union((List<?>) a, (List<?>) b);
    } else if (a instanceof Map) {
      return union(linker, (Map<ProtoMember, Object>) a, (Map<ProtoMember, Object>) b);
    } else {
      linker.addError("conflicting options: %s, %s", a, b);
      return a; // Just return any placeholder.
    }
  }
1014250
public Object add(Object left, Object right, ParserRuleContext errCtx) {
    if (left == null && right == null) {
      return 0;
    }

    // if either are collections... concatenate them
    if (left instanceof Collection<?> || right instanceof Collection<?>) {
      List<Object> res = newArrayList();
      res.addAll(toCollection(left));
      res.addAll(toCollection(right));
      return res;
    }

    // if either are strings... concatenate them
    if (left instanceof String || right instanceof String) {
      return toString(left).concat(toString(right));
    }

    // if both are maps... concatenate them
    if (left instanceof Map<?, ?> || right instanceof Map<?, ?>) {
      Map<Object, Object> res = newHashMap();
      res.putAll((Map<?, ?>) left);
      res.putAll((Map<?, ?>) right);
      return res;
    }

    try {

      // if either are floating point (double or float) use double
      if (isFloatingPointNumber(left) || isFloatingPointNumber(right)) {
        double l = toDouble(left);
        double r = toDouble(right);
        return new Double(l + r);
      }

      // if either are bigdecimal use that type
      if (left instanceof BigDecimal || right instanceof BigDecimal) {
        BigDecimal l = toBigDecimal(left);
        BigDecimal r = toBigDecimal(right);
        BigDecimal result = l.add(r, getMathContext());
        return narrowBigDecimal(left, right, result);
      }

      // if either are numbers use integers
      if (left instanceof Number || right instanceof Number) {
        BigInteger l = toBigInteger(left);
        BigInteger r = toBigInteger(right);
        BigInteger result = l.add(r);
        return narrowBigInteger(left, right, result);
      }

    }
    catch (java.lang.NumberFormatException nfe) {
    }

    throw new ExecutionException("invalid operands for +", interpreter.getLocation(errCtx));
  }
538702
public static <K, V> TreeMap<K, V> newTreeMap(Map<K, V> map, Comparator<? super K> comparator) {
		final TreeMap<K, V> treeMap = new TreeMap<>(comparator);
		if (false == isEmpty(map)) {
			treeMap.putAll(map);
		}
		return treeMap;
	}
1309642
private <K, V> List<Map.Entry<K, V>> sortedEntryList(Map<K, V> obj) {
        List<Map.Entry<K, V>> entryList = new ArrayList<Map.Entry<K, V>>(obj.entrySet());

        Collections.sort(entryList, new Comparator<Map.Entry<K, V>>() {
            @Override
            @SuppressWarnings({ "unchecked", "rawtypes" })
            public int compare(Entry<K, V> o1, Entry<K, V> o2) {
                K k1 = o1.getKey();
                K k2 = o2.getKey();

                if (k1 instanceof Comparable) {
                    return ((Comparable) k1).compareTo(k2);
                }

                return k1.hashCode() - k2.hashCode();
            }
        });

        return entryList;
    }
1146868
@Override
    public int compareTo(MimeType other) {
        int comp = getType().compareToIgnoreCase(other.getType());
        if (comp != 0) {
            return comp;
        }
        comp = getSubtype().compareToIgnoreCase(other.getSubtype());
        if (comp != 0) {
            return comp;
        }
        comp = getParameters().size() - other.getParameters().size();
        if (comp != 0) {
            return comp;
        }
        TreeSet<String> thisAttributes = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        thisAttributes.addAll(getParameters().keySet());
        TreeSet<String> otherAttributes = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
        otherAttributes.addAll(other.getParameters().keySet());
        Iterator<String> thisAttributesIterator = thisAttributes.iterator();
        Iterator<String> otherAttributesIterator = otherAttributes.iterator();
        while (thisAttributesIterator.hasNext()) {
            String thisAttribute = thisAttributesIterator.next();
            String otherAttribute = otherAttributesIterator.next();
            comp = thisAttribute.compareToIgnoreCase(otherAttribute);
            if (comp != 0) {
                return comp;
            }
            String thisValue = getParameters().get(thisAttribute);
            String otherValue = other.getParameters().get(otherAttribute);
            if (otherValue == null) {
                otherValue = "";
            }
            comp = thisValue.compareTo(otherValue);
            if (comp != 0) {
                return comp;
            }
        }
        return 0;
    }
153966
public static <K, V> Map<K, V> sortByValue(Map<K, V> map, final Comparator<? super V> comparator) {
		return sortByValueInternal(map, new EntryValueComparator<K, V>(comparator));
	}
373951
@PublicEvolving
	public TypeComparator<T> createComparator(int[] logicalKeyFields, boolean[] orders, int logicalFieldOffset, ExecutionConfig config) {

		TypeComparatorBuilder<T> builder = createTypeComparatorBuilder();

		builder.initializeTypeComparatorBuilder(logicalKeyFields.length);

		for (int logicalKeyFieldIndex = 0; logicalKeyFieldIndex < logicalKeyFields.length; logicalKeyFieldIndex++) {
			int logicalKeyField = logicalKeyFields[logicalKeyFieldIndex];
			int logicalField = logicalFieldOffset; // this is the global/logical field number
			boolean comparatorAdded = false;

			for (int localFieldId = 0; localFieldId < this.getArity() && logicalField <= logicalKeyField && !comparatorAdded; localFieldId++) {
				TypeInformation<?> localFieldType = this.getTypeAt(localFieldId);
				
				if (localFieldType instanceof AtomicType && logicalField == logicalKeyField) {
					// we found an atomic key --> create comparator
					builder.addComparatorField(
						localFieldId,
						((AtomicType<?>) localFieldType).createComparator(
							orders[logicalKeyFieldIndex],
							config));

					comparatorAdded = true;
				}
				// must be composite type and check that the logicalKeyField is within the bounds
				// of the composite type's logical fields
				else if (localFieldType instanceof CompositeType &&
					logicalField <= logicalKeyField &&
					logicalKeyField <= logicalField + (localFieldType.getTotalFields() - 1)) {
					// we found a compositeType that is containing the logicalKeyField we are looking for --> create comparator
					builder.addComparatorField(
						localFieldId,
						((CompositeType<?>) localFieldType).createComparator(
							new int[]{logicalKeyField},
							new boolean[]{orders[logicalKeyFieldIndex]},
							logicalField,
							config)
					);

					comparatorAdded = true;
				}

				if (localFieldType instanceof CompositeType) {
					// we need to subtract 1 because we are not accounting for the local field (not accessible for the user)
					logicalField += localFieldType.getTotalFields() - 1;
				}
				
				logicalField++;
			}

			if (!comparatorAdded) {
				throw new IllegalArgumentException("Could not add a comparator for the logical" +
					"key field index " + logicalKeyFieldIndex + ".");
			}
		}

		return builder.createTypeComparator(config);
	}
24948
public static <T> Iterable<T> merge(Comparator<T> comp, Iterable<T>... iterables)
    {
        Iterator[] arr = new Iterator[iterables.length];
        for (int ii=0;ii<arr.length;ii++)
        {
            arr[ii] = iterables[ii].iterator();
        }
        return iterable(merge(comp, arr));
    }
1102502
public static <K, V extends Comparable<V>> Map<K, V>
    sortByValue(Map<K, V> map) {
        return sort(map, comparing(map::get));
    }
1016102
function(options) {
      options || (options = {});
      if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
      var boundComparator = _.bind(this.comparator, this);
      if (this.comparator.length == 1) {
        this.models = this.sortBy(boundComparator);
      } else {
        this.models.sort(boundComparator);
      }
      if (!options.silent) this.trigger('reset', this, options);
      return this;
    }