text:
package com.google.common.collect;

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

import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.Collections2.FilteredCollection;

import java.io.Serializable;
import java.util.AbstractSet;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.NavigableSet;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.annotation.CheckReturnValue;
import javax.annotation.Nullable;

/**
 * Static utility methods pertaining to {@link Set} instances. Also see this
 * class's counterparts {@link Lists}, {@link Maps} and {@link Queues}.
 *
 *
See the Guava User Guide article on
 * {@code Sets}.
 *
 * @author Kevin Bourrillion
 * @author Jared Levy
 * @author Chris Povirk
 * @since 2.0
 */
@GwtCompatible(emulated = true)
public final class Sets {
  private Sets() {}

  /**
   * {@link AbstractSet} substitute without the potentially-quadratic
   * {@code removeAll} implementation.
   */
  abstract static class ImprovedAbstractSet<E> extends AbstractSet<E> {
    @Override
    public boolean removeAll(Collection<?> c) {
      return removeAllImpl(this, c);
    }

    @Override
    public boolean retainAll(Collection<?> c) {
      return super.retainAll(checkNotNull(c)); // GWT compatibility
    }
  }

  /**
   * Returns an immutable set instance containing the given enum elements.
   * Internally, the returned set will be backed by an {@link EnumSet}.
   *
   *
The iteration order of the returned set follows the enum's iteration
   * order, not the order in which the elements are provided to the method.
   *
   * @param anElement one of the elements the set should contain
   * @param otherElements the rest of the elements the set should contain
   * @return an immutable set containing those elements, minus duplicates
   */
  // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
  @GwtCompatible(serializable = true)
  public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(
      E anElement, E... otherElements) {
    return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements));
  }

  /**
   * Returns an immutable set instance containing the given enum elements.
   * Internally, the returned set will be backed by an {@link EnumSet}.
   *
   *
The iteration order of the returned set follows the enum's iteration
   * order, not the order in which the elements appear in the given collection.
   *
   * @param elements the elements, all of the same {@code enum} type, that the
   *     set should contain
   * @return an immutable set containing those elements, minus duplicates
   */
  // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028
  @GwtCompatible(serializable = true)
  public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(Iterable<E> elements) {
    if (elements instanceof ImmutableEnumSet) {
      return (ImmutableEnumSet<E>) elements;
    } else if (elements instanceof Collection) {
      Collection<E> collection = (Collection<E>) elements;
      if (collection.isEmpty()) {
        return ImmutableSet.of();
      } else {
        return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection));
      }
    } else {
      Iterator<E> itr = elements.iterator();
      if (itr.hasNext()) {
        EnumSet<E> enumSet = EnumSet.of(itr.next());
        Iterators.addAll(enumSet, itr);
        return ImmutableEnumSet.asImmutable(enumSet);
      } else {
        return ImmutableSet.of();
      }
    }
  }

  /**
   * Returns a new, mutable {@code EnumSet} instance containing the given elements in their
   * natural order. This method behaves identically to {@link EnumSet#copyOf(Collection)}, but also
   * accepts non-{@code Collection} iterables and empty iterables.
   */
  public static <E extends Enum<E>> EnumSet<E> newEnumSet(
      Iterable<E> iterable, Class<E> elementType) {
    EnumSet<E> set = EnumSet.noneOf(elementType);
    Iterables.addAll(set, iterable);
    return set;
  }

  // HashSet

  /**
   * Creates a mutable, initially empty {@code HashSet} instance.
   *
   *
Note: if mutability is not required, use {@link ImmutableSet#of()} instead. If
   * {@code E} is an {@link Enum} type, use {@link EnumSet#noneOf} instead. Otherwise, strongly
   * consider using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to
   * get deterministic iteration behavior.
   *
   *
Note for Java 7 and later: this method is now unnecessary and should be treated as
   * deprecated. Instead, use the {@code HashSet} constructor directly, taking advantage of the new
   * "diamond" syntax.
   */
  public static <E> HashSet<E> newHashSet() {
    return new HashSet<E>();
  }

  /**
   * Creates a mutable {@code HashSet} instance initially containing the given elements.
   *
   *
Note: if elements are non-null and won't be added or removed after this point, use
   * {@link ImmutableSet#of()} or {@link ImmutableSet#copyOf(Object[])} instead. If {@code E} is an
   * {@link Enum} type, use {@link EnumSet#of(Enum, Enum[])} instead. Otherwise, strongly consider
   * using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to get
   * deterministic iteration behavior.
   *
   *
This method is just a small convenience, either for {@code newHashSet(}{@link Arrays#asList
   * asList}{@code (...))}, or for creating an empty set then calling {@link Collections#addAll}.
   * This method is not actually very useful and will likely be deprecated in the future.
   */
  public static <E> HashSet<E> newHashSet(E... elements) {
    HashSet<E> set = newHashSetWithExpectedSize(elements.length);
    Collections.addAll(set, elements);
    return set;
  }

  /**
   * Creates a {@code HashSet} instance, with a high enough initial table size that it should
   * hold {@code expectedSize} elements without resizing. This behavior cannot be broadly
   * guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the
   * method isn't inadvertently oversizing the returned set.
   *
   * @param expectedSize the number of elements you expect to add to the
   *        returned set
   * @return a new, empty {@code HashSet} with enough capacity to hold {@code
   *         expectedSize} elements without resizing
   * @throws IllegalArgumentException if {@code expectedSize} is negative
   */
  public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) {
    return new HashSet<E>(Maps.capacity(expectedSize));
  }

  /**
   * Creates a mutable {@code HashSet} instance containing the given elements. A very thin
   * convenience for creating an empty set then calling {@link Collection#addAll} or {@link
   * Iterables#addAll}.
   *
   *
Note: if mutability is not required and the elements are non-null, use {@link
   * ImmutableSet#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link
   * FluentIterable} and call {@code elements.toSet()}.)
   *
   *
Note: if {@code E} is an {@link Enum} type, use {@link #newEnumSet(Iterable, Class)}
   * instead.
   *
   *
Note for Java 7 and later: if {@code elements} is a {@link Collection}, you don't
   * need this method. Instead, use the {@code HashSet} constructor directly, taking advantage of
   * the new "diamond" syntax.
   *
   *
Overall, this method is not very useful and will likely be deprecated in the future.
   */
  public static <E> HashSet<E> newHashSet(Iterable<? extends E> elements) {
    return (elements instanceof Collection)
        ? new HashSet<E>(Collections2.cast(elements))
        : newHashSet(elements.iterator());
  }

  /**
   * Creates a mutable {@code HashSet} instance containing the given elements. A very thin
   * convenience for creating an empty set and then calling {@link Iterators#addAll}.
   *
   *
Note: if mutability is not required and the elements are non-null, use {@link
   * ImmutableSet#copyOf(Iterator)} instead.
   *
   *
Note: if {@code E} is an {@link Enum} type, you should create an {@link EnumSet}
   * instead.
   *
   *
Overall, this method is not very useful and will likely be deprecated in the future.
   */
  public static <E> HashSet<E> newHashSet(Iterator<? extends E> elements) {
    HashSet<E> set = newHashSet();
    Iterators.addAll(set, elements);
    return set;
  }

  /**
   * Creates a thread-safe set backed by a hash map. The set is backed by a
   * {@link ConcurrentHashMap} instance, and thus carries the same concurrency
   * guarantees.
   *
   *
Unlike {@code HashSet}, this class does NOT allow {@code null} to be
   * used as an element. The set is serializable.
   *
   * @return a new, empty thread-safe {@code Set}
   * @since 15.0
   */
  public static <E> Set<E> newConcurrentHashSet() {
    return newSetFromMap(new ConcurrentHashMap<E, Boolean>());
  }

  /**
   * Creates a thread-safe set backed by a hash map and containing the given
   * elements. The set is backed by a {@link ConcurrentHashMap} instance, and
   * thus carries the same concurrency guarantees.
   *
   *
Unlike {@code HashSet}, this class does NOT allow {@code null} to be
   * used as an element. The set is serializable.
   *
   * @param elements the elements that the set should contain
   * @return a new thread-safe set containing those elements (minus duplicates)
   * @throws NullPointerException if {@code elements} or any of its contents is
   *      null
   * @since 15.0
   */
  public static <E> Set<E> newConcurrentHashSet(Iterable<? extends E> elements) {
    Set<E> set = newConcurrentHashSet();
    Iterables.addAll(set, elements);
    return set;
  }

  // LinkedHashSet

  /**
   * Creates a mutable, empty {@code LinkedHashSet} instance.
   *
   *
Note: if mutability is not required, use {@link ImmutableSet#of()} instead.
   *
   *
Note for Java 7 and later: this method is now unnecessary and should be treated as
   * deprecated. Instead, use the {@code LinkedHashSet} constructor directly, taking advantage of
   * the new "diamond" syntax.
   *
   * @return a new, empty {@code LinkedHashSet}
   */
  public static <E> LinkedHashSet<E> newLinkedHashSet() {
    return new LinkedHashSet<E>();
  }

  /**
   * Creates a {@code LinkedHashSet} instance, with a high enough "initial capacity" that it
   * should hold {@code expectedSize} elements without growth. This behavior cannot be
   * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed
   * that the method isn't inadvertently oversizing the returned set.
   *
   * @param expectedSize the number of elements you expect to add to the returned set
   * @return a new, empty {@code LinkedHashSet} with enough capacity to hold {@code expectedSize}
   *         elements without resizing
   * @throws IllegalArgumentException if {@code expectedSize} is negative
   * @since 11.0
   */
  public static <E> LinkedHashSet<E> newLinkedHashSetWithExpectedSize(int expectedSize) {
    return new LinkedHashSet<E>(Maps.capacity(expectedSize));
  }

  /**
   * Creates a mutable {@code LinkedHashSet} instance containing the given elements in order.
   *
   *
Note: if mutability is not required and the elements are non-null, use {@link
   * ImmutableSet#copyOf(Iterable)} instead.
   *
   *
Note for Java 7 and later: if {@code elements} is a {@link Collection}, you don't
   * need this method. Instead, use the {@code LinkedHashSet} constructor directly, taking advantage
   * of the new "diamond" syntax.
   *
   *
Overall, this method is not very useful and will likely be deprecated in the future.
   *
   * @param elements the elements that the set should contain, in order
   * @return a new {@code LinkedHashSet} containing those elements (minus duplicates)
   */
  public static <E> LinkedHashSet<E> newLinkedHashSet(Iterable<? extends E> elements) {
    if (elements instanceof Collection) {
      return new LinkedHashSet<E>(Collections2.cast(elements));
    }
    LinkedHashSet<E> set = newLinkedHashSet();
    Iterables.addAll(set, elements);
    return set;
  }

  // TreeSet

  /**
   * Creates a mutable, empty {@code TreeSet} instance sorted by the natural sort ordering of
   * its elements.
   *
   *
Note: if mutability is not required, use {@link ImmutableSortedSet#of()} instead.
   *
   *
Note for Java 7 and later: this method is now unnecessary and should be treated as
   * deprecated. Instead, use the {@code TreeSet} constructor directly, taking advantage of the new
   * "diamond" syntax.
   *
   * @return a new, empty {@code TreeSet}
   */
  public static <E extends Comparable> TreeSet<E> newTreeSet() {
    return new TreeSet<E>();
  }

  /**
   * Creates a mutable {@code TreeSet} instance containing the given elements sorted by their
   * natural ordering.
   *
   *
Note: if mutability is not required, use {@link ImmutableSortedSet#copyOf(Iterable)}
   * instead.
   *
   *
Note: If {@code elements} is a {@code SortedSet} with an explicit comparator, this
   * method has different behavior than {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code
   * TreeSet} with that comparator.
   *
   *
Note for Java 7 and later: this method is now unnecessary and should be treated as
   * deprecated. Instead, use the {@code TreeSet} constructor directly, taking advantage of the new
   * "diamond" syntax.
   *
   *
This method is just a small convenience for creating an empty set and then calling {@link
   * Iterables#addAll}. This method is not very useful and will likely be deprecated in the future.
   *
   * @param elements the elements that the set should contain
   * @return a new {@code TreeSet} containing those elements (minus duplicates)
   */
  public static <E extends Comparable> TreeSet<E> newTreeSet(Iterable<? extends E> elements) {
    TreeSet<E> set = newTreeSet();
    Iterables.addAll(set, elements);
    return set;
  }

  /**
   * Creates a mutable, empty {@code TreeSet} instance with the given comparator.
   *
   *
Note: if mutability is not required, use {@code
   * ImmutableSortedSet.orderedBy(comparator).build()} instead.
   *
   *
Note for Java 7 and later: this method is now unnecessary and should be treated as
   * deprecated. Instead, use the {@code TreeSet} constructor directly, taking advantage of the new
   * "diamond" syntax. One caveat to this is that the {@code
   * TreeSet} constructor uses a null {@code Comparator} to mean "natural ordering," whereas this
   * factory rejects null. Clean your code accordingly.
   *
   * @param comparator the comparator to use to sort the set
   * @return a new, empty {@code TreeSet}
   * @throws NullPointerException if {@code comparator} is null
   */
  public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) {
    return new TreeSet<E>(checkNotNull(comparator));
  }

  /**
   * Creates an empty {@code Set} that uses identity to determine equality. It
   * compares object references, instead of calling {@code equals}, to
   * determine whether a provided object matches an element in the set. For
   * example, {@code contains} returns {@code false} when passed an object that
   * equals a set member, but isn't the same instance. This behavior is similar
   * to the way {@code IdentityHashMap} handles key lookups.
   *
   * @since 8.0
   */
  public static <E> Set<E> newIdentityHashSet() {
    return Sets.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap());
  }

  /**
   * Creates an empty {@code CopyOnWriteArraySet} instance.
   *
   *
Note: if you need an immutable empty {@link Set}, use
   * {@link Collections#emptySet} instead.
   *
   * @return a new, empty {@code CopyOnWriteArraySet}
   * @since 12.0
   */
  @GwtIncompatible("CopyOnWriteArraySet")
  public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() {
    return new CopyOnWriteArraySet<E>();
  }

  /**
   * Creates a {@code CopyOnWriteArraySet} instance containing the given elements.
   *
   * @param elements the elements that the set should contain, in order
   * @return a new {@code CopyOnWriteArraySet} containing those elements
   * @since 12.0
   */
  @GwtIncompatible("CopyOnWriteArraySet")
  public static <E> CopyOnWriteArraySet<E> newCopyOnWriteArraySet(Iterable<? extends E> elements) {
    // We copy elements to an ArrayList first, rather than incurring the
    // quadratic cost of adding them to the COWAS directly.
    Collection<? extends E> elementsCollection =
        (elements instanceof Collection)
            ? Collections2.cast(elements)
            : Lists.newArrayList(elements);
    return new CopyOnWriteArraySet<E>(elementsCollection);
  }

  /**
   * Creates an {@code EnumSet} consisting of all enum values that are not in
   * the specified collection. If the collection is an {@link EnumSet}, this
   * method has the same behavior as {@link EnumSet#complementOf}. Otherwise,
   * the specified collection must contain at least one element, in order to
   * determine the element type. If the collection could be empty, use
   * {@link #complementOf(Collection, Class)} instead of this method.
   *
   * @param collection the collection whose complement should be stored in the
   *     enum set
   * @return a new, modifiable {@code EnumSet} containing all values of the enum
   *     that aren't present in the given collection
   * @throws IllegalArgumentException if {@code collection} is not an
   *     {@code EnumSet} instance and contains no elements
   */
  public static <E extends Enum<E>> EnumSet<E> complementOf(Collection<E> collection) {
    if (collection instanceof EnumSet) {
      return EnumSet.complementOf((EnumSet<E>) collection);
    }
    checkArgument(
        !collection.isEmpty(), "collection is empty; use the other version of this method");
    Class<E> type = collection.iterator().next().getDeclaringClass();
    return makeComplementByHand(collection, type);
  }

  /**
   * Creates an {@code EnumSet} consisting of all enum values that are not in
   * the specified collection. This is equivalent to
   * {@link EnumSet#complementOf}, but can act on any input collection, as long
   * as the elements are of enum type.
   *
   * @param collection the collection whose complement should be stored in the
   *     {@code EnumSet}
   * @param type the type of the elements in the set
   * @return a new, modifiable {@code EnumSet} initially containing all the
   *     values of the enum not present in the given collection
   */
  public static <E extends Enum<E>> EnumSet<E> complementOf(
      Collection<E> collection, Class<E> type) {
    checkNotNull(collection);
    return (collection instanceof EnumSet)
        ? EnumSet.complementOf((EnumSet<E>) collection)
        : makeComplementByHand(collection, type);
  }

  private static <E extends Enum<E>> EnumSet<E> makeComplementByHand(
      Collection<E> collection, Class<E> type) {
    EnumSet<E> result = EnumSet.allOf(type);
    result.removeAll(collection);
    return result;
  }

  /**
   * Returns a set backed by the specified map. The resulting set displays
   * the same ordering, concurrency, and performance characteristics as the
   * backing map. In essence, this factory method provides a {@link Set}
   * implementation corresponding to any {@link Map} implementation. There is no
   * need to use this method on a {@link Map} implementation that already has a
   * corresponding {@link Set} implementation (such as {@link java.util.HashMap}
   * or {@link java.util.TreeMap}).
   *
   *
Each method invocation on the set returned by this method results in
   * exactly one method invocation on the backing map or its {@code keySet}
   * view, with one exception. The {@code addAll} method is implemented as a
   * sequence of {@code put} invocations on the backing map.
   *
   *
The specified map must be empty at the time this method is invoked,
   * and should not be accessed directly after this method returns. These
   * conditions are ensured if the map is created empty, passed directly
   * to this method, and no reference to the map is retained, as illustrated
   * in the following code fragment:
  {@code
   *
   *   Set<Object> identityHashSet = Sets.newSetFromMap(
   *       new IdentityHashMap<Object, Boolean>());}

   *
   *
The returned set is serializable if the backing map is.
   *
   * @param map the backing map
   * @return the set backed by the map
   * @throws IllegalArgumentException if {@code map} is not empty
   * @deprecated Use {@link Collections#newSetFromMap} instead. This method
   *     will be removed in August 2017.
   */
  @Deprecated
  public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) {
    return Platform.newSetFromMap(map);
  }

  /**
   * An unmodifiable view of a set which may be backed by other sets; this view
   * will change as the backing sets do. Contains methods to copy the data into
   * a new set which will then remain stable. There is usually no reason to
   * retain a reference of type {@code SetView}; typically, you either use it
   * as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or
   * {@link #copyInto} and forget the {@code SetView} itself.
   *
   * @since 2.0
   */
  public abstract static class SetView<E> extends AbstractSet<E> {
    private SetView() {} // no subclasses but our own

    /**
     * Returns an immutable copy of the current contents of this set view.
     * Does not support null elements.
     *
     *
Warning: this may have unexpected results if a backing set of
     * this view uses a nonstandard notion of equivalence, for example if it is
     * a {@link TreeSet} using a comparator that is inconsistent with {@link
     * Object#equals(Object)}.
     */
    public ImmutableSet<E> immutableCopy() {
      return ImmutableSet.copyOf(this);
    }

    /**
     * Copies the current contents of this set view into an existing set. This
     * method has equivalent behavior to {@code set.addAll(this)}, assuming that
     * all the sets involved are based on the same notion of equivalence.
     *
     * @return a reference to {@code set}, for convenience
     */
    // Note: S should logically extend Set<? super E> but can't due to either
    // some javac bug or some weirdness in the spec, not sure which.
    public <S extends Set<E>> S copyInto(S set) {
      set.addAll(this);
      return set;
    }
  }

  /**
   * Returns an unmodifiable view of the union of two sets. The returned
   * set contains all elements that are contained in either backing set.
   * Iterating over the returned set iterates first over all the elements of
   * {@code set1}, then over each element of {@code set2}, in order, that is not
   * contained in {@code set1}.
   *
   *
Results are undefined if {@code set1} and {@code set2} are sets based on
   * different equivalence relations (as {@link HashSet}, {@link TreeSet}, and
   * the {@link Map#keySet} of an {@code IdentityHashMap} all are).
   *
   *
Note: The returned view performs better when {@code set1} is the
   * smaller of the two sets. If you have reason to believe one of your sets
   * will generally be smaller than the other, pass it first.
   *
   *
Further, note that the current implementation is not suitable for nested
   * {@code union} views, i.e. the following should be avoided when in a loop:
   * {@code union = Sets.union(union, anotherSet);}, since iterating over the resulting
   * set has a cubic complexity to the depth of the nesting.
   */
  public static <E> SetView<E> union(final Set<? extends E> set1, final Set<? extends E> set2) {
    checkNotNull(set1, "set1");
    checkNotNull(set2, "set2");

    final Set<? extends E> set2minus1 = difference(set2, set1);

    return new SetView<E>() {
      @Override
      public int size() {
        return set1.size() + set2minus1.size();
      }

      @Override
      public boolean isEmpty() {
        return set1.isEmpty() && set2.isEmpty();
      }

      @Override
      public Iterator<E> iterator() {
        return Iterators.unmodifiableIterator(
            Iterators.concat(set1.iterator(), set2minus1.iterator()));
      }

      @Override
      public boolean contains(Object object) {
        return set1.contains(object) || set2.contains(object);
      }

      @Override
      public <S extends Set<E>> S copyInto(S set) {
        set.addAll(set1);
        set.addAll(set2);
        return set;
      }

      @Override
      public ImmutableSet<E> immutableCopy() {
        return new ImmutableSet.Builder<E>().addAll(set1).addAll(set2).build();
      }
    };
  }

  /**
   * Returns an unmodifiable view of the intersection of two sets. The
   * returned set contains all elements that are contained by both backing sets.
   * The iteration order of the returned set matches that of {@code set1}.
   *
   *
Results are undefined if {@code set1} and {@code set2} are sets based
   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
   * and the keySet of an {@code IdentityHashMap} all are).
   *
   *
Note: The returned view performs slightly better when {@code
   * set1} is the smaller of the two sets. If you have reason to believe one of
   * your sets will generally be smaller than the other, pass it first.
   * Unfortunately, since this method sets the generic type of the returned set
   * based on the type of the first set passed, this could in rare cases force
   * you to make a cast, for example:
   {@code
   *
   *   Set<Object> aFewBadObjects = ...
   *   Set<String> manyBadStrings = ...
   *
   *   // impossible for a non-String to be in the intersection
   *   SuppressWarnings("unchecked")
   *   Set<String> badStrings = (Set) Sets.intersection(
   *       aFewBadObjects, manyBadStrings);}

   *
   *
This is unfortunate, but should come up only very rarely.
   */
  public static <E> SetView<E> intersection(final Set<E> set1, final Set<?> set2) {
    checkNotNull(set1, "set1");
    checkNotNull(set2, "set2");

    final Predicate<Object> inSet2 = Predicates.in(set2);
    return new SetView<E>() {
      @Override
      public Iterator<E> iterator() {
        return Iterators.filter(set1.iterator(), inSet2);
      }

      @Override
      public int size() {
        return Iterators.size(iterator());
      }

      @Override
      public boolean isEmpty() {
        return !iterator().hasNext();
      }

      @Override
      public boolean contains(Object object) {
        return set1.contains(object) && set2.contains(object);
      }

      @Override
      public boolean containsAll(Collection<?> collection) {
        return set1.containsAll(collection) && set2.containsAll(collection);
      }
    };
  }

  /**
   * Returns an unmodifiable view of the difference of two sets. The
   * returned set contains all elements that are contained by {@code set1} and
   * not contained by {@code set2}. {@code set2} may also contain elements not
   * present in {@code set1}; these are simply ignored. The iteration order of
   * the returned set matches that of {@code set1}.
   *
   *
Results are undefined if {@code set1} and {@code set2} are sets based
   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
   * and the keySet of an {@code IdentityHashMap} all are).
   */
  public static <E> SetView<E> difference(final Set<E> set1, final Set<?> set2) {
    checkNotNull(set1, "set1");
    checkNotNull(set2, "set2");

    final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
    return new SetView<E>() {
      @Override
      public Iterator<E> iterator() {
        return Iterators.filter(set1.iterator(), notInSet2);
      }

      @Override
      public int size() {
        return Iterators.size(iterator());
      }

      @Override
      public boolean isEmpty() {
        return set2.containsAll(set1);
      }

      @Override
      public boolean contains(Object element) {
        return set1.contains(element) && !set2.contains(element);
      }
    };
  }

  /**
   * Returns an unmodifiable view of the symmetric difference of two
   * sets. The returned set contains all elements that are contained in either
   * {@code set1} or {@code set2} but not in both. The iteration order of the
   * returned set is undefined.
   *
   *
Results are undefined if {@code set1} and {@code set2} are sets based
   * on different equivalence relations (as {@code HashSet}, {@code TreeSet},
   * and the keySet of an {@code IdentityHashMap} all are).
   *
   * @since 3.0
   */
  public static <E> SetView<E> symmetricDifference(
      final Set<? extends E> set1, final Set<? extends E> set2) {
    checkNotNull(set1, "set1");
    checkNotNull(set2, "set2");

    return new SetView<E>() {
      @Override
      public Iterator<E> iterator() {
        final Iterator<? extends E> itr1 = set1.iterator();
        final Iterator<? extends E> itr2 = set2.iterator();
        return new AbstractIterator<E>() {
          @Override
          public E computeNext() {
            while (itr1.hasNext()) {
              E elem1 = itr1.next();
              if (!set2.contains(elem1)) {
                return elem1;
              }
            }
            while (itr2.hasNext()) {
              E elem2 = itr2.next();
              if (!set1.contains(elem2)) {
                return elem2;
              }
            }
            return endOfData();
          }
        };
      }

      @Override
      public int size() {
        return Iterators.size(iterator());
      }

      @Override
      public boolean isEmpty() {
        return set1.equals(set2);
      }

      @Override
      public boolean contains(Object element) {
        return set1.contains(element) ^ set2.contains(element);
      }
    };
  }

  /**
   * Returns the elements of {@code unfiltered} that satisfy a predicate. The
   * returned set is a live view of {@code unfiltered}; changes to one affect
   * the other.
   *
   *
The resulting set's iterator does not support {@code remove()}, but all
   * other set methods are supported. When given an element that doesn't satisfy
   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
   * an {@link IllegalArgumentException}. When methods such as {@code
   * removeAll()} and {@code clear()} are called on the filtered set, only
   * elements that satisfy the filter will be removed from the underlying set.
   *
   *
The returned set isn't threadsafe or serializable, even if
   * {@code unfiltered} is.
   *
   *
Many of the filtered set's methods, such as {@code size()}, iterate
   * across every element in the underlying set and determine which elements
   * satisfy the filter. When a live view is not needed, it may be faster
   * to copy {@code Iterables.filter(unfiltered, predicate)} and use the copy.
   *
   *
Warning: {@code predicate} must be consistent with equals,
   * as documented at {@link Predicate#apply}. Do not provide a predicate such
   * as {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent
   * with equals. (See {@link Iterables#filter(Iterable, Class)} for related
   * functionality.)
   */
  // TODO(kevinb): how to omit that last sentence when building GWT javadoc?
  @CheckReturnValue
  public static <E> Set<E> filter(Set<E> unfiltered, Predicate<? super E> predicate) {
    if (unfiltered instanceof SortedSet) {
      return filter((SortedSet<E>) unfiltered, predicate);
    }
    if (unfiltered instanceof FilteredSet) {
      // Support clear(), removeAll(), and retainAll() when filtering a filtered
      // collection.
      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
      Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate);
      return new FilteredSet<E>((Set<E>) filtered.unfiltered, combinedPredicate);
    }

    return new FilteredSet<E>(checkNotNull(unfiltered), checkNotNull(predicate));
  }

  private static class FilteredSet<E> extends FilteredCollection<E> implements Set<E> {
    FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) {
      super(unfiltered, predicate);
    }

    @Override
    public boolean equals(@Nullable Object object) {
      return equalsImpl(this, object);
    }

    @Override
    public int hashCode() {
      return hashCodeImpl(this);
    }
  }

  /**
   * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that
   * satisfy a predicate. The returned set is a live view of {@code unfiltered};
   * changes to one affect the other.
   *
   *
The resulting set's iterator does not support {@code remove()}, but all
   * other set methods are supported. When given an element that doesn't satisfy
   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
   * an {@link IllegalArgumentException}. When methods such as
   * {@code removeAll()} and {@code clear()} are called on the filtered set,
   * only elements that satisfy the filter will be removed from the underlying
   * set.
   *
   *
The returned set isn't threadsafe or serializable, even if
   * {@code unfiltered} is.
   *
   *
Many of the filtered set's methods, such as {@code size()}, iterate across
   * every element in the underlying set and determine which elements satisfy
   * the filter. When a live view is not needed, it may be faster to copy
   * {@code Iterables.filter(unfiltered, predicate)} and use the copy.
   *
   *
Warning: {@code predicate} must be consistent with equals,
   * as documented at {@link Predicate#apply}. Do not provide a predicate such as
   * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
   * equals. (See {@link Iterables#filter(Iterable, Class)} for related
   * functionality.)
   *
   * @since 11.0
   */
  @CheckReturnValue
  public static <E> SortedSet<E> filter(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
    return Platform.setsFilterSortedSet(unfiltered, predicate);
  }

  static <E> SortedSet<E> filterSortedIgnoreNavigable(
      SortedSet<E> unfiltered, Predicate<? super E> predicate) {
    if (unfiltered instanceof FilteredSet) {
      // Support clear(), removeAll(), and retainAll() when filtering a filtered
      // collection.
      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
      Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate);
      return new FilteredSortedSet<E>((SortedSet<E>) filtered.unfiltered, combinedPredicate);
    }

    return new FilteredSortedSet<E>(checkNotNull(unfiltered), checkNotNull(predicate));
  }

  private static class FilteredSortedSet<E> extends FilteredSet<E> implements SortedSet<E> {

    FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) {
      super(unfiltered, predicate);
    }

    @Override
    public Comparator<? super E> comparator() {
      return ((SortedSet<E>) unfiltered).comparator();
    }

    @Override
    public SortedSet<E> subSet(E fromElement, E toElement) {
      return new FilteredSortedSet<E>(
          ((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate);
    }

    @Override
    public SortedSet<E> headSet(E toElement) {
      return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).headSet(toElement), predicate);
    }

    @Override
    public SortedSet<E> tailSet(E fromElement) {
      return new FilteredSortedSet<E>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate);
    }

    @Override
    public E first() {
      return iterator().next();
    }

    @Override
    public E last() {
      SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered;
      while (true) {
        E element = sortedUnfiltered.last();
        if (predicate.apply(element)) {
          return element;
        }
        sortedUnfiltered = sortedUnfiltered.headSet(element);
      }
    }
  }

  /**
   * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that
   * satisfy a predicate. The returned set is a live view of {@code unfiltered};
   * changes to one affect the other.
   *
   *
The resulting set's iterator does not support {@code remove()}, but all
   * other set methods are supported. When given an element that doesn't satisfy
   * the predicate, the set's {@code add()} and {@code addAll()} methods throw
   * an {@link IllegalArgumentException}. When methods such as
   * {@code removeAll()} and {@code clear()} are called on the filtered set,
   * only elements that satisfy the filter will be removed from the underlying
   * set.
   *
   *
The returned set isn't threadsafe or serializable, even if
   * {@code unfiltered} is.
   *
   *
Many of the filtered set's methods, such as {@code size()}, iterate across
   * every element in the underlying set and determine which elements satisfy
   * the filter. When a live view is not needed, it may be faster to copy
   * {@code Iterables.filter(unfiltered, predicate)} and use the copy.
   *
   *
Warning: {@code predicate} must be consistent with equals,
   * as documented at {@link Predicate#apply}. Do not provide a predicate such as
   * {@code Predicates.instanceOf(ArrayList.class)}, which is inconsistent with
   * equals. (See {@link Iterables#filter(Iterable, Class)} for related
   * functionality.)
   *
   * @since 14.0
   */
  @GwtIncompatible("NavigableSet")
  @SuppressWarnings("unchecked")
  @CheckReturnValue
  public static <E> NavigableSet<E> filter(
      NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
    if (unfiltered instanceof FilteredSet) {
      // Support clear(), removeAll(), and retainAll() when filtering a filtered
      // collection.
      FilteredSet<E> filtered = (FilteredSet<E>) unfiltered;
      Predicate<E> combinedPredicate = Predicates.<E>and(filtered.predicate, predicate);
      return new FilteredNavigableSet<E>((NavigableSet<E>) filtered.unfiltered, combinedPredicate);
    }

    return new FilteredNavigableSet<E>(checkNotNull(unfiltered), checkNotNull(predicate));
  }

  @GwtIncompatible("NavigableSet")
  private static class FilteredNavigableSet<E> extends FilteredSortedSet<E>
      implements NavigableSet<E> {
    FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) {
      super(unfiltered, predicate);
    }

    NavigableSet<E> unfiltered() {
      return (NavigableSet<E>) unfiltered;
    }

    @Override
    @Nullable
    public E lower(E e) {
      return Iterators.getNext(headSet(e, false).descendingIterator(), null);
    }

    @Override
    @Nullable
    public E floor(E e) {
      return Iterators.getNext(headSet(e, true).descendingIterator(), null);
    }

    @Override
    public E ceiling(E e) {
      return Iterables.getFirst(tailSet(e, true), null);
    }

    @Override
    public E higher(E e) {
      return Iterables.getFirst(tailSet(e, false), null);
    }

    @Override
    public E pollFirst() {
      return Iterables.removeFirstMatching(unfiltered(), predicate);
    }

    @Override
    public E pollLast() {
      return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate);
    }

    @Override
    public NavigableSet<E> descendingSet() {
      return Sets.filter(unfiltered().descendingSet(), predicate);
    }

    @Override
    public Iterator<E> descendingIterator() {
      return Iterators.filter(unfiltered().descendingIterator(), predicate);
    }

    @Override
    public E last() {
      return descendingIterator().next();
    }

    @Override
    public NavigableSet<E> subSet(
        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
      return filter(
          unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate);
    }

    @Override
    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
      return filter(unfiltered().headSet(toElement, inclusive), predicate);
    }

    @Override
    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
      return filter(unfiltered().tailSet(fromElement, inclusive), predicate);
    }
  }

  /**
   * Returns every possible list that can be formed by choosing one element
   * from each of the given sets in order; the "n-ary
   * Cartesian
   * product" of the sets. For example:
   {@code
   *
   *   Sets.cartesianProduct(ImmutableList.of(
   *       ImmutableSet.of(1, 2),
   *       ImmutableSet.of("A", "B", "C")))}

   *
   *
returns a set containing six lists:
   *
   *

   *
{@code ImmutableList.of(1, "A")}
   *
{@code ImmutableList.of(1, "B")}
   *
{@code ImmutableList.of(1, "C")}
   *
{@code ImmutableList.of(2, "A")}
   *
{@code ImmutableList.of(2, "B")}
   *
{@code ImmutableList.of(2, "C")}
   *

   *
   *
The result is guaranteed to be in the "traditional", lexicographical
   * order for Cartesian products that you would get from nesting for loops:
   *
   {@code
   *
   *   for (B b0 : sets.get(0)) {
   *     for (B b1 : sets.get(1)) {
   *       ...
   *       ImmutableList tuple = ImmutableList.of(b0, b1, ...);
   *       // operate on tuple
   *     }
   *   }}

   *
   *
Note that if any input set is empty, the Cartesian product will also be
   * empty. If no sets at all are provided (an empty list), the resulting
   * Cartesian product has one element, an empty list (counter-intuitive, but
   * mathematically consistent).
   *
   *
Performance notes: while the cartesian product of sets of size
   * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
   * consumption is much smaller. When the cartesian set is constructed, the
   * input sets are merely copied. Only as the resulting set is iterated are the
   * individual lists created, and these are not retained after iteration.
   *
   * @param sets the sets to choose elements from, in the order that
   *     the elements chosen from those sets should appear in the resulting
   *     lists
   * @param  any common base class shared by all axes (often just {@link
   *     Object})
   * @return the Cartesian product, as an immutable set containing immutable
   *     lists
   * @throws NullPointerException if {@code sets}, any one of the {@code sets},
   *     or any element of a provided set is null
   * @since 2.0
   */
  public static  Set<List> cartesianProduct(List<? extends Set<? extends B>> sets) {
    return CartesianSet.create(sets);
  }

  /**
   * Returns every possible list that can be formed by choosing one element
   * from each of the given sets in order; the "n-ary
   * Cartesian
   * product" of the sets. For example:
   {@code
   *
   *   Sets.cartesianProduct(
   *       ImmutableSet.of(1, 2),
   *       ImmutableSet.of("A", "B", "C"))}

   *
   *
returns a set containing six lists:
   *
   *

   *
{@code ImmutableList.of(1, "A")}
   *
{@code ImmutableList.of(1, "B")}
   *
{@code ImmutableList.of(1, "C")}
   *
{@code ImmutableList.of(2, "A")}
   *
{@code ImmutableList.of(2, "B")}
   *
{@code ImmutableList.of(2, "C")}
   *

   *
   *
The result is guaranteed to be in the "traditional", lexicographical
   * order for Cartesian products that you would get from nesting for loops:
   *
   {@code
   *
   *   for (B b0 : sets.get(0)) {
   *     for (B b1 : sets.get(1)) {
   *       ...
   *       ImmutableList tuple = ImmutableList.of(b0, b1, ...);
   *       // operate on tuple
   *     }
   *   }}

   *
   *
Note that if any input set is empty, the Cartesian product will also be
   * empty. If no sets at all are provided (an empty list), the resulting
   * Cartesian product has one element, an empty list (counter-intuitive, but
   * mathematically consistent).
   *
   *
Performance notes: while the cartesian product of sets of size
   * {@code m, n, p} is a set of size {@code m x n x p}, its actual memory
   * consumption is much smaller. When the cartesian set is constructed, the
   * input sets are merely copied. Only as the resulting set is iterated are the
   * individual lists created, and these are not retained after iteration.
   *
   * @param sets the sets to choose elements from, in the order that
   *     the elements chosen from those sets should appear in the resulting
   *     lists
   * @param  any common base class shared by all axes (often just {@link
   *     Object})
   * @return the Cartesian product, as an immutable set containing immutable
   *     lists
   * @throws NullPointerException if {@code sets}, any one of the {@code sets},
   *     or any element of a provided set is null
   * @since 2.0
   */
  public static  Set<List> cartesianProduct(Set<? extends B>... sets) {
    return cartesianProduct(Arrays.asList(sets));
  }

  private static final class CartesianSet<E> extends ForwardingCollection<List<E>>
      implements Set<List<E>> {
    private transient final ImmutableList<ImmutableSet<E>> axes;
    private transient final CartesianList<E> delegate;

    static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) {
      ImmutableList.Builder<ImmutableSet<E>> axesBuilder =
          new ImmutableList.Builder<ImmutableSet<E>>(sets.size());
      for (Set<? extends E> set : sets) {
        ImmutableSet<E> copy = ImmutableSet.copyOf(set);
        if (copy.isEmpty()) {
          return ImmutableSet.of();
        }
        axesBuilder.add(copy);
      }
      final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build();
      ImmutableList<List<E>> listAxes =
          new ImmutableList<List<E>>() {
            @Override
            public int size() {
              return axes.size();
            }

            @Override
            public List<E> get(int index) {
              return axes.get(index).asList();
            }

            @Override
            boolean isPartialView() {
              return true;
            }
          };
      return new CartesianSet<E>(axes, new CartesianList<E>(listAxes));
    }

    private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) {
      this.axes = axes;
      this.delegate = delegate;
    }

    @Override
    protected Collection<List<E>> delegate() {
      return delegate;
    }

    @Override
    public boolean equals(@Nullable Object object) {
      // Warning: this is broken if size() == 0, so it is critical that we
      // substitute an empty ImmutableSet to the user in place of this
      if (object instanceof CartesianSet) {
        CartesianSet<?> that = (CartesianSet<?>) object;
        return this.axes.equals(that.axes);
      }
      return super.equals(object);
    }

    @Override
    public int hashCode() {
      // Warning: this is broken if size() == 0, so it is critical that we
      // substitute an empty ImmutableSet to the user in place of this

      // It's a weird formula, but tests prove it works.
      int adjust = size() - 1;
      for (int i = 0; i < axes.size(); i++) {
        adjust *= 31;
        adjust = ~~adjust;
        // in GWT, we have to deal with integer overflow carefully
      }
      int hash = 1;
      for (Set<E> axis : axes) {
        hash = 31 * hash + (size() / axis.size() * axis.hashCode());

        hash = ~~hash;
      }
      hash += adjust;
      return ~~hash;
    }
  }

  /**
   * Returns the set of all possible subsets of {@code set}. For example,
   * {@code powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{},
   * {1}, {2}, {1, 2}}}.
   *
   *
Elements appear in these subsets in the same iteration order as they
   * appeared in the input set. The order in which these subsets appear in the
   * outer set is undefined. Note that the power set of the empty set is not the
   * empty set, but a one-element set containing the empty set.
   *
   *
The returned set and its constituent sets use {@code equals} to decide
   * whether two elements are identical, even if the input set uses a different
   * concept of equivalence.
   *
   *
Performance notes: while the power set of a set with size {@code
   * n} is of size {@code 2^n}, its memory usage is only {@code O(n)}. When the
   * power set is constructed, the input set is merely copied. Only as the
   * power set is iterated are the individual subsets created, and these subsets
   * themselves occupy only a small constant amount of memory.
   *
   * @param set the set of elements to construct a power set from
   * @return the power set, as an immutable set of immutable sets
   * @throws IllegalArgumentException if {@code set} has more than 30 unique
   *     elements (causing the power set size to exceed the {@code int} range)
   * @throws NullPointerException if {@code set} is or contains {@code null}
   * @see Power set article at
   *      Wikipedia
   * @since 4.0
   */
  @GwtCompatible(serializable = false)
  public static <E> Set<Set<E>> powerSet(Set<E> set) {
    return new PowerSet<E>(set);
  }

  private static final class SubSet<E> extends AbstractSet<E> {
    private final ImmutableMap<E, Integer> inputSet;
    private final int mask;

    SubSet(ImmutableMap<E, Integer> inputSet, int mask) {
      this.inputSet = inputSet;
      this.mask = mask;
    }

    @Override
    public Iterator<E> iterator() {
      return new UnmodifiableIterator<E>() {
        final ImmutableList<E> elements = inputSet.keySet().asList();
        int remainingSetBits = mask;

        @Override
        public boolean hasNext() {
          return remainingSetBits != 0;
        }

        @Override
        public E next() {
          int index = Integer.numberOfTrailingZeros(remainingSetBits);
          if (index == 32) {
            throw new NoSuchElementException();
          }
          remainingSetBits &= ~(1 << index);
          return elements.get(index);
        }
      };
    }

    @Override
    public int size() {
      return Integer.bitCount(mask);
    }

    @Override
    public boolean contains(@Nullable Object o) {
      Integer index = inputSet.get(o);
      return index != null && (mask & (1 << index)) != 0;
    }
  }

  private static final class PowerSet<E> extends AbstractSet<Set<E>> {
    final ImmutableMap<E, Integer> inputSet;

    PowerSet(Set<E> input) {
      this.inputSet = Maps.indexMap(input);
      checkArgument(
          inputSet.size() <= 30, "Too many elements to create power set: %s > 30", inputSet.size());
    }

    @Override
    public int size() {
      return 1 << inputSet.size();
    }

    @Override
    public boolean isEmpty() {
      return false;
    }

    @Override
    public Iterator<Set<E>> iterator() {
      return new AbstractIndexedListIterator<Set<E>>(size()) {
        @Override
        protected Set<E> get(final int setBits) {
          return new SubSet<E>(inputSet, setBits);
        }
      };
    }

    @Override
    public boolean contains(@Nullable Object obj) {
      if (obj instanceof Set) {
        Set<?> set = (Set<?>) obj;
        return inputSet.keySet().containsAll(set);
      }
      return false;
    }

    @Override
    public boolean equals(@Nullable Object obj) {
      if (obj instanceof PowerSet) {
        PowerSet<?> that = (PowerSet<?>) obj;
        return inputSet.equals(that.inputSet);
      }
      return super.equals(obj);
    }

    @Override
    public int hashCode() {
      /*
       * The sum of the sums of the hash codes in each subset is just the sum of
       * each input element's hash code times the number of sets that element
       * appears in. Each element appears in exactly half of the 2^n sets, so:
       */
      return inputSet.keySet().hashCode() << (inputSet.size() - 1);
    }

    @Override
    public String toString() {
      return "powerSet(" + inputSet + ")";
    }
  }

  /**
   * An implementation for {@link Set#hashCode()}.
   */
  static int hashCodeImpl(Set<?> s) {
    int hashCode = 0;
    for (Object o : s) {
      hashCode += o != null ? o.hashCode() : 0;

      hashCode = ~~hashCode;
      // Needed to deal with unusual integer overflow in GWT.
    }
    return hashCode;
  }

  /**
   * An implementation for {@link Set#equals(Object)}.
   */
  static boolean equalsImpl(Set<?> s, @Nullable Object object) {
    if (s == object) {
      return true;
    }
    if (object instanceof Set) {
      Set<?> o = (Set<?>) object;

      try {
        return s.size() == o.size() && s.containsAll(o);
      } catch (NullPointerException ignored) {
        return false;
      } catch (ClassCastException ignored) {
        return false;
      }
    }
    return false;
  }

  /**
   * Returns an unmodifiable view of the specified navigable set. This method
   * allows modules to provide users with "read-only" access to internal
   * navigable sets. Query operations on the returned set "read through" to the
   * specified set, and attempts to modify the returned set, whether direct or
   * via its collection views, result in an
   * {@code UnsupportedOperationException}.
   *
   *
The returned navigable set will be serializable if the specified
   * navigable set is serializable.
   *
   * @param set the navigable set for which an unmodifiable view is to be
   *        returned
   * @return an unmodifiable view of the specified navigable set
   * @since 12.0
   */
  @GwtIncompatible("NavigableSet")
  public static <E> NavigableSet<E> unmodifiableNavigableSet(NavigableSet<E> set) {
    if (set instanceof ImmutableSortedSet || set instanceof UnmodifiableNavigableSet) {
      return set;
    }
    return new UnmodifiableNavigableSet<E>(set);
  }

  @GwtIncompatible("NavigableSet")
  static final class UnmodifiableNavigableSet<E> extends ForwardingSortedSet<E>
      implements NavigableSet<E>, Serializable {
    private final NavigableSet<E> delegate;

    UnmodifiableNavigableSet(NavigableSet<E> delegate) {
      this.delegate = checkNotNull(delegate);
    }

    @Override
    protected SortedSet<E> delegate() {
      return Collections.unmodifiableSortedSet(delegate);
    }

    @Override
    public E lower(E e) {
      return delegate.lower(e);
    }

    @Override
    public E floor(E e) {
      return delegate.floor(e);
    }

    @Override
    public E ceiling(E e) {
      return delegate.ceiling(e);
    }

    @Override
    public E higher(E e) {
      return delegate.higher(e);
    }

    @Override
    public E pollFirst() {
      throw new UnsupportedOperationException();
    }

    @Override
    public E pollLast() {
      throw new UnsupportedOperationException();
    }

    private transient UnmodifiableNavigableSet<E> descendingSet;

    @Override
    public NavigableSet<E> descendingSet() {
      UnmodifiableNavigableSet<E> result = descendingSet;
      if (result == null) {
        result = descendingSet = new UnmodifiableNavigableSet<E>(delegate.descendingSet());
        result.descendingSet = this;
      }
      return result;
    }

    @Override
    public Iterator<E> descendingIterator() {
      return Iterators.unmodifiableIterator(delegate.descendingIterator());
    }

    @Override
    public NavigableSet<E> subSet(
        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
      return unmodifiableNavigableSet(
          delegate.subSet(fromElement, fromInclusive, toElement, toInclusive));
    }

    @Override
    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
      return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive));
    }

    @Override
    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
      return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive));
    }

    private static final long serialVersionUID = 0;
  }

  /**
   * Returns a synchronized (thread-safe) navigable set backed by the specified
   * navigable set.  In order to guarantee serial access, it is critical that
   * all access to the backing navigable set is accomplished
   * through the returned navigable set (or its views).
   *
   *
It is imperative that the user manually synchronize on the returned
   * sorted set when iterating over it or any of its {@code descendingSet},
   * {@code subSet}, {@code headSet}, or {@code tailSet} views.
   {@code
   *
   *   NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
   *    ...
   *   synchronized (set) {
   *     // Must be in the synchronized block
   *     Iterator<E> it = set.iterator();
   *     while (it.hasNext()) {
   *       foo(it.next());
   *     }
   *   }}

   *
   *
or:
   {@code
   *
   *   NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>());
   *   NavigableSet<E> set2 = set.descendingSet().headSet(foo);
   *    ...
   *   synchronized (set) { // Note: set, not set2!!!
   *     // Must be in the synchronized block
   *     Iterator<E> it = set2.descendingIterator();
   *     while (it.hasNext())
   *       foo(it.next());
   *     }
   *   }}

   *
   *
Failure to follow this advice may result in non-deterministic behavior.
   *
   *
The returned navigable set will be serializable if the specified
   * navigable set is serializable.
   *
   * @param navigableSet the navigable set to be "wrapped" in a synchronized
   *    navigable set.
   * @return a synchronized view of the specified navigable set.
   * @since 13.0
   */
  @GwtIncompatible("NavigableSet")
  public static <E> NavigableSet<E> synchronizedNavigableSet(NavigableSet<E> navigableSet) {
    return Synchronized.navigableSet(navigableSet);
  }

  /**
   * Remove each element in an iterable from a set.
   */
  static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) {
    boolean changed = false;
    while (iterator.hasNext()) {
      changed |= set.remove(iterator.next());
    }
    return changed;
  }

  static boolean removeAllImpl(Set<?> set, Collection<?> collection) {
    checkNotNull(collection); // for GWT
    if (collection instanceof Multiset) {
      collection = ((Multiset<?>) collection).elementSet();
    }
    /*
     * AbstractSet.removeAll(List) has quadratic behavior if the list size
     * is just less than the set's size.  We augment the test by
     * assuming that sets have fast contains() performance, and other
     * collections don't.  See
     * http://code.google.com/p/guava-libraries/issues/detail?id=1013
     */
    if (collection instanceof Set && collection.size() > set.size()) {
      return Iterators.removeAll(set.iterator(), collection);
    } else {
      return removeAllImpl(set, collection.iterator());
    }
  }

  @GwtIncompatible("NavigableSet")
  static class DescendingSet<E> extends ForwardingNavigableSet<E> {
    private final NavigableSet<E> forward;

    DescendingSet(NavigableSet<E> forward) {
      this.forward = forward;
    }

    @Override
    protected NavigableSet<E> delegate() {
      return forward;
    }

    @Override
    public E lower(E e) {
      return forward.higher(e);
    }

    @Override
    public E floor(E e) {
      return forward.ceiling(e);
    }

    @Override
    public E ceiling(E e) {
      return forward.floor(e);
    }

    @Override
    public E higher(E e) {
      return forward.lower(e);
    }

    @Override
    public E pollFirst() {
      return forward.pollLast();
    }

    @Override
    public E pollLast() {
      return forward.pollFirst();
    }

    @Override
    public NavigableSet<E> descendingSet() {
      return forward;
    }

    @Override
    public Iterator<E> descendingIterator() {
      return forward.iterator();
    }

    @Override
    public NavigableSet<E> subSet(
        E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) {
      return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet();
    }

    @Override
    public NavigableSet<E> headSet(E toElement, boolean inclusive) {
      return forward.tailSet(toElement, inclusive).descendingSet();
    }

    @Override
    public NavigableSet<E> tailSet(E fromElement, boolean inclusive) {
      return forward.headSet(fromElement, inclusive).descendingSet();
    }

    @SuppressWarnings("unchecked")
    @Override
    public Comparator<? super E> comparator() {
      Comparator<? super E> forwardComparator = forward.comparator();
      if (forwardComparator == null) {
        return (Comparator) Ordering.natural().reverse();
      } else {
        return reverse(forwardComparator);
      }
    }

    // If we inline this, we get a javac error.
    private static <T> Ordering<T> reverse(Comparator<T> forward) {
      return Ordering.from(forward).reverse();
    }

    @Override
    public E first() {
      return forward.last();
    }

    @Override
    public SortedSet<E> headSet(E toElement) {
      return standardHeadSet(toElement);
    }

    @Override
    public E last() {
      return forward.first();
    }

    @Override
    public SortedSet<E> subSet(E fromElement, E toElement) {
      return standardSubSet(fromElement, toElement);
    }

    @Override
    public SortedSet<E> tailSet(E fromElement) {
      return standardTailSet(fromElement);
    }

    @Override
    public Iterator<E> iterator() {
      return forward.descendingIterator();
    }

    @Override
    public Object[] toArray() {
      return standardToArray();
    }

    @Override
    public <T> T[] toArray(T[] array) {
      return standardToArray(array);
    }

    @Override
    public String toString() {
      return standardToString();
    }
  }
}


text:
EPW Home
Discussion Maps
Report from the States
Can India's Patriotism Be Built on Accepting Differences?
There are many avatars of nationalism premised on very different understandings of "the idea of India." This demands a patriotism premised on an inclusive love of all our peoples, a commitment to their integral welfare, and faith in an idea of India with its multicultural, pluri-religious society as less a nation state than a multi-nation-state in the making. The jury is still out on whether this will be a failed experiment or a prophetic sign of the future for a world still struggling to cope with diversity, not quite able to accept the different "other" and the legitimacy of the difference.
There is an obvious contradiction between nationalism and internationalism, and yet they prevail together: national chauvinism at home and international globalism abroad. Any response to such anomalies, particularly in a rapidly changing situation, must be critically assessed lest we pour new wine that cannot be contained in "old wine skins" and so burst the skins and spill the wine.
Some Issues and Clarifications
Nationalism and patriotism: Nationalism as devotion to one's country easily becomes exclusive: my country first, right or wrong. When national interests clash with those of others, nationalism inevitably becomes antagonistic and hostile to other countries and results in violence and war on the world stage, rather than dialogue and tolerance, leading to a compromise for the greater common good and peace. Such a chauvinist nationalism thrives on finding or creating national enemies, whether without or within the country. However, patriotism as a non-exclusive love of one's country must be premised on self-confidence and openness to other countries without fears and suspicions. This is a far better and more constructive basis for an inclusive society, both national and international, than jingoist exclusiveness.
An intensification of trade and finance, facilitated by media and migration, results in an imploding globalising world. The consequent rapid and radical change brings back uprooted people who seek lost roots in localisation.
Political leaders often find it convenient, even profitable to confuse nationalism and patriotism so as to mobilise people on the basis of a politics of hate, masquerading as nationalism, rather than painstakingly cultivating patriotism as a love for one's people that reaches out to other peoples as well. Such patriotism is a far more viable basis for a national community in pursuit of the common good, rather than the social contract of Thomas Hobbes (1985) which grounds our politics today in the self-interest in individual or group, national or international community. This is what plagues communities in our country and nations at the United Nations, despite so much pious rhetoric.
Imagining a nation: Nationalism is the ideology that drives this process of nation-building: "Nationalism is not the awakening of nations to self-consciousness; it invents nations where they do not exist". (Gellner 1964: 169) It was a powerful idea but one that imposed a uniformity (cultural, religious, and economic) with a brutal aggression subsuming lesser communities into the dominant one. The last century has witnessed horrendous clashes of aggressive nationalisms in Europe, engulfing the world in two great wars. However, we have not as yet managed to exorcise such nationalisms from our world.
Moreover, when religion is used to construct this national identity, then religion is politicised into an "ideology" and vice versa and nationalism is sacralised into a "religion"—in other words, a nationalised religion and a sacred nationalism. This entanglement of religion and politics inevitably becomes explosive, as religion becomes fundamentalist and exclusive; and politics becomes extremist and violent. No religious tradition has been an exception to such political manipulation, even those purported to be tolerant and non-violent. Only the expression of the violence varies.
When there are many imagined communities in a single polity, we have the multi-nation state, very different and far more problematic than the original European nation state. Moreover, a pluri-religious, multicultural society demands a correspondingly adequate ideological construct—a pluralism for a multicultural, pluri-religious multi-nation federal state, not the nationalism of the unitary nation state. But first, it must be a civil state before becoming political one.
Unhealed, wounded histories: In the states of the Indian republic, everyone belongs to some minority, depending on which way the cake is cut. Religious differences are foregrounded to proxy for the far more corrosive inequities of status, between castes and classes, and the hegemony of elites over the masses. At present there is a deliberate polarisation that pitches religious communities against each other only to the advantage of their instigating leaders. This is what the freedom struggle tirelessly strove to contain and resolve, and it seemed to have succeeded for a while in the aftermath of the trauma of partition and the murder of Mahatma Gandhi by Hindutvavadi fanatics. Fanaticism readily overtakes religious nationalism and precipitates a world of terror and counterterror by state and non-state actors.
Ashis Nandy (1994) distinguishes all such nationalism from a patriotism founded on humanism and universalism. Negative emotions and intellectual prejudice can be powerful mass mobilisers against powerless scapegoats but they are always very bad counsellors. It can eventually only bring strife and struggle not just between nations but within a national community as well. The human price for such a dangerous folly is incalculable, and the Indian subcontinent is a shocking witness to this.
Unity in diversity: The challenge of unity in diversity is to recognise and guarantee both equal dignity, founded on human rights and committed to enforcing equitable rights for all individuals and unique identity for every individual person and each human community, premised on collective rights and responsibility for ensuring the cultural identity of each group (Heredia 2007). Indeed,
"The national movement fully recognized the multifaceted diversity of the Indian people. That India was not yet a developed or structured nation, but a nation-in-the-making, was accepted and made the basis of political and ideological work and agitation." (Chandra et al 1988: 555)
Negating the identity and dignity of a subordinate group sets off a backlash and in return provokes a response from the dominant group, trapping both in a rising spiral of violence. This is an alarming reality in this subcontinent.
The Freedom Movement
Perspectives on Indian nationalism: There was an inherent ideological tension in the freedom struggle: between a vision of an idealised ancient past prioritising religious and cultural revivalism, and a dream of a new future centred on social transformation and concern. Gandhi's swaraj privileged even the most marginalised Indian but is now an ideal served more in the breach than in fact. The dominant Nehruvian consensus of the early independence era was premised on the dream of a new future, but it never could quite contain or defuse the lure of the first. Already, then, in the freedom struggle Indian nationalism had been contested by opposing constituencies with their antagonistic ideologies, seeking to co-opt it for their own partisan purposes.
Hindu nationalism has had a subterranean existence even when it has been marginalised in national politics. The rejection of the Hindu Code Bill in 1954 in spite of Nehru's support by a Congress dominated Parliament (which precipitated the resignation of Ambedkar) is evidence of this. A modified form of the bill was accepted later in 1955.
Rabindranath Tagore rejected a narrow aggressive nationalism, for a broad inclusive patriotism. Under Gandhi's leadership, the Indian freedom movement struggled to convert divisive debates into integrating dialogues, to transform exclusive identities into inclusive ones, to change hostile controversy into empathetic consensus. Both Muslim and Hindu nationalism on the subcontinent betrayed this ideal in 1947, and after the murder of Gandhi by a member of a Hindu nationalist organisation, Hindu nationalism was convincingly rejected, at least for a while. In the years after independence, Congress itself in effect abandoned Gandhi's ideals, and compromised the democratic institutions that Nehru had nurtured, thus opening the door for a Hindu nationalist authoritarian revival which now occupies a majoritarian space.
Caste and class hegemonies: Antonio Gramsci (1996) has shown how nationalism can also become a hegemony of the dominant classes over subordinate ones. Dominant religious groups too use nationalism to suppress or assimilate other groups. Such religious nationalisms are inevitably resisted by secular and other minority religious groups, and the confrontation often spins out of control. Pankaj Mishra correctly traces the rise of Hindutva (Savarkar 1989) to Giuseppe Mazzini's nationalism, premised on a selective historical memory, for a restoration of the glory that had been destroyed by barbarian invasions.
"an acute consciousness of the defeat and humiliation of ancestors, an awakening to historical pain, and a resolve to rectify the wrongs of the past with superhuman efforts at power and glory in the present and future. The latter include self-sacrifice for the greater cause of the nation, as Modi has repeatedly exhorted after unleashing demonetisation. An intellectual genealogy of Hindu nationalism, however, reveals that there is nothing uniquely 'Hindu' about it." (Mishra 2017)
This is the Hindutva that the Rashtriya Swayamsevak Sangh has adopted as its commanding ideology, but without the militant rationalism of Savarkar.
It is important to distinguish Hindutva as a political ideology from Hinduism as a religious faith tradition. However, this distinction has more validity for a liberal reformist Hinduism, which identifies itself as a religious faith, embodied in a religio-cultural tradition, not extremist Hindutva that politicises it for partisan purposes.
Once we begin to deconstruct and situate these traditions in their social context, we find a substantial continuity in the hegemonic project of the modern Hindutva agenda and the traditional savarna sensitivities—the former becomes very much a radicalised and politicised extension of the latter.
Ascendant Hindu nationalism: We need an effective and real equity that allows for diversity without inequity, whether sociocultural or politico-economic. This demands a negation of the idea of a unilinear social evolution within a single national tradition in which all communities are co-opted and merged. However, subaltern and minority quests for equality and justice must not sacrifice social identity and human dignity, least it be co-opted and subverted. This is precisely the dominant group's agenda to retain their hegemony: divide and rule.
But for this we need first to break out of the prison of our present consciousness and transcend the categories that constrain us there. We need to imagine another kind of community and invent a newer set of traditions. It is not as if subaltern alternatives have all the answers for such an enterprise, but they do represent a challenging horizon of revolt and revolution, which can fuse with others to construct the identities and the ideologies for this brave new world.
Someday, people may be able collectively to remake our founding myth into one more adequate to our new world view. For liberation seekers, history can be made to follow myth (Nandy 1983: 63).
Idea of India
Common consciousness: In the Indian subcontinent there was no real consciousness of a common national identity or a quest for nationhood, until the nationalist movement created such an awareness. It was a nationhood premised on an overarching civilisational commonality in pursuit of their shared tryst with destiny. The dominant inspiration of our freedom struggle was against the colonial Raj. However, independence as a nation was to celebrate an inclusive political unity in our rich cultural diversity and our religious pluralism. The freedom movement had constructed a new idea of India for both governance and civil society.
Tagore's concerns: Tagore's (1935) idea of India was distinctly syncretic. He imagined a civilisation "embedded in the tolerance encoded in various traditional ways of life in a highly diverse plural society" (Nandy 1994: x–xi), welcoming all peoples and cultures.
Tagore was keenly aware of dangers of nationalist chauvinism and sharply critical of how European nationalism had turned 20th century Europe into a "civilisation of power" (Tagore 1996: 425). After encountering it in Japan, he was apprehensive of the militant nationalism in India and the freedom movement. However, he remained a critical participant yet always a much valued and respected one. The genius of India he elaborated in terms of a spirit of cooperation: "Let our civilisation take its firm stand upon its basis of social cooperation and not upon that of economic exploitation and conflict" (Tagore 1996: 465).
Gandhi's swaraj: "Civilisation is that mode of conduct which points out to man the path of duty" (Gandhi 1909). The basis of his swaraj then could not be just rights, it had to be duties as well. It had to be a person's rule over one's self in this path of duty, before it could be the collective rule over one's country. His idea of India is bold and challenging, a utopia as a reference point to serve as a critique of contemporary society. He incisively rejects Western civilisation built on colonial imperialism, industrial capitalism, and rationalist materialism and then presents his alternative for India:
swaraj: beginning with the individual ruling oneself in responsible freedom, as the foundation for a people governing themselves as a society;
swadesh: the local neighbourhood community, as the node in a network of oceanic circles that over-lapped and spread out in its ever widening embrace;
satya: as the many-sided (anekantavad) experiential (not speculative) truth pursued with ahimsa and operationalised in satyagraha.
Gandhi was a patriot who wanted "Indian nationalism to be non-violent, anti-militaristic and therefore a variant of universalism" (Nandy 1995:14). He wrote: "By patriotism I mean the welfare of the whole people." (Gandhi 1909) Later he would affirm: "my patriotism is for me a stage on my journey to the land of freedom and peace," which was always inclusive (Gandhi 1924: 112). Indeed, Gandhi was an internationalist and patriot, not a narrow nationalist and chauvinist.
He feared India might succeed in getting independence (swatantrata) from the British for the political and other elites and fail in achieving freedom (swaraj) or rather integral self-rule (purna swaraj). In Gandhian terms, nationalism meant going the distance from swatantra to swaraj: to fulfil one's duties not merely affirm one's rights. This was true freedom that finally led to moksha via ahimsa and the seva-marg. This was not just an economic–political agenda, but a sociocultural one for a civilisational revolution. Today we find his fears have proven all too prescient.
Nehru's discovery: Nehru saw India not in exclusive terms, but rather as a multicultural and pluri-religious civilisation that was to be the defining basis for its national identity (Nehru 1946).
Nehru traces this right back to the meeting between the Aryans and the Dravidians, and later between the settlers and the Iranians, Greeks, Parthians, Bactrians, Scythians, Huns, Turks (before Islam), early Christians, Jews (and) Zoroastrians. (Bhattacharjee 2015: 21)
The basis of such a synthesis was the "astonishing inclusive capacity of Hinduism" (Nehru 1946: 74). This "discovery of India" that Nehru, the enlighted rationalist, made was not bound by religious roots or defined by specific practices (Nehru 1946).
Ambedkar's republic: For Ambedkar, Buddhism originally defined India, but through the ages, Buddhism was displaced by a Hinduism that was corrupted beyond redemption by Brahminism. He hoped that his neo-Buddhist Navayana would restore the original Buddhist ideal and be the foundation of the newly constituted Republic of India.
The constituent assembly debates, over which Ambedkar presided, hammered out the compact expressed in the Constitution of India. This represented the broad consensus of the movement led by the Indian National Congress. Despite differences and disagreements, this was not a pragmatic political compromise lacking conviction and commitment, but a compact based on mutual trust to allow for various underlying approaches and perspectives that were to be sorted out with sensitivity and understanding.
The constituent assembly left a fertile ground for conflict between the political compulsions of the government and the constitutional propriety of the courts. This area of constitutional propriety and political demands for rights has increasingly become a tug-of-war between the legislature and the judiciary.
Contesting the idea of India: The idea of India in our Constitution cannot be forced into a sectarian, communal interpretation without inflicting violence upon its basic structure. The earlier governments failed to do what they were elected to do—protect and promote the constitutional rights of citizens and implement the constitutional agenda on the integral development of society and progress for all its citizens. Inevitably, this has precipitated the present crisis.
However, today, this idea of India is being contested and contradicted as never before, to the point of threatening a reversal, by saffron-clad politicians, brown sahibs, neo-liberals, and free-marketeers. The 2014 general election was an alarming warning of the real and present danger of our republic being hijacked by an aggressive Hindu majoritarianism and populism. The 2019 general election may well be our last chance to reverse this.
Constitutional Propriety
Constitutional democracy: A critical and alert citizenry can best protect constitutional democracy from lapsing into populist democracy (Béteille 1999). This is an enormous challenge. Formal statutory rights are made justiciable, not the Directive Principles of State Policy, which mandate the pursuit of social and economic democracy. This means countering the entrenched institutions of caste and community, of patriarchy and landlordism, and to do this within the democratic framework of the Constitution.
Such divisions undermine a fraternal community, which "without fraternity, equality, and liberty will be no deeper than coats of paint" (Béteille 1999: 339) and society becomes divided into "beasts of burden" and "beasts of prey." (Béteille 1999: 340) The backlash from the liberal democracies of the West is a witness to this, with the ethnocentric politics of exclusion overtaking a precarious liberalism. This is surely happening in India as well.
Populist democracy: In contrast to a constitutional democracy, a populist one has little patience with constitutional restraints of checks and balances or due process. For "populist politics is often constructed from a blend of nativism, bigotry, grandiosity, and coarse speech" (Coll 2017). It depends on a charismatic leader mobilising a mass movement for populist interests. Electoral democracies, if not committed to constitutional propriety and morality, do produce such "democratic dictatorships."
The majority is privileged, while minorities are marginalised. Dissenters become non-people, and the poor and underprivileged are deprived of voice and choice; they become invisible. This is a prescription for disaster and eventually, after much drift and obfuscation, leads to the strong leader syndrome. Such leaders undermine democratic institutions and eventually exit leaving a trail of broken promises and belied hopes.
In stark contrast, a constitutional democracy pursues constitutionally defined political goals and ideals within a regime of rights, with due process and constitutional propriety. This is the real challenge for our democracy—to follow through and complete the social revolution begun with the freedom struggle, promulgated in the Constitution, and contextualised in the Directive Principles.
Nation without Nationalisms
Neoliberalism and saffronisation: The crisis of neo-liberalism is world wide, thanks to economic, political, neo-liberal globalisation. Thomas Piketty challenges the conventional wisdom of neo-liberal economists to demonstrate how the system reproduces and increases inequalities (Piketty 2014). Class strata are thus increasingly inherited and ascribed rather than merited, as with caste. In India, this is reinforced by the traditional caste hierarchy to produce an upper class/caste hegemony. There is clearly a connection between "saffronisation and liberalisation" (Ahmad 1996: 1329) and the predatory capitalism that the latter has spawned (Lele 1995: 38) The conservative free-market rightists and "saffron neo-liberalism" (Teltumbde 2014) make willing bedfellows.
Today caste, gender, ethnicity, and region have become fault lines. But most acutely, it is the religious divide of the majority–minority that is being aggressively exploited to consolidate vote banks for electoral gains, while communal polarisation consolidates extremist leadership. Despite all the pious talk to the contrary from all sides, collective violence still periodically rips apart the fabric of our society, leaving wounded people in broken communities, crying out for relief and justice that is mostly, if not often, denied.
Shockingly, while the government projects India as a rising global power, the World Economic Forum (2017) says that "India with a score of only 3.38, ranks 60th among the 79 developing economies on the Inclusive Development Index, despite the fact that its growth in GDP per capita is among the top 10 and labour productivity growth has been strong." Further, in the list of the least trusted institutions in 28 countries, the media in India ranks second after Rupert Murdoch's Australia![1] Nationalism has become the battle cry to neuter all opposition and all dissenters. Many see this as an undeclared Emergency.
Without a media watchdog, there can be no government accountability. Without a right to free speech and public dissent, there can be no substantive democracy. Without a shared solidarity, there can be no nation. We are now experiencing the debilitating contradiction in terms of a "nationalism without a nation in India" (Aloysius 1997) from which only scoundrels benefit! Hindu Rashtra is patently the subtext in the present context. This is surely a betrayal of the national freedom movement.
Future challenges: There is an urgent need for people of goodwill to come together; not just on minority rights of one's own community, but on the common ground of our human rights, statutorily affirmed as fundamental rights in the Constitution. However, to be credible we must, at the same time, emphasise our fundamental duties as affirmed in the same Constitution. Here, the role of family and fiduciary institutions is crucial.
Today, this is being challenged by the neo-liberalism unleashed by a global free market that promises liberty and equality but results in upper-class dominance and lower-class subordination. Further, with saffronisation, caste hierarchy and class stratification become mutually reinforcing of such subordinations and inequalities. Majoritarianism pretends to pursue democratic ideals, but marginalises the minorities and oppresses the underprivileged across the board. Nationalism is the ideology used to legitimise this hegemony, and to co-opt diverse and unequal communities and classes into a majoritarian cultural–political uniformity.
India's Democratic Saga
Projecting possibilities: There has been a continuing advance of an aggressive, majoritarian, religious right, as also of a defensive, minority, religious fundamentalism among both the majority and the minorities in this land. These are but mirror images of each other. They feed on each other and spill over into violence.
We need to recapture the open spaces that we have lost to communal polarisation and partisanship. This is the common ground we must recover so we can move together to a higher ground together. For this, civic activism must transcend identity politics, whether of caste or religion, and reach beyond to all other disadvantaged groups, whatever the grounds of their discrimination may be. It must be a process that begins at the grass roots, and but is scaled up. But it must also be accompanied with a top–down facilitation as much as it needs a bottom–up activation.
Culture of terror: Minority rights for a community must be compatible with fundamental rights in the Constitution. This requires a negotiation between national representatives and community ones. The grass roots and neighbourhood committees are a viable place to start. But when the representatives themselves become stridently extremist, they silence the very voices within their respective communities that might make for a sustainable social compact. A viable context for this requires an understanding of "human rights in popular consciousness" (Anderson and Guha 1998: 5), as also a sensitivity to minority cultures and their vulnerabilities.
Our constitutional vision is now under strain. We must draw on our tradition of public reasoning to rescue our democracy. The only remedy for a failing democracy is a more effective democracy.
We must build a civil society supportive of our constitutional vision—one that is decent and just, fair and egalitarian, participative and inclusive—beginning with our personal lives first, and building local communities that spread their ripple effect like Gandhi's oceanic circles. We need a patriotism that will make Indians a happy people, not a nationalism that pretends to great power status. In other words, an India for all Indians, especially the last and the least, the marginalised and the outcaste.
Neo-liberal globalisation sits comfortably with religious nationalisms except when their violence disrupts free markets. It sharpens inequalities in a diverse but imploding world and then attempts to contain the violent spill over with counter-violence, where leaders profit and people lose. We need a new social ethic, an inclusive religious vision, and an open spirituality.
There are many avatars of nationalism premised on very different understandings of "the idea of India." But not all can comprehend and embrace the tryst with destiny we made years ago in our struggle for freedom. This demands a patriotism premised on an open-ended, inclusive love of all our peoples, a commitment to their integral welfare, and faith in an idea of India with its multicultural, pluri-religious society. The jury is still out on whether this will be a failed endeavour or a prophetic experiment for the future for a world still struggling to cope with diversity, not quite able to accept the different "other" and the legitimacy of the difference.
If this idea of India falters, it may well prejudice the viability of a multicultural, pluri-religious society in a nation state for the rest of the world's community of nations.
This is an abridged version of the keynote address given at St Andrew's College, Mumbai on 11 February 2017.
[1] See the list of "The Least Trusted Institution in 28 Countries": https://assets.weforum.org/editor/yFyo00XCZGPo8N5jQbG7u425vc4HL5neDCJKcODkyOI.PNG
Ahmad, Eijaz (1996): "In the Eye of the storm: The Left Chooses", Economic & Political Weekly, Vol 31, No 22, pp 1329-43, https://www.epw.in/journal/1996/22/special-articles/eye-storm-left-chooses.html.
Aloysius, G (1997): Nationalism without a Nation In India, Delhi: Oxford University Press.
Anderson, Michael R and Sumit Guha (1998): "Introduction," Changing Concepts of Rights and Justice in South Asia, Michael R, Anderson and Sumit Guha (eds), Delhi: Oxford University Press.
Bhattacharjee, Manash (2015): "Nehru and the Question of National Identity," Economic & Political Weekly, Vol 50, No 16, pp 20–23.
Béteille, Andre (1999): "Citizenship, State and Civil Society," Economic & Political Weekly, Vol 34, No 36, pp 2566–91.
Chandra, Bipan et al (1988): India's Struggle for Independence, 1857-1947, New Delhi: Viking.
Coll, Steve (2017): "The Strongman Problem, From Modi to Trump," New Yorker, 18 January, https://www.newyorker.com/news/daily-comment/the-strongman-problem-from-modi-to-trump.
Gandhi, Mohandas K (1909): Hind Swaraj or Indian Home Rule, 1908, Ahmedabad: Navjivan Press.
— (1927): Young India, 1924-1926, New York: Viking Press.
Gellner, Ernest (1964): Thought and Change, London: Weidenfeld and Nicolson.
Gramsci, Antonio (1996): Selections from the Prison Notebooks, Quintin Hoare and Geoffrey Nowell Smith (eds and trans), Hyderabad: Orient Longman.
Heredia, Rudolf C (2007): Changing Gods: Rethinking Conversion in India, New Delhi: Penguin.
Hobbes, Thomas (1985): Leviathan, (1651), Crawford Macpherson B (ed), London: Penguin Books.
Lele, Jayant (1995): Hindutva: The Emergence of the Right, Madras: Earthworm Books.
Mishra, Pankaj (2017): "Hindu Nationalism Is More Italian and Christian than Sonia Gandhi," Times of India, 22 Jan, pp 22, http://timesofindia.indiatimes.com/home/sunday-times/all-that-matters/hindu-nationalism-is-more-italian-and-christian-than-sonia-gandhi/articleshow/56711905.cms.
Nandy, Ashis (1983): Intimate Enemy, New Delhi: Oxford University Press.
— (1994): The Illegitimacy of Nationalism, New Delhi: Oxford University Press.
— (1995): Creating a Nationality: The Ramjanmabhumi Movement and the Fear of the Self, New Delhi: Oxford University Press.
Nehru, Jawaharlal (1946): Discovery of India, Calcutta: Signet Press.
Piketty, Thomas (2014): Capital in the Twenty-first Century, Massachusetts: Harvard University Press.
Savarkar, Vinayak D (1989): Hindutva: Who Is a Hindu?, sixth ed, New Delhi: Bharati Sahitya Sadan.
Tagore, Rabindranath (1935): Bharatvarsher Itihas, 1902, Calcutta: Vishwa-Bharati, pp 1–15.
— (1996): "Nationalism," 1917, English Writings of Rabindranath Tagore, Vol II, Sisir Kumar Das (ed), New Delhi: Sahitya Akademi.
Teltumbde, Anand (2014): "Saffron Neoliberalism," Economic & Political Weekly, Vol 49, No 31, pp 10–11.
World Economic Forum (2017): "The Inclusive Growth and Development Report 2017," http://www3.weforum.org/docs/WEF_Forum_IncGrwth_2017.pdf.
Image Courtesy: Modified. Wikimedia Commons/ Yana Forget/ CC-BY-SA-3.0
Where is Democracy?
Creating a '21st Century World': Will Metro Systems Create 'Smart Cities'?
By inviting private capital and adopting an urbanisation plan that caters to the affluent, India's upcoming metro systems will not be a public good aimed for the masses.
NRC, Assam, and What Makes a Citizen: Navigate Our Snakes-and-Ladders Citizenship Guide
Were Gandhi's Practices Any Different From His Writings On Caste?
Marginalised Narratives of the Indian Freedom Movement
More importance should be given to recovering the stories of marginalised people who were involved in the struggle for independence.
Gandhi, Nehru and Ambedkar: Three Formulations of 'Real India'
Can Religion be Separated from State? Use this Tool to Find Your Way to a 'Secular State'
Can 'Castelessness' Fix Caste?
Prisoners' Rights and Values of Indian Democracy: An Introduction
In India, the debates around prison reforms and rights of prisoners have been very limited. Through our three-part series we seek to initiate a debate towards prisoners' civil and political rights....
What Kind of Nationalism Do We Need Today? Exploring Tagore on Nationalism
Tagore's brand of nationalism is fundamentally rooted in the question of what it means to be human.

redpajama_set_name: RedPajamaCommonCrawl


text:
Q: FFMPEG cannot read files in /tmp/ on Heroku I created a nodejs application hosted on heroku which uses imagemagick. I am doing this operation:
require('child_process').exec(`convert -quiet -delay 1 output.avi ${gif}`);

This should convert output.avi (which is present) to a gif file. In this case, gif is "/app/temp/gifs/xstrycatdq.gif". This command works perfectly on my local windows machine. As I use the path module to get a variable with path.joinand __dirname.
I have installed heroku buildpack:

*

*https://github.com/ello/heroku-buildpack-imagemagick
The error I am receiving is:
Command failed: convert -quiet -delay 1 output.avi /app/temp/gifs/xstrycatdq.gif
convert: DelegateFailed `'ffmpeg' -nostdin -v -1 -vframes %S -i '%i' -vcodec pam -an -f rawvideo -y '%u.pam' 2> '%Z'' @ error/delegate.c/InvokeDelegate/1919.
convert: UnableToOpenBlob `magick-93R4VJcemPz0z1.pam': No such file or directory @ error/blob.c/OpenBlob/2705.
convert: NoImagesDefined `/app/temp/gifs/xstrycatdq.gif' @ error/convert.c/ConvertImageCommand/3257.

It seems that the /tmp/ directory can't be written to or anything. I also tried to mkdir /tmp/ but bash tells me that this dir already exists.
I have also tried changing the imagemagick's temp directory with the environment variable by doing export MAGICK_TMPDIR="temp".
Any help?
Edit: The variables are now absolute.

A: Are you sure it's not an issue of permissions? Can you write a simple text file to /app/temp? Is nothing is being read or written at all, it sounds like an issue of permissions. Maybe it's not necessarily a protection design of ImageMagick, but rather heroku or your programming environment?
This directory you're trying to use, it's special in that it contains corrupt or incomplete files - it may have special protections or guards in place, when certain software is running. temp directories are typically designed (or assumed) to be protected from user interference, as they are only to be used and worked with, by the program itself - not the user's commands of the program.
This question is similar to yours, it might be able to help you.

redpajama_set_name: RedPajamaStackExchange


The gradual change in the level of the Oceans and Seas.
The rate that sea level is changing is called the trend in sea level. The sea level trend is presented as the height of change per year for example as mm per year.
The amount of sea level rise has been determined globally from long term tide gauge records. Globally, sea level rise has been reported at an average rate of 1.8 mm per year for the past century and 1.9 mm/year from 1961 up to 2009.
Since 1993, measurements from satellite radar altimeters have allowed estimates of global mean sea level. These measurements are continuously calibrated against a network of tide gauges. When seasonal and other variations are subtracted, they allow estimation of the global sea level trend.
The global sea level trend from the beginning of satellite measurements in 1993 up to 2014 is 3.2 mm/year. The sea level trend for the period 1993 to 2009 calculated from tide gauge records is 2.8 mm/year very close to the satellite altimeter global sea level trend.
In Australia, the trend in sea level has been calculated from long term averaged tide gauge records as 1.2 mm/year.
The two longest tide gauge records at Fort Denison in Sydney harbour and at Fremantle in Western Australia indicate a slightly higher trend of 1.4 mm/yr at Fort Denison and a lower trend of 0.9 mm/yr at Fremantle. Both of these Australian determinations may include changes in the reference datum relative to the International Frame (IRF) due to the vertical movement of land.


text:
Sociologists Believe Shrieking Left-Winger Who Is Throwing Things May Be Expressing Disagreement
27k Share
PORTLAND, OR—Kevin Drake got a surprise. While discussing politics with friends, he was suddenly accosted by a left-winger who started shrieking at him and throwing things, including a milkshake and also a brick. While Drake's friends were startled, Drake had dealt with left-wingers before and correctly identified the behavior as an attempt to communicate.
"He's expressing that he disagreed with something I said," Drake told his friends. He then repeated what he had said, observing when and how much the left-winger shrieked and got violent to try and determine what it was he disagreed with. When they found the opinion that set the left-winger off, though, they were uncertain what to do next. "We didn't understand why he disagreed, and when Kevin tried to ask him, he only shrieked louder and threw more things."
"While the far-left can successfully communicate what they disagree with by using noise and tossing objects," explained Dr. Robert Powell, a leading sociologist, "coherently explaining why they disagree with a view is unfortunately beyond their limited communication skills." When the left-winger's trigger has been identified, Dr. Powell said there are two options. One is to avoid saying the thing the left-winger disagrees with so he'll remain calm. The other is to hold him down and say what he disagrees with over and over in his face and then harvest his tears to later drink from a tumbler.
There are 2 comments on this article.
Nation's Progressive Christians Applaud Hell For Being So Inclusive
Discover God's Will For Your Life With This One Weird Trick!
Second Democratic Debate Turns Into Tense Minimum Wage Bidding War
Report: President Trump's Self-Approval Rating At All-Time High
Winning: Trump Walks Onstage Holding Hunter Biden's Laptop
Elizabeth Warren Promises To Cure Smallpox
Trump Tells Kim Jong Un He Just Wants To Be 'Pursued'
Biden To Save Taxpayers Nearly 30% By Selecting Female VP