text:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace Microsoft.PythonTools.Analysis.Values {
    /// <summary>
    /// Represents an unordered collection of <see cref="Namespace" /> objects;
    /// in effect, a set of Python types. There are multiple implementing
    /// classes, including <see cref="Namespace" /> itself, to improve memory
    /// usage for small sets.
    ///
    /// <see cref="NamespaceSet" /> does not implement this interface, but
    /// provides factory and extension methods.
    /// </summary>
    internal interface INamespaceSet : IEnumerable<Namespace> {
        INamespaceSet Add(Namespace item, bool canMutate = true);
        INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true);
        INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true);
        INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true);
        INamespaceSet Clone();

        bool Contains(Namespace item);
        bool SetEquals(INamespaceSet other);

        int Count { get; }
        IEqualityComparer<Namespace> Comparer { get; }
    }

    /// <summary>
    /// Provides factory and extension methods for objects implementing
    /// <see cref="INamespaceSet" />.
    /// </summary>
    internal static class NamespaceSet {
        /// <summary>
        /// An empty set that does not combine types. This object is immutable
        /// and can be used without cloning.
        /// </summary>
        public static readonly INamespaceSet Empty = Create();
        /// <summary>
        /// An empty set that combines types with a strength of zero. This
        /// object is immutable and can be used without cloning.
        /// </summary>
        public static readonly INamespaceSet EmptyUnion = CreateUnion(UnionComparer.Instances[0]);

        #region Constructors

        /// <summary>
        /// Returns an empty set that does not combine types. This is exactly
        /// equivalent to accessing <see cref="Empty" />.
        /// </summary>
        public static INamespaceSet Create() {
            return NamespaceSetDetails.NamespaceSetEmptyObject.Instance;
        }

        /// <summary>
        /// Returns a set containing only <paramref name="ns" />. This is
        /// exactly equivalent to casting <paramref name="ns" /> to <see
        /// cref="INamespaceSet" />.
        /// </summary>
        /// <param name="ns">The namespace to contain in the set.</param>
        public static INamespaceSet Create(Namespace ns) {
            return ns;
        }

        /// <summary>
        /// Returns a set containing all the types in <paramref name="ns" />.
        /// This is the usual way of creating a new set from any sequence.
        /// </summary>
        /// <param name="ns">The namespaces to contain in the set.</param>
        public static INamespaceSet Create(IEnumerable<Namespace> ns) {
            // TODO: Replace Trim() call with more efficient enumeration.
            return new NamespaceSetDetails.NamespaceSetManyObject(ns).Trim();
        }

        /// <summary>
        /// Returns a set containing all the types in <paramref name="ns" />
        /// with the specified comparer. This function uses the type of
        /// <paramref name="comparer" /> to determine which factory method
        /// should be used.
        ///
        /// If <paramref name="ns" /> is a set with the same comparer as
        /// <paramref name="comparer"/>, it may be returned without
        /// modification.
        /// </summary>
        /// <param name="ns">The namespaces to contain in the set.</param>
        /// <param name="comparer">The comparer to use for the set.</param>
        /// <exception name="InvalidOperationException"><paramref
        /// name="comparer" /> is not an instance of <see cref="ObjectComparer"
        /// /> or <see cref="UnionComparer" />.</exception>
        public static INamespaceSet Create(IEnumerable<Namespace> ns, IEqualityComparer<Namespace> comparer) {
            var set = ns as INamespaceSet;
            if (set == null) {
                UnionComparer uc;
                if (comparer is ObjectComparer) {
                    return ns == null ? Create() : Create(ns);
                } else if ((uc = comparer as UnionComparer) != null) {
                    return ns == null ? CreateUnion(uc) : CreateUnion(ns, uc);
                }
            } else if (comparer == set.Comparer) {
                return set;
            } else if (comparer != null && comparer.GetType() == set.Comparer.GetType()) {
                return set;
            } else if (comparer is ObjectComparer) {
                return Create(set);
            } else if (comparer is UnionComparer) {
                bool dummy;
                return set.AsUnion((UnionComparer)comparer, out dummy);
            }

            throw new InvalidOperationException(string.Format("cannot use {0} as a comparer", comparer));
        }

        /// <summary>
        /// Returns an empty set that uses a <see cref="UnionComparer" /> with
        /// the specified strength.
        /// </summary>
        /// <param name="strength">The strength to use for the comparer.
        /// </param>
        public static INamespaceSet CreateUnion(int strength) {
            if (strength < 0) {
                strength = 0;
            } else if (strength > UnionComparer.MAX_STRENGTH) {
                strength = UnionComparer.MAX_STRENGTH;
            }
            return NamespaceSetDetails.NamespaceSetEmptyUnion.Instances[strength];
        }

        /// <summary>
        /// Returns an empty set that uses the specified <see
        /// cref="UnionComparer" />.
        /// </summary>
        /// <param name="comparer">The comparer to use for the set.</param>
        public static INamespaceSet CreateUnion(UnionComparer comparer) {
            return NamespaceSetDetails.NamespaceSetEmptyUnion.Instances[comparer.Strength];
        }

        /// <summary>
        /// Returns a set containing only <paramref name="ns" /> that uses the
        /// specified <see cref="UnionComparer" />.
        ///
        /// This is different to casting from <see cref="Namespace" /> to <see
        /// cref="INamespaceSet" />, because the implementation in <see
        /// cref="Namespace" /> always uses <see cref="ObjectComparer" />.
        /// </summary>
        /// <param name="ns">The namespace to contain in the set.</param>
        /// <param name="comparer">The comparer to use for the set.</param>
        public static INamespaceSet CreateUnion(Namespace ns, UnionComparer comparer) {
            return new NamespaceSetDetails.NamespaceSetOneUnion(ns, comparer);
        }

        /// <summary>
        /// Returns a set containing all the types in <paramref name="ns" />
        /// after merging using the specified <see cref="UnionComparer" />. For
        /// large sets, this operation may require significant time and memory.
        /// The returned set is always a copy of the original.
        /// </summary>
        /// <param name="ns">The namespaces to contain in the set.</param>
        /// <param name="comparer">The comparer to use for the set.</param>
        public static INamespaceSet CreateUnion(IEnumerable<Namespace> ns, UnionComparer comparer) {
            bool dummy;
            // TODO: Replace Trim() call with more intelligent enumeration.
            return new NamespaceSetDetails.NamespaceSetManyUnion(ns.UnionIter(comparer, out dummy), comparer).Trim();
        }

        /// <summary>
        /// Returns a set containing all types in all the sets in <paramref
        /// name="sets" />.
        /// </summary>
        /// <param name="sets">The sets to contain in the set.</param>
        /// <param name="canMutate">True if sets in <paramref name="sets"/> may
        /// be modified.</param>
        public static INamespaceSet UnionAll(IEnumerable<INamespaceSet> sets, bool canMutate = true) {
            return Empty.UnionAll(sets, canMutate);
        }

        /// <summary>
        /// Returns a set containing all types in all the sets in <paramref
        /// name="sets" />.
        /// </summary>
        /// <param name="sets">The sets to contain in the set.</param>
        /// <param name="wasChanged">Returns True if the result is not an empty
        /// set.</param>
        /// <param name="canMutate">True if sets in <paramref name="sets"/> may
        /// be modified.</param>
        public static INamespaceSet UnionAll(IEnumerable<INamespaceSet> sets, out bool wasChanged, bool canMutate = true) {
            return Empty.UnionAll(sets, out wasChanged, canMutate);
        }

        #endregion

        #region Extension Methods

        /// <summary>
        /// Returns <paramref name="set"/> with a comparer with increased
        /// strength. If the strength cannot be increased, <paramref
        /// name="set"/> is returned unmodified.
        /// </summary>
        /// <param name="set">The set to increase the strength of.</param>
        public static INamespaceSet AsStrongerUnion(this INamespaceSet set) {
            var comparer = set.Comparer as UnionComparer;
            if (comparer != null) {
                return set.AsUnion(comparer.Strength + 1);
            } else {
                return set.AsUnion(0);
            }
        }

        /// <summary>
        /// Returns <paramref name="set"/> with a comparer with the specified
        /// strength. If the strength does not need to be changed, <paramref
        /// name="set"/> is returned unmodified.
        /// </summary>
        /// <param name="set">The set to convert to a union.</param>
        /// <param name="strength">The strength of the union.</param>
        public static INamespaceSet AsUnion(this INamespaceSet set, int strength) {
            bool dummy;
            return set.AsUnion(strength, out dummy);
        }

        /// <summary>
        /// Returns <paramref name="set"/> with a comparer with the specified
        /// strength. If the strength does not need to be changed, <paramref
        /// name="set"/> is returned unmodified.
        /// </summary>
        /// <param name="set">The set to convert to a union.</param>
        /// <param name="strength">The strength of the union.</param>
        /// <param name="wasChanged">Returns True if the contents of the
        /// returned set are different to <paramref name="set"/>.</param>
        public static INamespaceSet AsUnion(this INamespaceSet set, int strength, out bool wasChanged) {
            if (strength > UnionComparer.MAX_STRENGTH) {
                strength = UnionComparer.MAX_STRENGTH;
            } else if (strength < 0) {
                strength = 0;
            }
            var comparer = UnionComparer.Instances[strength];
            return AsUnion(set, comparer, out wasChanged);
        }

        /// <summary>
        /// Returns <paramref name="set"/> with the specified comparer. If the
        /// comparer does not need to be changed, <paramref name="set"/> is
        /// returned unmodified.
        /// </summary>
        /// <param name="set">The set to convert to a union.</param>
        /// <param name="comparer">The comparer to use for the set.</param>
        /// <param name="wasChanged">Returns True if the contents of the
        /// returned set are different to <paramref name="set"/>.</param>
        public static INamespaceSet AsUnion(this INamespaceSet set, UnionComparer comparer, out bool wasChanged) {
            if ((set is NamespaceSetDetails.NamespaceSetOneUnion ||
                set is NamespaceSetDetails.NamespaceSetTwoUnion ||
                set is NamespaceSetDetails.NamespaceSetEmptyUnion ||
                set is NamespaceSetDetails.NamespaceSetManyUnion) &&
                set.Comparer == comparer) {
                wasChanged = false;
                return set;
            }

            wasChanged = true;

            var ns = set as Namespace;
            if (ns != null) {
                return CreateUnion(ns, comparer);
            }
            var ns1 = set as NamespaceSetDetails.NamespaceSetOneObject;
            if (ns1 != null) {
                return CreateUnion(ns1.Value, comparer);
            }
            var ns2 = set as NamespaceSetDetails.NamespaceSetTwoObject;
            if (ns2 != null) {
                if (comparer.Equals(ns2.Value1, ns2.Value2)) {
                    bool dummy;
                    return new NamespaceSetDetails.NamespaceSetOneUnion(comparer.MergeTypes(ns2.Value1, ns2.Value2, out dummy), comparer);
                } else {
                    return new NamespaceSetDetails.NamespaceSetTwoUnion(ns2.Value1, ns2.Value2, comparer);
                }
            }

            return new NamespaceSetDetails.NamespaceSetManyUnion(set, comparer);
        }

        /// <summary>
        /// Merges the provided sequence using the specified <see
        /// cref="UnionComparer"/>.
        /// </summary>
        internal static IEnumerable<Namespace> UnionIter(this IEnumerable<Namespace> items, UnionComparer comparer, out bool wasChanged) {
            wasChanged = false;

            var asSet = items as INamespaceSet;
            if (asSet != null && asSet.Comparer == comparer) {
                return items;
            }

            var newItems = new List<Namespace>();
            var anyMerged = true;

            while (anyMerged) {
                anyMerged = false;
                var matches = new Dictionary<Namespace, List<Namespace>>(comparer);

                foreach (var ns in items) {
                    List<Namespace> list;
                    if (matches.TryGetValue(ns, out list)) {
                        if (list == null) {
                            matches[ns] = list = new List<Namespace>();
                        }
                        list.Add(ns);
                    } else {
                        matches[ns] = null;
                    }
                }

                newItems.Clear();

                foreach (var keyValue in matches) {
                    var item = keyValue.Key;
                    if (keyValue.Value != null) {
                        foreach (var other in keyValue.Value) {
                            bool merged;
                            item = comparer.MergeTypes(item, other, out merged);
                            if (merged) {
                                anyMerged = true;
                                wasChanged = true;
                            }
                        }
                    }
                    newItems.Add(item);
                }
                items = newItems;
            }

            return items;
        }

        /// <summary>
        /// Removes excess capacity from <paramref name="set"/>.
        /// </summary>
        public static INamespaceSet Trim(this INamespaceSet set) {
            if (set is NamespaceSetDetails.NamespaceSetManyObject) {
                switch (set.Count) {
                    case 0:
                        return Empty;
                    case 1:
                        return set.First();
                    case 2:
                        return new NamespaceSetDetails.NamespaceSetTwoObject(set);
                    default:
                        return set;
                }
            } else if (set is NamespaceSetDetails.NamespaceSetManyUnion) {
                switch (set.Count) {
                    case 0:
                        return NamespaceSetDetails.NamespaceSetEmptyUnion.Instances[((UnionComparer)set.Comparer).Strength];
                    case 1:
                        return new NamespaceSetDetails.NamespaceSetOneUnion(set.First(), (UnionComparer)set.Comparer);
                    case 2: {
                            var tup = NamespaceSetDetails.NamespaceSetTwoUnion.FromEnumerable(set, (UnionComparer)set.Comparer);
                            if (tup == null) {
                                return set;
                            } else if (tup.Item1 == null && tup.Item2 == null) {
                                return NamespaceSetDetails.NamespaceSetEmptyUnion.Instances[((UnionComparer)set.Comparer).Strength];
                            } else if (tup.Item2 == null) {
                                return new NamespaceSetDetails.NamespaceSetOneUnion(tup.Item1, (UnionComparer)set.Comparer);
                            } else {
                                return new NamespaceSetDetails.NamespaceSetTwoUnion(tup.Item1, tup.Item2, (UnionComparer)set.Comparer);
                            }
                        }
                    default:
                        return set;
                }
            } else {
                return set;
            }
        }

        /// <summary>
        /// Merges all the types in <paramref name="sets" /> into this set.
        /// </summary>
        /// <param name="sets">The sets to merge into this set.</param>
        /// <param name="canMutate">True if this set may be modified.</param>
        public static INamespaceSet UnionAll(this INamespaceSet set, IEnumerable<INamespaceSet> sets, bool canMutate = true) {
            bool dummy;
            return set.UnionAll(sets, out dummy, canMutate);
        }

        /// <summary>
        /// Merges all the types in <paramref name="sets" /> into this set.
        /// </summary>
        /// <param name="sets">The sets to merge into this set.</param>
        /// <param name="wasChanged">Returns True if the contents of the
        /// returned set are different to the original set.</param>
        /// <param name="canMutate">True if this set may be modified.</param>
        public static INamespaceSet UnionAll(this INamespaceSet set, IEnumerable<INamespaceSet> sets, out bool wasChanged, bool canMutate = true) {
            bool changed;
            wasChanged = false;
            foreach (var s in sets) {
                var newSet = set.Union(s, out changed, canMutate);
                if (changed) {
                    wasChanged = true;
                }
                set = newSet;
            }
            return set;
        }

        #endregion
    }

    sealed class ObjectComparer : IEqualityComparer<Namespace>, IEqualityComparer<INamespaceSet> {
        public static readonly ObjectComparer Instance = new ObjectComparer();

        public bool Equals(Namespace x, Namespace y) {
            return (x == null) ? (y == null) : x.Equals(y);
        }

        public int GetHashCode(Namespace obj) {
            return (obj == null) ? 0 : obj.GetHashCode();
        }

        public bool Equals(INamespaceSet set1, INamespaceSet set2) {
            if (set1.Comparer == this) {
                return set1.SetEquals(set2);
            } else if (set2.Comparer == this) {
                return set2.SetEquals(set1);
            } else {
                return set1.All(ns => set2.Contains(ns, this)) &&
                    (set2.Comparer == set1.Comparer || set2.All(ns => set1.Contains(ns, this)));
            }
        }

        public int GetHashCode(INamespaceSet obj) {
            return obj.Aggregate(GetHashCode(), (hash, ns) => hash ^ GetHashCode(ns));
        }
    }

    sealed class UnionComparer : IEqualityComparer<Namespace>, IEqualityComparer<INamespaceSet> {
        public const int MAX_STRENGTH = 3;
        public static readonly UnionComparer[] Instances = Enumerable.Range(0, MAX_STRENGTH + 1).Select(i => new UnionComparer(i)).ToArray();

        public readonly int Strength;

        public UnionComparer(int strength = 0) {
            Strength = strength;
        }

        public bool Equals(Namespace x, Namespace y) {
            if (Object.ReferenceEquals(x, y)) {
                return true;
            }
            return (x == null) ? (y == null) : x.UnionEquals(y, Strength);
        }

        public int GetHashCode(Namespace obj) {
            return (obj == null) ? 0 : obj.UnionHashCode(Strength);
        }

        public Namespace MergeTypes(Namespace x, Namespace y, out bool wasChanged) {
            if (Object.ReferenceEquals(x, y)) {
                wasChanged = false;
                return x;
            }
            var z = x.UnionMergeTypes(y, Strength);
            wasChanged = !Object.ReferenceEquals(x, z);
            return z;
        }

        public bool Equals(INamespaceSet set1, INamespaceSet set2) {
            if (set1.Comparer == this) {
                return set1.SetEquals(set2);
            } else if (set2.Comparer == this) {
                return set2.SetEquals(set1);
            } else {
                return set1.All(ns => set2.Contains(ns, this)) &&
                    (set2.Comparer == set1.Comparer || set2.All(ns => set1.Contains(ns, this)));
            }
        }

        public int GetHashCode(INamespaceSet obj) {
            return obj.Aggregate(GetHashCode(), (hash, ns) => hash ^ GetHashCode(ns));
        }
    }

    namespace NamespaceSetDetails {
        sealed class DebugViewProxy {
            [DebuggerBrowsable(DebuggerBrowsableState.Never)]
            public const string DisplayString = "{this}, {Comparer.GetType().Name,nq}";

            public DebugViewProxy(INamespaceSet source) {
                Data = source.ToArray();
                Comparer = source.Comparer;
            }

            [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
            public Namespace[] Data;

            public override string ToString() {
                return ToString(Data);
            }

            public static string ToString(INamespaceSet source) {
                return ToString(source.ToArray());
            }

            public static string ToString(Namespace[] source) {
                var data = source.ToArray();
                if (data.Length == 0) {
                    return "{}";
                } else if (data.Length < 5) {
                    return "{" + string.Join(", ", data.AsEnumerable()) + "}";
                } else {
                    return string.Format("{{Size = {0}}}", data.Length);
                }
            }

            public IEqualityComparer<Namespace> Comparer {
                get;
                private set;
            }

            public int Size {
                get { return Data.Length; }
            }
        }

        [DebuggerDisplay(DebugViewProxy.DisplayString), DebuggerTypeProxy(typeof(DebugViewProxy))]
        sealed class NamespaceSetManyObject : INamespaceSet {
            public readonly HashSet<Namespace> Set;

            public NamespaceSetManyObject(IEnumerable<Namespace> items) {
                Set = new HashSet<Namespace>(items, ObjectComparer.Instance);
            }

            internal NamespaceSetManyObject(NamespaceSetTwoObject firstTwo, Namespace third) {
                Set = new HashSet<Namespace>(ObjectComparer.Instance);
                Set.Add(firstTwo.Value1);
                Set.Add(firstTwo.Value2);
                Set.Add(third);
            }

            public INamespaceSet Add(Namespace item, bool canMutate = true) {
                if (Set.Contains(item)) {
                    return this;
                }
                var set = canMutate ? this : new NamespaceSetManyObject(this.Set);
                set.Set.Add(item);
                return set;
            }

            public INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true) {
                if (Set.Contains(item)) {
                    wasChanged = false;
                    return this;
                }
                var set = canMutate ? this : new NamespaceSetManyObject(this.Set);
                wasChanged = set.Set.Add(item);
                return set;
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true) {
                if (Set.IsSupersetOf(items)) {
                    return this;
                }
                var set = canMutate ? this : new NamespaceSetManyObject(this.Set);
                set.Set.UnionWith(items);
                return set;
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true) {
                if (Set.IsSupersetOf(items)) {
                    wasChanged = false;
                    return this;
                }
                var set = canMutate ? this : new NamespaceSetManyObject(this.Set);
                wasChanged = true;
                set.Set.UnionWith(items);
                return set;
            }

            public INamespaceSet Clone() {
                switch (Set.Count) {
                    case 0:
                        return new NamespaceSetEmptyObject();
                    case 1:
                        return new NamespaceSetOneObject(Set.First());
                    case 2:
                        return new NamespaceSetTwoObject(Set);
                    default:
                        return new NamespaceSetManyObject(Set);
                }
            }

            public bool Contains(Namespace item) {
                return Set.Contains(item);
            }

            public bool SetEquals(INamespaceSet other) {
                if (other == null) {
                    return false;
                }
                foreach (var ns in Set) {
                    if (!other.Contains(ns, Comparer)) {
                        return false;
                    }
                }
                if (other.Comparer != Comparer) {
                    foreach (var ns in Set) {
                        if (!other.Contains(ns, Comparer)) {
                            return false;
                        }
                    }
                }
                return true;
            }

            public int Count {
                get { return Set.Count; }
            }

            public IEnumerator<Namespace> GetEnumerator() {
                return Set.GetEnumerator();
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
                return Set.GetEnumerator();
            }

            public IEqualityComparer<Namespace> Comparer {
                get { return ObjectComparer.Instance; }
            }

            public override string ToString() {
                return DebugViewProxy.ToString(this);
            }
        }

        [DebuggerDisplay(DebugViewProxy.DisplayString), DebuggerTypeProxy(typeof(DebugViewProxy))]
        sealed class NamespaceSetEmptyObject : INamespaceSet {
            public static readonly INamespaceSet Instance = new NamespaceSetEmptyObject();

            public INamespaceSet Add(Namespace item, bool canMutate = true) {
                return item;
            }

            public INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true) {
                wasChanged = true;
                return item;
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true) {
                if (items is NamespaceSetEmptyObject || items is NamespaceSetEmptyUnion) {
                    return this;
                }
                if (items is Namespace || items is NamespaceSetOneObject || items is NamespaceSetTwoObject) {
                    return (INamespaceSet)items;
                }
                return items.Any() ? NamespaceSet.Create(items) : this;
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true) {
                if (items is NamespaceSetEmptyObject || items is NamespaceSetEmptyUnion) {
                    wasChanged = false;
                    return this;
                }
                if (items is Namespace || items is NamespaceSetOneObject || items is NamespaceSetTwoObject) {
                    wasChanged = true;
                    return (INamespaceSet)items;
                }
                wasChanged = items.Any();
                return wasChanged ? NamespaceSet.Create(items) : this;
            }

            public INamespaceSet Clone() {
                return this;
            }

            public bool Contains(Namespace item) {
                return false;
            }

            public bool SetEquals(INamespaceSet other) {
                return other != null && other.Count == 0;
            }

            public int Count {
                get { return 0; }
            }

            public IEnumerator<Namespace> GetEnumerator() {
                yield break;
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
                return GetEnumerator();
            }

            public IEqualityComparer<Namespace> Comparer {
                get { return ObjectComparer.Instance; }
            }

            public override string ToString() {
                return DebugViewProxy.ToString(this);
            }
        }

        [DebuggerDisplay(DebugViewProxy.DisplayString), DebuggerTypeProxy(typeof(DebugViewProxy))]
        sealed class NamespaceSetOneObject : INamespaceSet {
            public readonly Namespace Value;

            public NamespaceSetOneObject(Namespace value) {
                Value = value;
            }

            public INamespaceSet Add(Namespace item, bool canMutate = true) {
                if (ObjectComparer.Instance.Equals(Value, item)) {
                    return this;
                } else {
                    return new NamespaceSetTwoObject(Value, item);
                }
            }

            public INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true) {
                if (ObjectComparer.Instance.Equals(Value, item)) {
                    wasChanged = false;
                    return this;
                } else {
                    wasChanged = true;
                    return new NamespaceSetTwoObject(Value, item);
                }
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true) {
                NamespaceSetOneObject ns1;
                NamespaceSetTwoObject ns2;
                if ((ns1 = items as NamespaceSetOneObject) != null) {
                    return Add(ns1.Value, canMutate);
                } else if ((ns2 = items as NamespaceSetTwoObject) != null) {
                    if (ns2.Contains(Value)) {
                        return ns2;
                    }
                    return new NamespaceSetManyObject(ns2, Value);
                } else {
                    return new NamespaceSetManyObject(items).Add(Value);
                }
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true) {
                NamespaceSetOneObject ns1;
                NamespaceSetTwoObject ns2;
                if ((ns1 = items as NamespaceSetOneObject) != null) {
                    return Add(ns1.Value, out wasChanged, canMutate);
                } else if ((ns2 = items as NamespaceSetTwoObject) != null) {
                    wasChanged = true;
                    if (ns2.Contains(Value)) {
                        return ns2;
                    }
                    return new NamespaceSetManyObject(ns2, Value);
                } else {
                    return new NamespaceSetManyObject(items).Add(Value, out wasChanged);
                }
            }

            public INamespaceSet Clone() {
                return this;
            }

            public bool Contains(Namespace item) {
                return ObjectComparer.Instance.Equals(Value, item);
            }

            public bool SetEquals(INamespaceSet other) {
                Namespace ns;
                NamespaceSetOneObject ns1o;
                NamespaceSetOneUnion ns1u;
                if ((ns = other as Namespace) != null) {
                    return ObjectComparer.Instance.Equals(Value, ns);
                } else if ((ns1o = other as NamespaceSetOneObject) != null) {
                    return ObjectComparer.Instance.Equals(Value, ns1o.Value);
                } else if ((ns1u = other as NamespaceSetOneUnion) != null) {
                    return ObjectComparer.Instance.Equals(Value, ns1u.Value);
                } else if (other != null && other.Count == 1) {
                    return ObjectComparer.Instance.Equals(Value, other.First());
                } else {
                    return false;
                }
            }

            public int Count {
                get { return 1; }
            }

            public IEnumerator<Namespace> GetEnumerator() {
                return new SetOfOneEnumerator<Namespace>(Value);
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
                return GetEnumerator();
            }

            public IEqualityComparer<Namespace> Comparer {
                get { return ObjectComparer.Instance; }
            }

            public override string ToString() {
                return DebugViewProxy.ToString(this);
            }
        }

        [DebuggerDisplay(DebugViewProxy.DisplayString), DebuggerTypeProxy(typeof(DebugViewProxy))]
        sealed class NamespaceSetTwoObject : INamespaceSet {
            public readonly Namespace Value1, Value2;

            public NamespaceSetTwoObject(Namespace value1, Namespace value2) {
                Value1 = value1;
                Value2 = value2;
            }

            public NamespaceSetTwoObject(IEnumerable<Namespace> set) {
                using (var e = set.GetEnumerator()) {
                    if (!e.MoveNext()) {
                        throw new InvalidOperationException("Sequence requires exactly two values");
                    }
                    Value1 = e.Current;
                    if (!e.MoveNext() && !ObjectComparer.Instance.Equals(e.Current, Value1)) {
                        throw new InvalidOperationException("Sequence requires exactly two values");
                    }
                    Value2 = e.Current;
                    if (e.MoveNext()) {
                        throw new InvalidOperationException("Sequence requires exactly two values");
                    }
                }
            }

            public INamespaceSet Add(Namespace item, bool canMutate = true) {
                if (ObjectComparer.Instance.Equals(Value1, item) || ObjectComparer.Instance.Equals(Value2, item)) {
                    return this;
                }
                return new NamespaceSetManyObject(this, item);
            }

            public INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true) {
                if (ObjectComparer.Instance.Equals(Value1, item) || ObjectComparer.Instance.Equals(Value2, item)) {
                    wasChanged = false;
                    return this;
                }
                wasChanged = true;
                return new NamespaceSetManyObject(this, item);
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true) {
                Namespace ns;
                NamespaceSetOneObject ns1;
                if ((ns = items as Namespace) != null) {
                    return Add(ns, canMutate);
                } else if ((ns1 = items as NamespaceSetOneObject) != null) {
                    return Add(ns1.Value, canMutate);
                } else {
                    return new NamespaceSetManyObject(items).Add(Value1).Add(Value2);
                }
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true) {
                Namespace ns;
                NamespaceSetOneObject ns1;
                if ((ns = items as Namespace) != null) {
                    return Add(ns, out wasChanged, canMutate);
                } else if ((ns1 = items as NamespaceSetOneObject) != null) {
                    return Add(ns1.Value, out wasChanged, canMutate);
                } else {
                    bool wasChanged1, wasChanged2;
                    var set = new NamespaceSetManyObject(items).Add(Value1, out wasChanged1).Add(Value2, out wasChanged2);
                    wasChanged = wasChanged1 || wasChanged2;
                    return set;
                }
            }

            public INamespaceSet Clone() {
                return this;
            }

            public bool Contains(Namespace item) {
                return ObjectComparer.Instance.Equals(Value1, item) || ObjectComparer.Instance.Equals(Value2, item);
            }

            public bool SetEquals(INamespaceSet other) {
                var ns2 = other as NamespaceSetTwoObject;
                if (ns2 != null) {
                    return ObjectComparer.Instance.Equals(Value1, ns2.Value1) && ObjectComparer.Instance.Equals(Value2, ns2.Value2) ||
                        ObjectComparer.Instance.Equals(Value1, ns2.Value2) && ObjectComparer.Instance.Equals(Value2, ns2.Value1);
                } else if (other != null && other.Count == 2) {
                    foreach (var ns in other) {
                        if (!ObjectComparer.Instance.Equals(Value1, ns) && !ObjectComparer.Instance.Equals(Value2, ns)) {
                            return false;
                        }
                    }
                    return true;
                } else {
                    return false;
                }
            }

            public int Count {
                get { return 2; }
            }

            public IEnumerator<Namespace> GetEnumerator() {
                yield return Value1;
                yield return Value2;
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
                return GetEnumerator();
            }

            public IEqualityComparer<Namespace> Comparer {
                get { return ObjectComparer.Instance; }
            }

            public override string ToString() {
                return DebugViewProxy.ToString(this);
            }
        }

        [DebuggerDisplay(DebugViewProxy.DisplayString), DebuggerTypeProxy(typeof(DebugViewProxy))]
        sealed class NamespaceSetManyUnion : INamespaceSet {
            public readonly HashSet<Namespace> Set;

            public NamespaceSetManyUnion(IEnumerable<Namespace> items, UnionComparer comparer) {
                Set = new HashSet<Namespace>(items, comparer);
            }

            internal NamespaceSetManyUnion(NamespaceSetTwoUnion firstTwo, Namespace third, UnionComparer comparer, out bool wasChanged) {
                Set = new HashSet<Namespace>(comparer);
                Set.Add(firstTwo.Value1);
                wasChanged = true;
                if (!Set.Add(firstTwo.Value2) || !Set.Add(third)) {
                    Set.Clear();
                    Set.UnionWith(firstTwo.Concat(third).UnionIter(comparer, out wasChanged));
                }
            }

            private NamespaceSetManyUnion(HashSet<Namespace> set) {
                Set = set;
            }

            public INamespaceSet Add(Namespace item, bool canMutate = true) {
                bool dummy;
                return Add(item, out dummy, canMutate);
            }

            public INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true) {
                var set = Set;
                if (canMutate) {
                    if (set.Add(item)) {
                        wasChanged = true;
                        return this;
                    }
                } else if (!set.Contains(item)) {
                    set = new HashSet<Namespace>(set, set.Comparer);
                    wasChanged = set.Add(item);
                    return wasChanged ? new NamespaceSetManyUnion(set) : this;
                } else {
                    set = new HashSet<Namespace>(set, set.Comparer);
                }

                var cmp = Comparer;
                var newItem = item;
                bool newItemAlreadyInSet = false;
                foreach (var ns in Set) {
                    if (cmp.Equals(ns, newItem)) {
                        bool changed = false;
                        newItem = cmp.MergeTypes(ns, newItem, out changed);
                        newItemAlreadyInSet |= !changed;
                    }
                }
                if (!newItemAlreadyInSet) {
                    wasChanged = (set.RemoveWhere(ns => cmp.Equals(ns, newItem)) > 0);
                    wasChanged |= set.Add(newItem);
                } else {
                    wasChanged = (set.RemoveWhere(ns => !Object.ReferenceEquals(ns, newItem) && cmp.Equals(ns, newItem)) > 0);
                }

                return (canMutate | !wasChanged) ? this : new NamespaceSetManyUnion(set);
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true) {
                bool anyAdded = false;
                var cmp = Comparer;
                var set = canMutate ? Set : new HashSet<Namespace>(Set, Set.Comparer);
                foreach (var item in items) {
                    if (set.Add(item)) {
                        anyAdded = true;
                    } else {
                        bool dummy;
                        var newItem = item;
                        foreach (var ns in set) {
                            if (Object.ReferenceEquals(ns, newItem)) {
                                return this;
                            }
                            if (cmp.Equals(ns, newItem)) {
                                newItem = cmp.MergeTypes(ns, newItem, out dummy);
                            }
                        }
                        set.RemoveWhere(ns => cmp.Equals(ns, newItem));
                        set.Add(newItem);
                    }
                }
                return (canMutate | !anyAdded) ? this : new NamespaceSetManyUnion(set);
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true) {
                bool anyAdded = false;
                var cmp = Comparer;
                var set = canMutate ? Set : new HashSet<Namespace>(Set, Set.Comparer);
                wasChanged = false;
                foreach (var item in items) {
                    if (set.Add(item)) {
                        anyAdded = true;
                    } else {
                        bool changed = false;
                        var newItem = item;
                        foreach (var ns in set) {
                            if (Object.ReferenceEquals(ns, newItem)) {
                                return this;
                            }
                            if (cmp.Equals(ns, newItem)) {
                                newItem = cmp.MergeTypes(ns, newItem, out changed);
                            }
                        }
                        int removed = set.RemoveWhere(ns => cmp.Equals(ns, newItem));
                        set.Add(newItem);
                        anyAdded |= (removed > 1) | changed;
                    }
                }
                wasChanged = anyAdded;
                return (canMutate | !anyAdded) ? this : new NamespaceSetManyUnion(set);
            }

            public INamespaceSet Clone() {
                switch (Set.Count) {
                    case 0:
                        return NamespaceSetEmptyUnion.Instances[Comparer.Strength];
                    case 1:
                        return new NamespaceSetOneUnion(Set.First(), Comparer);
                    case 2: {
                            var tup = NamespaceSetTwoUnion.FromEnumerable(Set, Comparer);
                            if (tup == null) {
                                return new NamespaceSetManyUnion(Set, Comparer);
                            } else if (tup.Item1 == null && tup.Item2 == null) {
                                return NamespaceSetEmptyUnion.Instances[Comparer.Strength];
                            } else if (tup.Item2 == null) {
                                return new NamespaceSetOneUnion(tup.Item1, Comparer);
                            } else {
                                return new NamespaceSetTwoUnion(tup.Item1, tup.Item2, Comparer);
                            }
                        }
                    default:
                        return new NamespaceSetManyUnion(Set, Comparer);
                }
            }

            public bool Contains(Namespace item) {
                return Set.Contains(item);
            }

            public bool SetEquals(INamespaceSet other) {
                if (other == null) {
                    return false;
                }
                foreach (var ns in Set) {
                    if (!other.Contains(ns, Comparer)) {
                        return false;
                    }
                }
                if (other.Comparer != Comparer) {
                    foreach (var ns in Set) {
                        if (!other.Contains(ns, Comparer)) {
                            return false;
                        }
                    }
                }
                return true;
            }

            public int Count {
                get { return Set.Count; }
            }

            public IEnumerator<Namespace> GetEnumerator() {
                return Set.GetEnumerator();
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
                return Set.GetEnumerator();
            }

            internal UnionComparer Comparer {
                get { return (UnionComparer)Set.Comparer; }
            }

            IEqualityComparer<Namespace> INamespaceSet.Comparer {
                get { return Set.Comparer; }
            }

            public override string ToString() {
                return DebugViewProxy.ToString(this);
            }
        }

        [DebuggerDisplay(DebugViewProxy.DisplayString), DebuggerTypeProxy(typeof(DebugViewProxy))]
        sealed class NamespaceSetEmptyUnion : INamespaceSet {
            public static readonly INamespaceSet[] Instances = UnionComparer.Instances.Select(cmp => new NamespaceSetEmptyUnion(cmp)).ToArray();

            private readonly UnionComparer _comparer;

            public NamespaceSetEmptyUnion(UnionComparer comparer) {
                _comparer = comparer;
            }

            public INamespaceSet Add(Namespace item, bool canMutate = true) {
                return new NamespaceSetOneUnion(item, Comparer);
            }

            public INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true) {
                wasChanged = true;
                return new NamespaceSetOneUnion(item, Comparer);
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true) {
                if (items is NamespaceSetOneUnion || items is NamespaceSetTwoUnion || items is NamespaceSetEmptyUnion) {
                    return (INamespaceSet)items;
                }
                return items.Any() ? NamespaceSet.CreateUnion(items, Comparer) : this;
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true) {
                if (items is NamespaceSetEmptyObject || items is NamespaceSetEmptyUnion) {
                    wasChanged = false;
                    return this;
                }
                if (items is NamespaceSetOneUnion || items is NamespaceSetTwoUnion) {
                    wasChanged = true;
                    return (INamespaceSet)items;
                }
                wasChanged = items.Any();
                return wasChanged ? NamespaceSet.CreateUnion(items, Comparer) : this;
            }

            public INamespaceSet Clone() {
                return this;
            }

            public bool Contains(Namespace item) {
                return false;
            }

            public bool SetEquals(INamespaceSet other) {
                return other != null && other.Count == 0;
            }

            public int Count {
                get { return 0; }
            }

            public IEnumerator<Namespace> GetEnumerator() {
                yield break;
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
                return GetEnumerator();
            }

            internal UnionComparer Comparer {
                get { return _comparer; }
            }

            IEqualityComparer<Namespace> INamespaceSet.Comparer {
                get { return ((NamespaceSetEmptyUnion)this).Comparer; }
            }

            public override string ToString() {
                return DebugViewProxy.ToString(this);
            }
        }

        [DebuggerDisplay(DebugViewProxy.DisplayString), DebuggerTypeProxy(typeof(DebugViewProxy))]
        sealed class NamespaceSetOneUnion : INamespaceSet {
            public readonly Namespace Value;
            private readonly UnionComparer _comparer;

            public NamespaceSetOneUnion(Namespace value, UnionComparer comparer) {
                Value = value;
                _comparer = comparer;
            }

            public INamespaceSet Add(Namespace item, bool canMutate = true) {
                if (Object.ReferenceEquals(Value, item)) {
                    return this;
                } else if (Comparer.Equals(Value, item)) {
                    bool wasChanged;
                    var newItem = Comparer.MergeTypes(Value, item, out wasChanged);
                    return wasChanged ? new NamespaceSetOneUnion(newItem, Comparer) : this;
                } else {
                    return new NamespaceSetTwoUnion(Value, item, Comparer);
                }
            }

            public INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true) {
                if (Object.ReferenceEquals(Value, item)) {
                    wasChanged = false;
                    return this;
                } else if (Comparer.Equals(Value, item)) {
                    var newItem = Comparer.MergeTypes(Value, item, out wasChanged);
                    return wasChanged ? new NamespaceSetOneUnion(newItem, Comparer) : this;
                } else {
                    wasChanged = true;
                    return new NamespaceSetTwoUnion(Value, item, Comparer);
                }
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true) {
                Namespace ns;
                NamespaceSetOneUnion ns1;
                NamespaceSetOneObject nsO1;
                NamespaceSetTwoUnion ns2;
                if ((ns = items as Namespace) != null) {
                    return Add(ns, canMutate);
                } else if ((ns1 = items as NamespaceSetOneUnion) != null) {
                    return Add(ns1.Value, canMutate);
                } else if ((nsO1 = items as NamespaceSetOneObject) != null) {
                    return Add(nsO1.Value, canMutate);
                } else if ((ns2 = items as NamespaceSetTwoUnion) != null && ns2.Comparer == Comparer) {
                    return ns2.Add(Value, false);
                } else {
                    return new NamespaceSetManyUnion(items, Comparer).Add(Value).Trim();
                }
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true) {
                Namespace ns;
                NamespaceSetOneUnion ns1;
                NamespaceSetOneObject nsO1;
                NamespaceSetTwoUnion ns2;
                if ((ns = items as Namespace) != null) {
                    return Add(ns, out wasChanged, canMutate);
                } else if ((ns1 = items as NamespaceSetOneUnion) != null) {
                    return Add(ns1.Value, out wasChanged, canMutate);
                } else if ((nsO1 = items as NamespaceSetOneObject) != null) {
                    return Add(nsO1.Value, out wasChanged, canMutate);
                } else if ((ns2 = items as NamespaceSetTwoUnion) != null && ns2.Comparer == Comparer) {
                    return ns2.Add(Value, out wasChanged, false);
                } else {
                    return new NamespaceSetManyUnion(Value, Comparer).Union(items, out wasChanged).Trim();
                }
            }

            public INamespaceSet Clone() {
                return this;
            }

            public bool Contains(Namespace item) {
                return Comparer.Equals(Value, item);
            }

            public bool SetEquals(INamespaceSet other) {
                var ns1 = other as NamespaceSetOneUnion;
                if (ns1 != null) {
                    return Comparer.Equals(Value, ns1.Value);
                } else if (other == null) {
                    return false;
                } else if (other.Count == 1) {
                    return Comparer.Equals(Value, other.First());
                } else {
                    return other.All(ns => Comparer.Equals(ns, Value));
                }
            }

            public int Count {
                get { return 1; }
            }

            public IEnumerator<Namespace> GetEnumerator() {
                return new SetOfOneEnumerator<Namespace>(Value);
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
                return GetEnumerator();
            }

            internal UnionComparer Comparer {
                get { return _comparer; }
            }

            IEqualityComparer<Namespace> INamespaceSet.Comparer {
                get { return ((NamespaceSetOneUnion)this).Comparer; }
            }

            public override string ToString() {
                return DebugViewProxy.ToString(this);
            }
        }

        [DebuggerDisplay(DebugViewProxy.DisplayString), DebuggerTypeProxy(typeof(DebugViewProxy))]
        sealed class NamespaceSetTwoUnion : INamespaceSet {
            public readonly Namespace Value1, Value2;
            private readonly UnionComparer _comparer;

            public NamespaceSetTwoUnion(Namespace value1, Namespace value2, UnionComparer comparer) {
                Debug.Assert(!comparer.Equals(value1, value2));
                Value1 = value1;
                Value2 = value2;
                _comparer = comparer;
            }

            internal static Tuple<Namespace, Namespace> FromEnumerable(IEnumerable<Namespace> set, UnionComparer comparer) {
                using (var e = set.GetEnumerator()) {
                    if (!e.MoveNext()) {
                        return new Tuple<Namespace, Namespace>(null, null);
                    }
                    var value1 = e.Current;
                    if (!e.MoveNext()) {
                        return new Tuple<Namespace, Namespace>(value1, null);
                    }
                    var value2 = e.Current;
                    if (comparer.Equals(e.Current, value1)) {
                        bool dummy;
                        return new Tuple<Namespace, Namespace>(comparer.MergeTypes(value1, value2, out dummy), null);
                    }
                    if (e.MoveNext()) {
                        return null;
                    }
                    return new Tuple<Namespace, Namespace>(value1, value2);
                }
            }

            public NamespaceSetTwoUnion(IEnumerable<Namespace> set, UnionComparer comparer) {
                _comparer = comparer;
                var tup = FromEnumerable(set, comparer);
                if (tup == null || tup.Item2 == null) {
                    throw new InvalidOperationException("Sequence requires exactly two values");
                }
                Value1 = tup.Item1;
                Value2 = tup.Item2;
            }

            public INamespaceSet Add(Namespace item, bool canMutate = true) {
                bool dummy;
                return Add(item, out dummy, canMutate);
            }

            public INamespaceSet Add(Namespace item, out bool wasChanged, bool canMutate = true) {
                bool dummy;
                if (Object.ReferenceEquals(Value1, item) || Object.ReferenceEquals(Value2, item)) {
                    wasChanged = false;
                    return this;
                } else if (Comparer.Equals(Value1, item)) {
                    var newValue = Comparer.MergeTypes(Value1, item, out wasChanged);
                    if (!wasChanged) {
                        return this;
                    }
                    if (Comparer.Equals(Value2, newValue)) {
                        return new NamespaceSetOneUnion(Comparer.MergeTypes(Value2, newValue, out dummy), Comparer);
                    } else {
                        return new NamespaceSetTwoUnion(newValue, Value2, Comparer);
                    }
                } else if (Comparer.Equals(Value2, item)) {
                    var newValue = Comparer.MergeTypes(Value2, item, out wasChanged);
                    if (!wasChanged) {
                        return this;
                    }
                    if (Comparer.Equals(Value1, newValue)) {
                        return new NamespaceSetOneUnion(Comparer.MergeTypes(Value1, newValue, out dummy), Comparer);
                    } else {
                        return new NamespaceSetTwoUnion(Value1, newValue, Comparer);
                    }
                }
                wasChanged = true;
                return new NamespaceSetManyUnion(this, item, Comparer, out dummy);
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, bool canMutate = true) {
                Namespace ns;
                NamespaceSetOneObject ns1o;
                NamespaceSetOneUnion ns1u;
                if ((ns = items as Namespace) != null) {
                    return Add(ns, canMutate);
                } else if ((ns1o = items as NamespaceSetOneObject) != null) {
                    return Add(ns1o.Value, canMutate);
                } else if ((ns1u = items as NamespaceSetOneUnion) != null) {
                    return Add(ns1u.Value, canMutate);
                } else {
                    return new NamespaceSetManyUnion(this, Comparer).Union(items);
                }
            }

            public INamespaceSet Union(IEnumerable<Namespace> items, out bool wasChanged, bool canMutate = true) {
                Namespace ns;
                NamespaceSetOneObject ns1o;
                NamespaceSetOneUnion ns1u;
                if ((ns = items as Namespace) != null) {
                    return Add(ns, out wasChanged, canMutate);
                } else if ((ns1o = items as NamespaceSetOneObject) != null) {
                    return Add(ns1o.Value, out wasChanged, canMutate);
                } else if ((ns1u = items as NamespaceSetOneUnion) != null) {
                    return Add(ns1u.Value, out wasChanged, canMutate);
                } else {
                    return new NamespaceSetManyUnion(this, Comparer).Union(items, out wasChanged);
                }
            }

            public INamespaceSet Clone() {
                return this;
            }

            public bool Contains(Namespace item) {
                return Comparer.Equals(Value1, item) || Comparer.Equals(Value2, item);
            }

            public bool SetEquals(INamespaceSet other) {
                var ns2 = other as NamespaceSetTwoUnion;
                if (ns2 != null) {
                    return Comparer.Equals(Value1, ns2.Value1) && Comparer.Equals(Value2, ns2.Value2) ||
                        Comparer.Equals(Value1, ns2.Value2) && Comparer.Equals(Value2, ns2.Value1);
                } else if (other != null) {
                    return other.All(ns => Comparer.Equals(Value1) || Comparer.Equals(Value2));
                } else {
                    return false;
                }
            }

            public int Count {
                get { return 2; }
            }

            public IEnumerator<Namespace> GetEnumerator() {
                yield return Value1;
                yield return Value2;
            }

            System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() {
                return GetEnumerator();
            }

            internal UnionComparer Comparer {
                get { return _comparer; }
            }

            IEqualityComparer<Namespace> INamespaceSet.Comparer {
                get { return ((NamespaceSetTwoUnion)this).Comparer; }
            }

            public override string ToString() {
                return DebugViewProxy.ToString(this);
            }
        }

    }

}


text:
Taxia
   A legitimate taxi always has a meter and two-way radio inside. Make sure these instruments are in the taxi before you get in and feel free to wave the cab by if you don't see them. A taxi may not use a meter and still be safe, but one without radio calls for alarm. Every taxi needs communicate with a base - without a real radio, it may not be a real cab. Also, sharing a cab with strangers might seem like a safe idea and a good way to save money, but it's a scam in some places.

redpajama_set_name: RedPajamaGithub


text:
extern crate ansi_term;
extern crate clap;
extern crate regex;
extern crate walkdir;

use std::io;
use std::io::Write;
use std::process;

use ansi_term::Colour::Blue;
use clap::{App, AppSettings, Arg};
use regex::Regex;

use walkdir::{DirEntry, WalkDir};

use std::env;
use std::path::PathBuf;

fn is_hidden(entry: &DirEntry) -> bool {
    entry
        .file_name()
        .to_str()
        .map(|s| s.starts_with("."))
        .unwrap_or(false)
}

fn find<T>(
    rgx: Regex,
    dirs: T,
    ignore_hidden: bool,
    replacement: &Option<String>,
) -> Option<io::Error>
where
    T: IntoIterator<Item = PathBuf>,
{
    for dir in dirs {
        let wkd: Box<Iterator<Item = walkdir::Result<DirEntry>>> = if ignore_hidden {
            Box::new(
                WalkDir::new(dir)
                    .into_iter()
                    .filter_entry(|d| !is_hidden(d)),
            )
        } else {
            Box::new(WalkDir::new(dir).into_iter())
        };

        for file in wkd {
            let entry = match file {
                Ok(e) => e,
                Err(err) => {
                    let write_error = writeln!(&mut io::stderr(), "{}", err);
                    if let Err(e) = write_error {
                        return Some(e);
                    }

                    continue;
                }
            };

            // paths are ascii or utf-8 so should always be valid unicode
            // the edge case is super rare so just ignore it
            let s = &entry.path().to_string_lossy();
            if rgx.is_match(s) {
                let write_error = writeln!(
                    &mut io::stdout(),
                    "{}",
                    match replacement {
                        Some(repl) => rgx.replace_all(s, repl.as_str()).to_owned(),
                        None => s.to_owned(),
                    }
                );

                if let Err(e) = write_error {
                    return Some(e);
                }
            }
        }
    }

    None
}

fn main() {
    let matches = App::new("fnd")
        .version("0.3.1")
        .author("Mathew Robinson <mrobinson@praelatus.io>")
        .about(
            "
Find files by regex.

Copyright (C) 2016 Mathew Robinson <mrobinson@praelatus.io>

This program is free software: you can redistribute it and/or modify
it under the terms of the Apache Version 2.0 License

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

You should have recieved a copy of the license with this software if
not you can view it here: https://www.apache.org/licenses/LICENSE-2.0",
        )
        .setting(AppSettings::TrailingVarArg)
        .arg(Arg::with_name("color").long("color").short("c").help(
            "When specified will highlight matches with ansi \
             term color codes. Note that for large regexes or \
             regexes which match a large portion of text this \
             can negatively affect performance.",
        ))
        .arg(
            Arg::with_name("all")
                .long("all")
                .short("a")
                .help("When specified recurse into hidden directories."),
        )
        .arg(
            Arg::with_name("REGEX")
                .required(true)
                .index(1)
                .help("The REGEX to search for, defaults to fuzzy finding"),
        )
        .arg(
            Arg::with_name("DIRS")
                .multiple(true)
                .help("Where to search for SEARCH")
                .default_value("."),
        )
        .get_matches();

    let search = matches.value_of("REGEX").unwrap();
    let dirs = matches.values_of("DIRS").unwrap().map(|x| {
        if x == "." {
            return env::current_dir().unwrap().to_path_buf();
        }

        PathBuf::from(x)
    });

    let re = format!("(?P<search>{})", search);
    let rgx = Regex::new(&re).unwrap();
    let painter;
    let replacement = if matches.is_present("color") {
        painter = Blue.paint("$search");
        Some(format!("{}", painter))
    } else {
        None
    };

    if let Some(ref err) = find(rgx, dirs, !matches.is_present("all"), &replacement) {
        if err.kind() == io::ErrorKind::BrokenPipe {
            process::exit(0)
        } else {
            println!("ERROR: {}", err);
            process::exit(1)
        }
    }
}


text:
package uk.co.ribot.androidboilerplate.util;

/**
 * Robolectric default config properties
 */
public class DefaultConfig {

    //The api level that Roboelectric will use to run the unit tests
    public static final int EMULATE_SDK = 23;
}


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var fileTypeFilter_pipe_1 = require('./fileTypeFilter.pipe');
var fileNameFilter_pipe_1 = require('./fileNameFilter.pipe');
var DatasetViewerComponent = (function () {
    function DatasetViewerComponent() {
        this.geography = Array();
        this._selection = 'All';
        this.bObj = '';
    }
    DatasetViewerComponent.prototype.fileSelection = function (s) {
        this._selection = s;
        this.bObj = s;
    };
    DatasetViewerComponent.prototype.onDownloadClick = function (file) {
        console.log(file.Link);
        window.open(file.Link);
    };
    DatasetViewerComponent = __decorate([
        core_1.Component({
            selector: 'dataset-viewer-component',
            styleUrls: ['./warehouse/warehouse.css'],
            templateUrl: './warehouse/warehouse-viewer.html',
            inputs: ['geography', 'searchInitiated'],
            pipes: [fileNameFilter_pipe_1.FileNamePipe, fileTypeFilter_pipe_1.FileTypePipe]
        }),
        __metadata('design:paramtypes', [])
    ], DatasetViewerComponent);
    return DatasetViewerComponent;
}());
exports.DatasetViewerComponent = DatasetViewerComponent;
//# sourceMappingURL=dataset-viewer.component.js.map


text:
package life.catalogue.api.model;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import life.catalogue.api.vocab.Issue;
import org.apache.commons.text.StringEscapeUtils;
import org.gbif.dwc.terms.Term;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;
import java.io.Serializable;
import java.net.URI;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.*;
import java.util.regex.Pattern;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * A verbatim record that offers basic value cleaning and unescaping of common character entities
 * on read methods without altering the underlying original verbatim data.
 *

 * It also strips simple xml/html tags without attributes such as  or
 *

 * When a value is altered during unescaping the record keeps track that it had been unescaped.
 *

 * The following escaped character formats are recognized:
 * 1) html entities
 * named &
 * hex &
 * decimal &
 * 2) Hexadecimal and octal escapes as used in Java, CSS & ECMA Javascript:
 * Hexadecimal unicode escapes started by  "\\u": \\u00A9
 * Unicode code point escapes indicated by "\\u{}": \\u{2F80}
 * 3) Unicode char escaping using brackets:
 */
public class VerbatimRecord implements DSID<Integer>, IssueContainer, Serializable {
  private static final Logger LOG = LoggerFactory.getLogger(VerbatimRecord.class);
  private static final Pattern REMOVE_TAGS = Pattern.compile("</? *[a-z][a-z1-5]{0,5} *>", Pattern.CASE_INSENSITIVE);
  private static final Pattern ECMA_UNICODE = Pattern.compile("\\\\u\\{([0-9a-f]{4})}", Pattern.CASE_INSENSITIVE);
  private static final Pattern ANGLE_UNICODE = Pattern.compile("", Pattern.CASE_INSENSITIVE);

  private Integer id;
  private Integer datasetKey;
  // instance hash created on load to see if the instance has been changed
  private int _hashKeyOnLoad = -1;

  private long line;
  private String file;
  private Term type;
  private Map<Term, String> terms = new HashMap<>();
  private Set<Issue> issues = EnumSet.noneOf(Issue.class);

  public VerbatimRecord() {
  }

  public VerbatimRecord(VerbatimRecord v) {
    this(v.datasetKey, v.line, v.file, v.type);
  }

  public VerbatimRecord(long line, String file, Term type) {
    this.line = line;
    this.file = file;
    this.type = type;
  }

  public VerbatimRecord(Integer datasetKey, long line, String file, Term type) {
    this(line, file, type);
    this.datasetKey = datasetKey;
  }

  public Integer getId() {
    return id;
  }

  public void setId(Integer id) {
    this.id = id;
  }

  public Integer getDatasetKey() {
    return datasetKey;
  }

  public void setDatasetKey(Integer datasetKey) {
    this.datasetKey = datasetKey;
  }

  /**
   * @return line number this record represents in the underlying source file
   */
  public long getLine() {
    return line;
  }

  public void setLine(long line) {
    this.line = line;
  }

  public void setFile(String file) {
    this.file = file;
  }

  public String getFile() {
    return file;
  }

  public Term getType() {
    return type;
  }

  public void setType(Term type) {
    this.type = type;
  }

  public Map<Term, String> getTerms() {
    return terms;
  }

  public void setTerms(Map<Term, String> terms) {
    this.terms = terms;
  }

  @Override
  public Set<Issue> getIssues() {
    return issues;
  }

  @Override
  public void setIssues(Set<Issue> issues) {
    this.issues = issues;
  }

  @Override
  public void addIssue(Issue issue) {
    issues.add(issue);
  }

  public void addIssues(Issue... issues) {
    addIssues(Arrays.asList(issues));
  }

  public void addIssues(Collection<Issue> issues) {
    this.issues.addAll(issues);
  }

  @Override
  public boolean removeIssue(Issue issue) {
    return issues.remove(issue);
  }

  @Override
  public boolean hasIssue(Issue issue) {
    return issues.contains(issue);
  }

  private String unescape(String x) {
    if (Strings.isNullOrEmpty(x)) {
      return null;
    }
    try {
      String unescaped = ECMA_UNICODE.matcher(x).replaceAll("\\\\u$1");
      unescaped = ANGLE_UNICODE.matcher(unescaped).replaceAll("\\\\u$1");
      unescaped = StringEscapeUtils.unescapeEcmaScript(StringEscapeUtils.unescapeHtml4(unescaped));
      unescaped = REMOVE_TAGS.matcher(unescaped).replaceAll("");
      if (!x.equals(unescaped)) {
        issues.add(Issue.ESCAPED_CHARACTERS);
      }
      return unescaped;
    } catch (RuntimeException e) {
      LOG.debug("Failed to unescape: {}", x, e);
      return x;
    }
  }

  /**
   * @return true if a term exists and is not null or an empty string
   */
  public boolean hasTerm(Term term) {
    checkNotNull(term, "term can't be null");
    return terms.get(term) != null;
  }

  /**
   * @return true if at least one term exists and is not null or an empty string
   */
  public boolean hasAny(Term... terms) {
    for (Term t : terms) {
      if (hasTerm(t)) {
        return true;
      }
    }
    return false;
  }

  /**
   * @return the raw value without any unescaping
   */
  public String getRaw(Term term) {
    checkNotNull(term, "term can't be null");
    return terms.get(term);
  }

  /**
   * @return the potentially unescaped value
   */
  public String get(Term term) {
    checkNotNull(term, "term can't be null");
    String val = terms.get(term);
    if (val != null) {
      return unescape(val);
    }
    return null;
  }

  public String getOrDefault(Term term, String defaultValue) {
    String val = get(term);
    return val == null ? defaultValue : val;
  }

  public int size() {
    return terms.size();
  }

  @JsonIgnore
  public boolean isEmpty() {
    return terms.isEmpty();
  }

  public Set<Term> terms() {
    return terms.keySet();
  }

  public void put(Term term, String value) {
    checkNotNull(term, "term can't be null");
    if (value == null) {
      terms.remove(term);
    } else {
      terms.put(term, value);
    }
  }

  /**
   * @return a URI based on the raw value without applying any unescaping or null if an invalid URI
   */
  public URI getURI(Term term) {
    checkNotNull(term, "term can't be null");
    String val = terms.get(term);
    if (val != null) {
      try {
        return URI.create(val);
      } catch (IllegalArgumentException e) {
        LOG.debug("Invalid URI: {}", val);
      }
    }
    return null;
  }

  /**
   * Returns a parsed integer for a term value, adding the invalidIssue to the verbatim record issues
   * if the value cannot be parsed, returning null in that case.
   */
  public Integer getInt(Term term, Issue invalidIssue) {
    try {
      return getInt(term);
    } catch (NumberFormatException e) {
      issues.add(invalidIssue);
      return null;
    }
  }

  /**
   * Returns a parsed integer for a term value, throwing NumberFormatException if the value cannot be parsed.
   */
  public Integer getInt(Term term) throws NumberFormatException {
    checkNotNull(term, "term can't be null");
    String val = get(term);
    if (val != null) {
      return Integer.valueOf(val);
    }
    return null;
  }

  /**
   * Returns a parsed date for a term value, throwing DateTimeParseException if the value cannot be parsed.
   */
  public LocalDate getDate(Term term) throws DateTimeParseException {
    checkNotNull(term, "term can't be null");
    String val = get(term);
    if (val != null) {
      return LocalDate.parse(val);
    }
    return null;
  }

  /**
   * Get the first non blank term for a list of terms.
   *
   * @param terms list to try
   */
  @Nullable
  public String getFirst(Term... terms) {
    for (Term t : terms) {
      String val = get(t);
      if (val != null) {
        return val;
      }
    }
    return null;
  }

  /**
   * Get the first non blank term for a list of terms.
   *
   * @param terms list to try
   */
  @Nullable
  public String getFirstRaw(Term... terms) {
    for (Term t : terms) {
      String val = getRaw(t);
      if (val != null) {
        return val;
      }
    }
    return null;
  }

  /**
   * Get the term value split by a delimiter
   */
  @Nullable
  public List<String> get(Term term, Splitter splitter) {
    checkNotNull(term, "term can't be null");
    String val = get(term);
    if (val != null) {
      return splitter.splitToList(val);
    }
    return null;
  }

  /**
   * Stores the current state of the instance for subsequent hasChanged() tests.
   */
  public void setHashCode() {
    _hashKeyOnLoad = hashCode();
  }

  /**
   * @return true if the instance has been modified since the last time setHashCode was executed.
   */
  public boolean hasChanged() {
    return _hashKeyOnLoad == -1 || _hashKeyOnLoad != hashCode();
  }

  @Override
  public String toString() {
    return "v" + id + "{" + file + "#" + line + ", " + terms.size() + " terms";
  }

  public String fileLine() {
    return file + "#" + line;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    VerbatimRecord that = (VerbatimRecord) o;
    return line == that.line &&
        Objects.equals(id, that.id) &&
        Objects.equals(datasetKey, that.datasetKey) &&
        Objects.equals(file, that.file) &&
        Objects.equals(type, that.type) &&
        Objects.equals(terms, that.terms) &&
        Objects.equals(issues, that.issues);
  }

  @Override
  public int hashCode() {

    return Objects.hash(id, datasetKey, line, file, type, terms, issues);
  }

  /**
   * @return all terms and values as a string
   */
  public String toStringComplete() {
    StringBuilder sb = new StringBuilder();
    sb.append(id).append(" ")
        .append(file).append("#").append(line)
        .append(", " + type)
        .append(": ");
    boolean first = true;
    for (Map.Entry<Term, String> te : terms.entrySet()) {
      if (first) {
        first = false;
      } else {
        sb.append(", ");
      }
      sb.append(te.getKey().prefixedName())
          .append("=")
          .append(te.getValue());
    }
    return sb.toString();
  }

}


text:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;

namespace ChakraCore.NET.Debug
{
    public struct VariableProperties
    {
        [JsonProperty(propertyName: "totalPropertiesOfObject")]
        public int StackProperties;
        [JsonProperty(propertyName: "properties")]
        public Variable[] Properties;
        [JsonProperty(propertyName: "debuggerOnlyProperties")]
        public Variable[] DebuggerOnlyProperties;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Tag an image</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

          <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            Toggle navigation

          </button>
          Manzanilla

Home

Hello, user

Log out

Upload a new image resource to EcoLexicon.

      <form action="upload_done.html">

          Image
          <input type="file" id="file">

Select the image you want to upload.

          Resource
          <input type="text" class="form-control" id="resource" placeholder="Resource">

          Title
          <input type="text" class="form-control" id="title" placeholder="Title">

          Description
          <textarea  id="description" class="form-control" rows="3"></textarea>

          Source
          <input type="text" class="form-control" id="source" placeholder="Source">

        <button type="submit" class="btn btn-primary">Submit</button>
      </form>


text:
"""
SQLAlchemy models for rally data.
"""

import uuid

from oslo_db.sqlalchemy.compat import utils as compat_utils
from oslo_db.sqlalchemy import models
from oslo_utils import timeutils
import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import schema
from sqlalchemy import types

from rally.common.db.sqlalchemy import types as sa_types
from rally import consts

BASE = declarative_base()

def UUID():
    return str(uuid.uuid4())

class RallyBase(models.ModelBase):
    metadata = None
    created_at = sa.Column(sa.DateTime, default=lambda: timeutils.utcnow())
    updated_at = sa.Column(sa.DateTime, default=lambda: timeutils.utcnow(),
                           onupdate=lambda: timeutils.utcnow())

    def save(self, session=None):
        # NOTE(LimingWu): We can't direct import the api module. that will
        # result in the cyclic reference import since the api has imported
        # this module.
        from rally.common.db.sqlalchemy import api as sa_api

        if session is None:
            session = sa_api.get_session()

        super(RallyBase, self).save(session=session)

class Deployment(BASE, RallyBase):
    """Represent a deployment of OpenStack."""
    __tablename__ = "deployments"
    __table_args__ = (
        sa.Index("deployment_uuid", "uuid", unique=True),
        sa.Index("deployment_parent_uuid", "parent_uuid"),
    )

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    uuid = sa.Column(sa.String(36), default=UUID, nullable=False)
    parent_uuid = sa.Column(
        sa.String(36),
        sa.ForeignKey(uuid, use_alter=True, name="fk_parent_uuid"),
        default=None,
    )
    name = sa.Column(sa.String(255), unique=True)
    started_at = sa.Column(sa.DateTime)
    completed_at = sa.Column(sa.DateTime)
    # XXX(akscram): Do we need to explicitly store a name of the
    #               deployment engine?
    # engine_name = sa.Column(sa.String(36))

    config = sa.Column(
        sa_types.MutableJSONEncodedDict,
        default={},
        nullable=False,
    )

    credentials = sa.Column(types.PickleType, default=[], nullable=False)

    status = sa.Column(
        sa.Enum(*consts.DeployStatus, name="enum_deploy_status"),
        name="enum_deployments_status",
        default=consts.DeployStatus.DEPLOY_INIT,
        nullable=False,
    )

    parent = sa.orm.relationship(
        "Deployment",
        backref=sa.orm.backref("subdeploys"),
        remote_side=[uuid],
        foreign_keys=parent_uuid,
    )

    # TODO(rpromyshlennikov): remove admin after credentials refactoring
    @property
    def admin(self):
        return self.credentials[0][1]["admin"]

    @admin.setter
    def admin(self, value):
        pass

    # TODO(rpromyshlennikov): remove users after credentials refactoring
    @property
    def users(self):
        return self.credentials[0][1]["users"]

    @users.setter
    def users(self, value):
        pass

class Resource(BASE, RallyBase):
    """Represent a resource of a deployment."""
    __tablename__ = "resources"
    __table_args__ = (
        sa.Index("resource_deployment_uuid", "deployment_uuid"),
        sa.Index("resource_provider_name", "deployment_uuid", "provider_name"),
        sa.Index("resource_type", "deployment_uuid", "type"),
        sa.Index("resource_provider_name_and_type", "deployment_uuid",
                 "provider_name", "type"),
    )

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    provider_name = sa.Column(sa.String(255))
    type = sa.Column(sa.String(255))

    info = sa.Column(
        sa_types.MutableJSONEncodedDict,
        default={},
        nullable=False,
    )

    deployment_uuid = sa.Column(
        sa.String(36),
        sa.ForeignKey(Deployment.uuid),
        nullable=False,
    )
    deployment = sa.orm.relationship(
        Deployment,
        backref=sa.orm.backref("resources"),
        foreign_keys=deployment_uuid,
        primaryjoin=(deployment_uuid == Deployment.uuid),
    )

class Task(BASE, RallyBase):
    """Represents a Benchmark task."""
    __tablename__ = "tasks"
    __table_args__ = (
        sa.Index("task_uuid", "uuid", unique=True),
        sa.Index("task_status", "status"),
        sa.Index("task_deployment", "deployment_uuid"),
    )

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    uuid = sa.Column(sa.String(36), default=UUID, nullable=False)
    status = sa.Column(sa.Enum(*list(consts.TaskStatus),
                       name="enum_tasks_status"),
                       default=consts.TaskStatus.INIT,
                       nullable=False)
    verification_log = sa.Column(sa.Text, default="")
    tag = sa.Column(sa.String(64), default="")

    deployment_uuid = sa.Column(
        sa.String(36),
        sa.ForeignKey(Deployment.uuid),
        nullable=False,
    )

    deployment = sa.orm.relationship(
        Deployment,
        backref=sa.orm.backref("tasks"),
        foreign_keys=deployment_uuid,
        primaryjoin=(deployment_uuid == Deployment.uuid),
    )

class TaskResult(BASE, RallyBase):
    __tablename__ = "task_results"
    __table_args__ = ()

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)

    key = sa.Column(sa_types.MutableJSONEncodedDict, nullable=False)
    data = sa.Column(sa_types.BigMutableJSONEncodedDict, nullable=False)

    task_uuid = sa.Column(sa.String(36), sa.ForeignKey("tasks.uuid"))
    task = sa.orm.relationship(Task,
                               backref=sa.orm.backref("results"),
                               foreign_keys=task_uuid,
                               primaryjoin="TaskResult.task_uuid == Task.uuid")

class Verification(BASE, RallyBase):
    """Represents a verifier result."""

    __tablename__ = "verifications"
    __table_args__ = (
        sa.Index("verification_uuid", "uuid", unique=True),
    )

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    uuid = sa.Column(sa.String(36), default=UUID, nullable=False)

    deployment_uuid = sa.Column(
        sa.String(36),
        sa.ForeignKey(Deployment.uuid),
        nullable=False,
    )

    status = sa.Column(sa.Enum(*list(consts.TaskStatus),
                       name="enum_tasks_status"),
                       default=consts.TaskStatus.INIT,
                       nullable=False)
    set_name = sa.Column(sa.String(20))

    tests = sa.Column(sa.Integer, default=0)
    # TODO(andreykurilin): remove this variable, when rally will support db
    #   migrations. Reason: It is not used anywhere :)
    errors = sa.Column(sa.Integer, default=0)
    failures = sa.Column(sa.Integer, default=0)
    time = sa.Column(sa.Float, default=0.0)

class VerificationResult(BASE, RallyBase):
    __tablename__ = "verification_results"
    __table_args__ = ()

    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)

    verification_uuid = sa.Column(sa.String(36),
                                  sa.ForeignKey("verifications.uuid"))

    data = sa.Column(sa_types.BigMutableJSONEncodedDict, nullable=False)

class Worker(BASE, RallyBase):
    __tablename__ = "workers"
    __table_args__ = (
        schema.UniqueConstraint("hostname", name="uniq_worker@hostname"),
    )
    id = sa.Column(sa.Integer, primary_key=True, autoincrement=True)
    hostname = sa.Column(sa.String(255))

# TODO(boris-42): Remove it after oslo.db > 1.4.1 will be released.
def drop_all_objects(engine):
    """Drop all database objects.

    Drops all database objects remaining on the default schema of the given
    engine. Per-db implementations will also need to drop items specific to
    those systems, such as sequences, custom types (e.g. pg ENUM), etc.
    """
    with engine.begin() as conn:
        inspector = sa.inspect(engine)
        metadata = schema.MetaData()
        tbs = []
        all_fks = []

        for table_name in inspector.get_table_names():
            fks = []
            for fk in inspector.get_foreign_keys(table_name):
                if not fk["name"]:
                    continue
                fks.append(
                    schema.ForeignKeyConstraint((), (), name=fk["name"]))
            table = schema.Table(table_name, metadata, *fks)
            tbs.append(table)
            all_fks.extend(fks)

        if engine.name != "sqlite":
            for fkc in all_fks:
                conn.execute(schema.DropConstraint(fkc))
        for table in tbs:
            conn.execute(schema.DropTable(table))

        if engine.name == "postgresql":
            if compat_utils.sqla_100:
                enums = [e["name"] for e in sa.inspect(conn).get_enums()]
            else:
                enums = conn.dialect._load_enums(conn).keys()

            for e in enums:
                conn.execute("DROP TYPE %s" % e)

def drop_db():
    # NOTE(LimingWu): We can't direct import the api module. that will
    # result in the cyclic reference import since the api has imported
    # this module.
    from rally.common.db.sqlalchemy import api as sa_api
    drop_all_objects(sa_api.get_engine())


text:
var btn = document.getElementById('exchange');
btn.addEventListener('click', function() {
    var firstVal = document.getElementById('first-val').value;
    var secondVal = document.getElementById('second-val').value;
    var temp = firstVal;
    if(firstVal > secondVal) {
    	document.getElementById('first-val').value = secondVal;
    	document.getElementById('second-val').value = temp;

    	document.getElementById('result').innerHTML = "Values have been exchanged";
    }
})


text:
//
//  JMSGFileContent.h
//  JMessage
//
//  Created by deng on 16/7/4.
//  Copyright © 2016年 HXHG. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <JMessage/JMSGMediaAbstractContent.h>

/*!
 * 文件内容类型
 */
@interface JMSGFileContent : JMSGMediaAbstractContent<NSCopying>

JMSG_ASSUME_NONNULL_BEGIN

/*!
 * @abstract 文件名
 */
@property(nonatomic, copy, readonly) NSString *fileName;

/*!
 * @abstract 文件格式
 *
 * 注意:格式后缀不需要带点,只需后缀名,如:pdf、doc 等
 */
@property(nonatomic, strong) NSString * JMSG_NULLABLE format;

// 不支持使用的初始化方法
- (nullable instancetype)init NS_UNAVAILABLE;

/**
 *  初始化文件内容
 *
 *  @param data     文件数据
 *  @param fileName 文件名
 *
 */
- (instancetype)initWithFileData:(NSData *)data
                        fileName:(NSString *)fileName;

/*!
 * @abstract 获取文件内容的数据
 */
- (void)fileData:(JMSGAsyncDataHandler)handler;

/*!
 * @abstract 获取文件内容的数据
 *
 * @param progressHandler 下载进度。会持续回调更新进度, 直接下载完成。如果为 nil 则表示不关心进度。
 * @param handler 结果回调。回调参数:
 *
 * - data 文件数据;
 * - objectId 消息msgId;
 * - error 不为nil表示出错;
 *
 * 如果 error 为 ni, data 也为 nil, 表示没有数据.
 *
 * @discussion
 * 如果本地数据文件已经存在, 则直接返回;
 * 如果本地还没有文件,会发起网络请求下载。下载完后再回调。
 */
- (void)fileDataWithProgress:(JMSGMediaProgressHandler JMSG_NULLABLE)progressHandler
           completionHandler:(JMSGAsyncDataHandler JMSG_NULLABLE)handler;

JMSG_ASSUME_NONNULL_END

@end


text:
class ProviderProfile < ActiveRecord::Base
  module TransitionTo
    class ActiveService < GenericTransitionService
      def perform
        return unless valid?
        transaction do
          update_state!
          cancel_shipping_request_if_any!
        end
      end

      private

      def cancel_shipping_request_if_any!
        if shipping_request.present?
          shipping_request.paper_trail_event = "canceled"
          shipping_request.update!(
            status: :canceled,
            reason: I18n.t("admin.provider_profile.transition.to.active")
          )
          shipping_request.paper_trail_event = nil
        end
      end

      def predicate
        :active
      end

      def shipping_request
        @shipping_request ||= ShippingRequest.with_status(
          :new, :assigned, :in_progress
        ).with_kind(:ask_to_validate)
         .find_by(resource: @provider_profile)
      end
    end
  end
end


text:
module GovKit
  module OpenCongress
    class RollCall < OpenCongressObject

      attr_accessor :abstains, :presents, :roll_type, :title, :question, :republican_position, :democratic_position,
                    :amendment_id, :ayes, :nays, :bill, :date, :number, :id, :required, :where

      def initialize(params)
        params.each do |key, value|
          instance_variable_set("@#{key}", value) if RollCall.instance_methods.include? key
        end
      end

    end
  end
end


text:
/** Testing utilities for the reference runner. */
package org.apache.beam.runners.reference.testing;