text:
package java.util

import java.{lang => jl}
import java.io.Serializable

import scala.language.implicitConversions

import scala.annotation.tailrec

import scala.collection.JavaConversions._

object Collections {

  final lazy val EMPTY_SET: Set[_] = {
    unmodifiableSet(
      new AbstractSet[Any] with Serializable {
        override def size(): Int = 0

        override def iterator(): Iterator[Any] = emptyIterator[Any]
      })
  }

  final lazy val EMPTY_LIST: List[_] = {
    unmodifiableList(
      new AbstractList[Any] with Serializable with RandomAccess {
        override def get(index: Int): Any =
          throw new IndexOutOfBoundsException(index.toString)

        override def size(): Int = 0
      })
  }

  final lazy val EMPTY_MAP: Map[_, _] = {
    unmodifiableMap[Any, Any](
      new AbstractMap[Any, Any] with Serializable {
        override def entrySet(): Set[Map.Entry[Any, Any]] =
          EMPTY_SET.asInstanceOf[Set[Map.Entry[Any, Any]]]
      })
  }

  private lazy val EMPTY_ITERATOR: Iterator[_] =
    new EmptyIterator

  private lazy val EMPTY_LIST_ITERATOR: ListIterator[_] =
    new EmptyListIterator

  private lazy val EMPTY_ENUMERATION: Enumeration[_] = {
    new Enumeration[Any] {
      def hasMoreElements: Boolean = false

      def nextElement(): Any =
        throw new NoSuchElementException
    }
  }

  // Differs from original type definition, original: [T <: jl.Comparable[_ >: T]]
  def sort[T <: jl.Comparable[T]](list: List[T]): Unit =
    sort(list, naturalComparator[T])

  def sort[T](list: List[T], c: Comparator[_ >: T]): Unit = {
    val sortedList = list.sorted(c)
    list match {
      case list: RandomAccess => copyImpl(sortedList.iterator, list)
      case _                  => copyImpl(sortedList.iterator, list.listIterator)
    }
  }

  def binarySearch[T](list: List[_ <: jl.Comparable[_ >: T]], key: T): Int =
    binarySearchImpl(list, (elem: Comparable[_ >: T]) => elem.compareTo(key))

  def binarySearch[T](list: List[_ <: T], key: T, c: Comparator[_ >: T]): Int =
    binarySearchImpl(list, (elem: T) => c.compare(elem, key))

  @inline
  private def binarySearchImpl[E](list: List[E], compareToKey: E => Int): Int = {
    def notFound(insertionPoint: Int): Int = {
      -insertionPoint - 1
    }

    @tailrec
    def binarySearch(lo: Int, hi: Int, get: Int => E): Int = {
      if (lo < hi) {
        val mid = lo + (hi - lo) / 2
        val cmp = compareToKey(get(mid))
        if (cmp == 0) mid
        else if (cmp > 0) binarySearch(lo, mid, get)
        else binarySearch(mid + 1, hi, get)
      } else {
        notFound(lo)
      }
    }

    list match {
      case _: RandomAccess =>
        binarySearch(0, list.size, list(_))

      case _ =>
        def getFrom(iter: ListIterator[E])(index: Int): E = {
          val shift = index - iter.nextIndex
          if (shift > 0)
            (0 until shift).foreach(_ => iter.next())
          else
            (0 until -shift).foreach(_ => iter.previous())
          iter.next()
        }
        binarySearch(0, list.size, getFrom(list.listIterator))
    }
  }

  def reverse(list: List[_]): Unit =
    reverseImpl(list)

  @inline
  def reverseImpl[T](list: List[T]): Unit = {
    val size = list.size
    list match {
      case list: RandomAccess =>
        for (i <- 0 until size / 2) {
          val tmp = list(i)
          list(i) = list(size - i - 1)
          list(size - i - 1) = tmp
        }

      case _ =>
        val it1 = list.listIterator()
        val it2 = list.listIterator(size)
        for (i <- 0 until size / 2) {
          val tmp = it1.next()
          it1.set(it2.previous())
          it2.set(tmp)
        }
    }
  }

  def shuffle(list: List[_]): Unit =
    shuffle(list, new Random)

  def shuffle(list: List[_], rnd: Random): Unit =
    shuffleImpl(list, rnd)

  @inline
  def shuffleImpl[T](list: List[T], rnd: Random): Unit = {
    val scalaRnd = scala.util.Random.javaRandomToRandom(rnd)
    val shuffledList = scalaRnd.shuffle(list.toSeq)
    list match {
      case list: RandomAccess => copyImpl(shuffledList.iterator, list)
      case _                  => copyImpl(shuffledList.iterator, list.listIterator)
    }
  }

  def swap(list: List[_], i: Int, j: Int): Unit =
    swapImpl(list, i, j)

  @inline
  private def swapImpl[E](list: List[E], i: Int, j: Int): Unit = {
    list match {
      case list: RandomAccess =>
        val tmp = list(i)
        list(i) = list(j)
        list(j) = tmp

      case _ =>
        val it1 = list.listIterator(i)
        val it2 = list.listIterator(j)
        if (!it1.hasNext || !it2.hasNext)
          throw new IndexOutOfBoundsException
        val tmp = it1.next()
        it1.set(it2.next())
        it2.set(tmp)
    }
  }

  def fill[T](list: List[_ >: T], obj: T): Unit = {
    list match {
      case list: RandomAccess =>
        (0 until list.size).foreach(list(_) = obj)

      case _ =>
        val iter = list.listIterator
        while (iter.hasNext) {
          iter.next()
          iter.set(obj)
        }
    }
  }

  def copy[T](dest: List[_ >: T], src: List[_ <: T]): Unit = {
    (dest, src) match {
      case (dest: RandomAccess, src: RandomAccess) => copyImpl(src, dest)
      case (dest: RandomAccess, _)                 => copyImpl(src.iterator, dest)
      case (_, src: RandomAccess)                  => copyImpl(src, dest.listIterator)
      case (_, _)                                  => copyImpl(src.iterator, dest.listIterator)
    }
  }

  private def copyImpl[T](source: List[_ <: T] with RandomAccess,
      dest: List[T] with RandomAccess): Unit = {
    (0 until source.size).foreach(i => dest(i) = source.get(i))
  }

  private def copyImpl[T](source: Iterator[_ <: T], dest: List[T] with RandomAccess): Unit = {
    val destEnd = dest.size()
    var i = 0
    while (source.hasNext) {
      if (i < destEnd)
        dest.set(i, source.next())
      else
        throw new IndexOutOfBoundsException
      i += 1
    }
  }

  private def copyImpl[T](source: List[_ <: T] with RandomAccess, dest: ListIterator[T]): Unit = {
    for (i <- 0 until source.size) {
      if (dest.hasNext) {
        dest.next()
        dest.set(source.get(i))
      } else {
        throw new IndexOutOfBoundsException
      }
    }
  }

  private def copyImpl[T](source: Iterator[_ <: T], dest: ListIterator[T]): Unit = {
    while (source.hasNext) {
      if (dest.hasNext) {
        dest.next()
        dest.set(source.next())
      } else {
        throw new IndexOutOfBoundsException
      }
    }
  }

  // Differs from original type definition, original: [T <: jl.Comparable[_ >: T]]
  def min[T <: AnyRef with jl.Comparable[T]](coll: Collection[_ <: T]): T =
    min(coll, naturalComparator[T])

  def min[T](coll: Collection[_ <: T], comp: Comparator[_ >: T]): T =
    coll.min(comp)

  // Differs from original type definition, original: [T <: jl.Comparable[_ >: T]]
  def max[T <: AnyRef with jl.Comparable[T]](coll: Collection[_ <: T]): T =
    max(coll, naturalComparator[T])

  def max[T](coll: Collection[_ <: T], comp: Comparator[_ >: T]): T =
    coll.max(comp)

  def rotate(list: List[_], distance: Int): Unit =
    rotateImpl(list, distance)

  private def rotateImpl[T](list: List[T], distance: Int): Unit = {
    val listSize = list.size
    if (listSize > 1 && distance % listSize != 0) {
      def exchangeRotation(): Unit = {
        def indexModulo(i: Int): Int = modulo(i, listSize)

        @tailrec
        def rotateNext(cycleStartIndex: Int, count: Int, index: Int, value: T): Unit = {
          val nextValue = list(index)
          val newCount = count + 1
          list(index) = value
          if (index != cycleStartIndex) {
            rotateNext(cycleStartIndex, newCount, indexModulo(index + distance), nextValue)
          } else if (newCount < listSize) {
            val nextCycleStart = cycleStartIndex + 1
            rotateNext(nextCycleStart, newCount, indexModulo(nextCycleStart + distance),
                list(nextCycleStart))
          }
        }
        rotateNext(0, 0, indexModulo(distance), list(0))
      }

      def splitReverseRotation(): Unit = {
        val splitPoint = modulo(-distance, listSize)
        reverse(list.subList(0, splitPoint))
        reverse(list.subList(splitPoint, listSize))
        reverse(list)
      }

      list match {
        case _: RandomAccess    => exchangeRotation()
        case _ if listSize < 16 => exchangeRotation() // TODO benchmark and set proper limit
        case _                  => splitReverseRotation()
      }
    }
  }

  def replaceAll[T](list: List[T], oldVal: T, newVal: T): Boolean = {
    list match {
      case _: RandomAccess =>
        var modified = false
        for (i <- list.indices) {
          if (list(i) === oldVal) {
            list(i) = newVal
            modified = true
          }
        }
        modified

      case _ =>
        @tailrec
        def replaceAll(iter: ListIterator[T], mod: Boolean): Boolean = {
          if (iter.hasNext) {
            val isEqual = iter.next() === oldVal
            if (isEqual)
              iter.set(newVal)
            replaceAll(iter, mod || isEqual)
          } else {
            mod
          }
        }
        replaceAll(list.listIterator(), false)
    }
  }

  def indexOfSubList(source: List[_], target: List[_]): Int =
    indexOfSubListImpl(source, target, fromStart = true)

  def lastIndexOfSubList(source: List[_], target: List[_]): Int =
    indexOfSubListImpl(source, target, fromStart = false)

  @inline
  private def indexOfSubListImpl(source: List[_], target: List[_],
      fromStart: Boolean): Int = {
    val targetSize = target.size
    if (targetSize == 0) {
      0
    } else {
      val indices = 0 to source.size - targetSize
      val indicesInOrder = if (fromStart) indices else indices.reverse
      indicesInOrder.find { i =>
        source.subList(i, i + target.size).equals(target)
      }.getOrElse(-1)
    }
  }

  def unmodifiableCollection[T](c: Collection[_ <: T]): Collection[T] = {
    class BasicImmutableCollection
        extends ImmutableCollection[T, Collection[T]](c.asInstanceOf[Collection[T]]) {

      override def equals(obj: Any): Boolean =
        this eq obj.asInstanceOf[AnyRef]

      override def hashCode(): Int =
        System.identityHashCode(this)
    }
    c match {
      case _: Serializable => new BasicImmutableCollection with Serializable
      case _               => new BasicImmutableCollection
    }
  }

  def unmodifiableSet[T](a: Set[_ <: T]): Set[T] = {
    class BasicImmutableSet extends ImmutableSet[T, Set[T]](a.asInstanceOf[Set[T]])
    a match {
      case _: Serializable => new BasicImmutableSet with Serializable
      case _               => new BasicImmutableSet
    }
  }

  def unmodifiableSortedSet[T](s: SortedSet[T]): SortedSet[T] = {
    class BasicImmutableSortedSet extends ImmutableSortedSet[T](s)
    s match {
      case _: Serializable => new BasicImmutableSortedSet with Serializable
      case _               => new BasicImmutableSortedSet
    }
  }

  def unmodifiableList[T](list: List[_ <: T]): List[T] = {
    class BasicImmutableList extends ImmutableList[T](list.asInstanceOf[List[T]])
    list match {
      case _: Serializable with RandomAccess =>
        new BasicImmutableList with Serializable with RandomAccess

      case _: Serializable => new BasicImmutableList with Serializable
      case _: RandomAccess => new BasicImmutableList with RandomAccess
      case _               => new BasicImmutableList
    }
  }

  def unmodifiableMap[K, V](m: Map[_ <: K, _ <: V]): Map[K, V] = {
    class BasicImmutableMap
        extends ImmutableMap[K, V, Map[K, V]](m.asInstanceOf[Map[K, V]])
    m match {
      case _: Serializable => new BasicImmutableMap with Serializable
      case _               => new BasicImmutableMap
    }
  }

  def unmodifiableSortedMap[K, V](m: SortedMap[K, _ <: V]): SortedMap[K, V] = {
    class BasicImmutableSortedMap
        extends ImmutableSortedMap[K, V](m.asInstanceOf[SortedMap[K, V]])
    m match {
      case _: Serializable => new BasicImmutableSortedMap with Serializable
      case _               => new BasicImmutableSortedMap
    }
  }

  def synchronizedCollection[T](c: Collection[T]): Collection[T] = {
    class BasicSynchronizedCollection extends WrappedCollection[T, Collection[T]] {
      override protected val inner: Collection[T] = c

      override def equals(obj: Any): Boolean =
        this eq obj.asInstanceOf[AnyRef]

      override def hashCode(): Int =
        System.identityHashCode(this)
    }
    c match {
      case _: Serializable => new BasicSynchronizedCollection with Serializable
      case _               => new BasicSynchronizedCollection
    }
  }

  def synchronizedSet[T](s: Set[T]): Set[T] = {
    class BasicSynchronizedSet extends WrappedSet[T, Set[T]] {
      override protected val inner: Set[T] = s
    }
    s match {
      case _: Serializable => new BasicSynchronizedSet with Serializable
      case _               => new BasicSynchronizedSet
    }
  }

  def synchronizedSortedSet[T](s: SortedSet[T]): SortedSet[T] = {
    class BasicSynchronizedSortedSet extends WrappedSortedSet[T] {
      override protected val inner: SortedSet[T] = s
    }
    s match {
      case _: Serializable => new BasicSynchronizedSortedSet with Serializable
      case _               => new BasicSynchronizedSortedSet
    }
  }

  def synchronizedList[T](list: List[T]): List[T] = {
    class BasicSynchronizedList extends WrappedList[T] {
      override protected val inner: List[T] = list
    }
    list match {
      case _: Serializable with RandomAccess =>
        new BasicSynchronizedList with Serializable with RandomAccess

      case _: Serializable => new BasicSynchronizedList with Serializable
      case _: RandomAccess => new BasicSynchronizedList with RandomAccess
      case _               => new BasicSynchronizedList
    }
  }

  def synchronizedMap[K, V](m: Map[K, V]): Map[K, V] = {
    class BasicSynchronizedMap extends WrappedMap[K, V, Map[K, V]] {
      override protected val inner: Map[K, V] = m
    }
    m match {
      case _: Serializable => new BasicSynchronizedMap with Serializable
      case _               => new BasicSynchronizedMap
    }
  }

  def synchronizedSortedMap[K, V](m: SortedMap[K, V]): SortedMap[K, V] = {
    class BasicSynchronizedSortedMap extends WrappedSortedMap[K, V] {
      override protected val inner: SortedMap[K, V] = m
    }
    m match {
      case _: Serializable => new BasicSynchronizedSortedMap with Serializable
      case _               => new BasicSynchronizedSortedMap
    }
  }

  def checkedCollection[E](c: Collection[E], typ: Class[E]): Collection[E] = {
    class BasicCheckedCollection extends CheckedCollection[E, Collection[E]](c, typ) {
      override def equals(obj: Any): Boolean =
        this eq obj.asInstanceOf[AnyRef]

      override def hashCode(): Int =
        System.identityHashCode(this)
    }
    c match {
      case _: Serializable => new BasicCheckedCollection with Serializable
      case _               => new BasicCheckedCollection
    }
  }

  def checkedSet[E](s: Set[E], typ: Class[E]): Set[E] = {
    class BasicCheckedSet extends CheckedSet[E, Set[E]](s, typ)
    s match {
      case _: Serializable => new BasicCheckedSet with Serializable
      case _               => new BasicCheckedSet
    }
  }

  def checkedSortedSet[E](s: SortedSet[E], typ: Class[E]): SortedSet[E] = {
    class BasicCheckedSortedSet extends CheckedSortedSet[E](s, typ)
    s match {
      case _: Serializable => new BasicCheckedSortedSet with Serializable
      case _               => new BasicCheckedSortedSet
    }
  }

  def checkedList[E](list: List[E], typ: Class[E]): List[E] = {
    class BasicCheckedList extends CheckedList[E](list, typ)
    list match {
      case _: Serializable with RandomAccess =>
        new BasicCheckedList with Serializable with RandomAccess

      case _: Serializable => new BasicCheckedList with Serializable
      case _: RandomAccess => new BasicCheckedList with RandomAccess
      case _               => new BasicCheckedList
    }
  }

  def checkedMap[K, V](m: Map[K, V], keyType: Class[K], valueType: Class[V]): Map[K, V] = {
    class BasicCheckedMap extends CheckedMap[K, V, Map[K, V]](m, keyType, valueType)
    m match {
      case _: Serializable => new BasicCheckedMap with Serializable
      case _               => new BasicCheckedMap
    }
  }

  def checkedSortedMap[K, V](m: SortedMap[K, V], keyType: Class[K], valueType: Class[V]): SortedMap[K, V] = {
    class BasicCheckedSortedMap extends CheckedSortedMap[K, V](m, keyType, valueType)
    m match {
      case _: Serializable => new BasicCheckedSortedMap with Serializable
      case _               => new BasicCheckedSortedMap
    }
  }

  def emptyIterator[T](): Iterator[T] =
    EMPTY_ITERATOR.asInstanceOf[Iterator[T]]

  def emptyListIterator[T](): ListIterator[T] =
    EMPTY_LIST_ITERATOR.asInstanceOf[ListIterator[T]]

  def emptyEnumeration[T](): Enumeration[T] =
    EMPTY_ENUMERATION.asInstanceOf[Enumeration[T]]

  def emptySet[T](): Set[T] =
    EMPTY_SET.asInstanceOf[Set[T]]

  def emptyList[T](): List[T] =
    EMPTY_LIST.asInstanceOf[List[T]]

  def emptyMap[K, V](): Map[K, V] =
    EMPTY_MAP.asInstanceOf[Map[K, V]]

  def singleton[T](o: T): Set[T] = {
    unmodifiableSet(new AbstractSet[T] with Serializable {
      def size(): Int = 1

      def iterator(): Iterator[T] = {
        new Iterator[T] {
          private var _hasNext: Boolean = true

          def hasNext(): Boolean = _hasNext

          def next(): T = {
            if (!_hasNext)
              throw new NoSuchElementException
            _hasNext = false
            o
          }

          def remove(): Unit =
            throw new UnsupportedOperationException
        }
      }
    })
  }

  def singletonList[T](o: T): List[T] = {
    unmodifiableList(new AbstractList[T] with Serializable {
      def size(): Int = 1

      def get(index: Int): T =
        if (index == 0) o
        else throw new IndexOutOfBoundsException(index.toString)
    })
  }

  def singletonMap[K, V](key: K, value: V): Map[K, V] = {
    unmodifiableMap[K, V](new AbstractMap[K, V] with Serializable {
      def entrySet(): Set[Map.Entry[K, V]] =
        singleton(new AbstractMap.SimpleImmutableEntry(key, value))
    })
  }

  def nCopies[T](n: Int, o: T): List[T] = {
    if (n < 0)
      throw new IllegalArgumentException

    unmodifiableList(new AbstractList[T] with Serializable with RandomAccess {
      def size(): Int = n

      def get(index: Int): T = {
        if (index < 0 || index >= n)
          throw new IndexOutOfBoundsException
        o
      }
    })
  }

  def reverseOrder[T](): Comparator[T] = {
    val cmp = new Comparator[T] {
      def compare(o1: T, o2: T): Int = o1.asInstanceOf[Comparable[T]].compareTo(o2)
    }
    reverseOrder(cmp)
  }

  def reverseOrder[T](cmp: Comparator[T]): Comparator[T] = {
    class ReverseComparator extends Comparator[T] {
      override def compare(o1: T, o2: T): Int = cmp.compare(o2, o1)
    }
    cmp match {
      case _: Serializable => new ReverseComparator with Serializable
      case _               => new ReverseComparator
    }
  }

  def enumeration[T](c: Collection[T]): Enumeration[T] = {
    val it = c.iterator
    new Enumeration[T] {
      override def hasMoreElements: Boolean =
        it.hasNext

      override def nextElement(): T =
        it.next()
    }
  }

  def list[T](e: Enumeration[T]): ArrayList[T] = {
    val arrayList = new ArrayList[T]
    e.foreach(arrayList += _)
    arrayList
  }

  def frequency(c: Collection[_], o: AnyRef): Int =
    c.count(_ === o)

  def disjoint(c1: Collection[_], c2: Collection[_]): Boolean = {
    if (c1.size < c2.size)
      !c1.exists(elem => c2.contains(elem))
    else
      !c2.exists(elem => c1.contains(elem))
  }

  def addAll[T](c: Collection[_ >: T], elements: Array[AnyRef]): Boolean =
    c.addAll(asJavaCollection(elements.asInstanceOf[Array[T]]))

  def newSetFromMap[E](map: Map[E, java.lang.Boolean]): Set[E] = {
    if (map.nonEmpty)
      throw new IllegalArgumentException

    new WrappedSet[E, Set[E]] {
      override protected val inner: Set[E] =
        map.keySet

      override def add(e: E): Boolean =
        map.put(e, true) == null

      override def addAll(c: Collection[_ <: E]): Boolean =
        c.foldLeft(false)((prev, elem) => map.put(elem, true) == null || prev)
    }
  }

  @inline
  private def modulo(a: Int, b: Int): Int = ((a % b) + b) % b

  @inline
  private def naturalComparator[T <: jl.Comparable[T]]: Comparator[T] = {
    new Comparator[T] {
      final def compare(o1: T, o2: T): Int = o1.compareTo(o2)
    }
  }

  @inline
  private implicit def comparatorToOrdering[E](cmp: Comparator[E]): Ordering[E] = {
    new Ordering[E] {
      final def compare(x: E, y: E): Int = cmp.compare(x, y)
    }
  }

  private trait WrappedCollection[E, Coll <: Collection[E]]
      extends Collection[E] {

    protected def inner: Coll

    def size(): Int =
      inner.size

    def isEmpty: Boolean =
      inner.isEmpty

    def contains(o: Any): Boolean =
      inner.contains(o)

    def iterator(): Iterator[E] =
      inner.iterator

    def toArray: Array[AnyRef] =
      inner.toArray()

    def toArray[T <: AnyRef](a: Array[T]): Array[T] =
      inner.toArray[T](a)

    def add(e: E): Boolean =
      inner.add(e)

    def remove(o: Any): Boolean =
      inner.remove(o)

    def containsAll(c: Collection[_]): Boolean =
      inner.containsAll(c)

    def addAll(c: Collection[_ <: E]): Boolean =
      inner.addAll(c)

    def removeAll(c: Collection[_]): Boolean =
      inner.removeAll(c)

    def retainAll(c: Collection[_]): Boolean =
      inner.retainAll(c)

    def clear(): Unit =
      inner.clear()

    override def equals(obj: Any): Boolean =
      inner.equals(obj)

    override def hashCode(): Int =
      inner.hashCode

    override def toString: String =
      inner.toString
  }

  private trait WrappedSet[E, Coll <: Set[E]]
      extends WrappedCollection[E, Coll] with Set[E]

  private trait WrappedSortedSet[E]
      extends WrappedCollection[E, SortedSet[E]] with SortedSet[E] {
    def comparator(): Comparator[_ >: E] =
      inner.comparator()

    def subSet(fromElement: E, toElement: E): SortedSet[E] =
      inner.subSet(fromElement, toElement)

    def tailSet(fromElement: E): SortedSet[E] =
      inner.tailSet(fromElement)

    def headSet(toElement: E): SortedSet[E] =
      inner.headSet(toElement)

    def first(): E =
      inner.first

    def last(): E =
      inner.last
  }

  private trait WrappedList[E]
      extends WrappedCollection[E, List[E]] with List[E] {

    def addAll(index: Int, c: Collection[_ <: E]): Boolean =
      inner.addAll(index, c)

    def get(index: Int): E =
      inner.get(index)

    def set(index: Int, element: E): E =
      inner.set(index, element)

    def add(index: Int, element: E): Unit =
      inner.add(index, element)

    def remove(index: Int): E =
      inner.remove(index)

    def indexOf(o: scala.Any): Int =
      inner.indexOf(o)

    def lastIndexOf(o: scala.Any): Int =
      inner.lastIndexOf(o)

    def listIterator(): ListIterator[E] =
      inner.listIterator()

    def listIterator(index: Int): ListIterator[E] =
      inner.listIterator(index)

    def subList(fromIndex: Int, toIndex: Int): List[E] =
      inner.subList(fromIndex, toIndex)
  }

  private trait WrappedMap[K, V, M <: Map[K, V]] extends Map[K, V] {
    protected def inner: M

    def size(): Int =
      inner.size()

    def isEmpty: Boolean =
      inner.isEmpty

    def containsKey(key: scala.Any): Boolean =
      inner.containsKey(key)

    def containsValue(value: scala.Any): Boolean =
      inner.containsValue(value)

    def get(key: scala.Any): V =
      inner.get(key)

    def put(key: K, value: V): V =
      inner.put(key, value)

    def remove(key: scala.Any): V =
      inner.remove(key)

    def putAll(m: Map[_ <: K, _ <: V]): Unit =
      inner.putAll(m)

    def clear(): Unit =
      inner.clear()

    def keySet(): Set[K] =
      inner.keySet

    def values(): Collection[V] =
      inner.values

    def entrySet(): Set[Map.Entry[K, V]] =
      inner.entrySet.asInstanceOf[Set[Map.Entry[K, V]]]

    override def equals(obj: Any): Boolean =
      inner.equals(obj)

    override def hashCode(): Int =
      inner.hashCode

    override def toString(): String =
      inner.toString
  }

  private trait WrappedSortedMap[K, V]
      extends WrappedMap[K, V, SortedMap[K, V]] with SortedMap[K, V] {
    def comparator(): Comparator[_ >: K] =
      inner.comparator

    def subMap(fromKey: K, toKey: K): SortedMap[K, V] =
      inner.subMap(fromKey, toKey)

    def headMap(toKey: K): SortedMap[K, V] =
      inner.headMap(toKey)

    def tailMap(fromKey: K): SortedMap[K, V] =
      inner.tailMap(fromKey)

    def firstKey(): K =
      inner.firstKey

    def lastKey(): K =
      inner.lastKey
  }

  private trait WrappedIterator[E, Iter <: Iterator[E]] extends Iterator[E] {
    protected def inner: Iter

    def hasNext(): Boolean =
      inner.hasNext

    def next(): E =
      inner.next()

    def remove(): Unit =
      inner.remove()
  }

  private trait WrappedListIterator[E]
      extends WrappedIterator[E, ListIterator[E]] with ListIterator[E] {
    def hasPrevious(): Boolean =
      inner.hasPrevious

    def previous(): E =
      inner.previous()

    def nextIndex(): Int =
      inner.nextIndex

    def previousIndex(): Int =
      inner.previousIndex

    def set(e: E): Unit =
      inner.set(e)

    def add(e: E): Unit =
      inner.add(e)
  }

  private class ImmutableCollection[E, Coll <: Collection[E]](
      protected val inner: Coll) extends WrappedCollection[E, Coll] {

    override def clear(): Unit =
      throw new UnsupportedOperationException

    override def iterator(): Iterator[E] =
      new ImmutableIterator(inner.iterator)

    override def add(e: E): Boolean =
      throw new UnsupportedOperationException

    override def remove(o: Any): Boolean =
      throw new UnsupportedOperationException

    override def addAll(c: Collection[_ <: E]): Boolean =
      throw new UnsupportedOperationException

    override def removeAll(c: Collection[_]): Boolean =
      throw new UnsupportedOperationException

    override def retainAll(c: Collection[_]): Boolean =
      throw new UnsupportedOperationException
  }

  private class ImmutableSet[E, Coll <: Set[E]](inner: Coll)
      extends ImmutableCollection[E, Coll](inner) with WrappedSet[E, Coll]

  private class ImmutableSortedSet[E](inner: SortedSet[E])
      extends ImmutableSet[E, SortedSet[E]](inner) with WrappedSortedSet[E]

  private class ImmutableList[E](inner: List[E])
      extends ImmutableCollection[E, List[E]](inner) with WrappedList[E] {

    override def addAll(index: Int, c: Collection[_ <: E]): Boolean =
      throw new UnsupportedOperationException

    override def set(index: Int, element: E): E =
      throw new UnsupportedOperationException

    override def add(index: Int, element: E): Unit =
      throw new UnsupportedOperationException

    override def remove(index: Int): E =
      throw new UnsupportedOperationException

    override def listIterator(): ListIterator[E] =
      new ImmutableListIterator(this.inner.listIterator())

    override def listIterator(index: Int): ListIterator[E] =
      new ImmutableListIterator(this.inner.listIterator(index))

    override def subList(fromIndex: Int, toIndex: Int): List[E] =
      unmodifiableList(super.subList(fromIndex, toIndex))
  }

  private class ImmutableMap[K, V, M <: Map[K, V]](
      protected val inner: M) extends WrappedMap[K, V, M] {

    override def put(key: K, value: V): V =
      throw new UnsupportedOperationException

    override def remove(key: scala.Any): V =
      throw new UnsupportedOperationException

    override def putAll(m: Map[_ <: K, _ <: V]): Unit =
      throw new UnsupportedOperationException

    override def clear(): Unit =
      throw new UnsupportedOperationException

    override def keySet(): Set[K] =
      unmodifiableSet(super.keySet)

    override def values(): Collection[V] =
      unmodifiableCollection(super.values)

    override def entrySet(): Set[Map.Entry[K, V]] =
      unmodifiableSet(super.entrySet)
  }

  private class ImmutableSortedMap[K, V](inner: SortedMap[K, V])
      extends ImmutableMap[K, V, SortedMap[K, V]](inner) with WrappedSortedMap[K, V] {

    override def subMap(fromKey: K, toKey: K): SortedMap[K, V] =
      unmodifiableSortedMap(super.subMap(fromKey, toKey))

    override def headMap(toKey: K): SortedMap[K, V] =
      unmodifiableSortedMap(super.headMap(toKey))

    override def tailMap(fromKey: K): SortedMap[K, V] =
      unmodifiableSortedMap(super.tailMap(fromKey))
  }

  private class ImmutableIterator[E, Iter <: Iterator[E]](protected val inner: Iter)
      extends WrappedIterator[E, Iter] {
    override def remove(): Unit = throw new UnsupportedOperationException
  }

  private class ImmutableListIterator[E](innerIterator: ListIterator[E])
      extends ImmutableIterator[E, ListIterator[E]](innerIterator)
      with WrappedListIterator[E] {
    override def set(e: E): Unit = throw new UnsupportedOperationException

    override def add(e: E): Unit = throw new UnsupportedOperationException
  }

  private final def checkClass[T](elem: T, clazz: Class[T]): Unit =
    clazz.cast(elem)

  private class CheckedCollection[E, Coll <: Collection[E]](
      protected val inner: Coll, protected val elemClazz: Class[E])
      extends WrappedCollection[E, Coll] {

    override def add(e: E): Boolean = {
      checkElem(e)
      super.add(e)
    }

    override def addAll(c: Collection[_ <: E]): Boolean = {
      c.foreach(checkElem)
      super.addAll(c)
    }

    protected final def checkElem(elem: E) =
      checkClass(elem, elemClazz)
  }

  private class CheckedSet[E, Coll <: Set[E]](inner: Coll, elemClazz: Class[E])
      extends CheckedCollection[E, Coll](inner, elemClazz) with WrappedSet[E, Coll]

  private class CheckedSortedSet[E](inner: SortedSet[E], elemClazz: Class[E])
      extends CheckedSet[E, SortedSet[E]](inner, elemClazz) with WrappedSortedSet[E] {

    override def subSet(fromElement: E, toElement: E): SortedSet[E] =
      checkedSortedSet(super.subSet(fromElement, toElement), this.elemClazz)

    override def headSet(toElement: E): SortedSet[E] =
      checkedSortedSet(super.headSet(toElement), this.elemClazz)

    override def tailSet(fromElement: E): SortedSet[E] =
      checkedSortedSet(super.tailSet(fromElement), this.elemClazz)
  }

  private class CheckedList[E](inner: List[E], elemClazz: Class[E])
      extends CheckedCollection[E, List[E]](inner, elemClazz) with WrappedList[E] {

    override def addAll(index: Int, c: Collection[_ <: E]): Boolean = {
      c.foreach(checkElem)
      super.addAll(index, c)
    }

    override def set(index: Int, element: E): E = {
      checkElem(element)
      super.set(index, element)
    }

    override def add(index: Int, element: E): Unit = {
      checkElem(element)
      super.add(index, element)
    }

    override def listIterator(): ListIterator[E] = listIterator(0)

    override def listIterator(index: Int): ListIterator[E] =
      new CheckedListIterator[E](this.inner.listIterator(index), this.elemClazz)

    override def subList(fromIndex: Int, toIndex: Int): List[E] =
      checkedList(super.subList(fromIndex, toIndex), this.elemClazz)
  }

  private class CheckedMap[K, V, M <: Map[K, V]](protected val inner: M, protected val keyClazz: Class[K],
      protected val valueClazz: Class[V]) extends WrappedMap[K, V, M] {

    override def put(key: K, value: V): V = {
      checkKeyAndValue(key, value)
      super.put(key, value)
    }

    override def putAll(m: Map[_ <: K, _ <: V]): Unit = {
      m.entrySet().foreach(entry => checkKeyAndValue(entry.getKey, entry.getValue))
      super.putAll(m)
    }

    override def entrySet(): Set[Map.Entry[K, V]] = {
      val innerSet = super.entrySet()
      new WrappedSet[Map.Entry[K, V], Set[Map.Entry[K, V]]] {
        protected def inner: Set[Map.Entry[K, V]] = innerSet

        override def iterator(): Iterator[Map.Entry[K, V]] = {
          val innerIterator = super.iterator()
          new WrappedIterator[Map.Entry[K, V], Iterator[Map.Entry[K, V]]] {
            protected def inner: Iterator[Map.Entry[K, V]] = innerIterator

            override def next(): Map.Entry[K, V] = {
              val nextEntry = super.next()
              new Map.Entry[K, V] {
                def getKey(): K =
                  nextEntry.getKey()

                def getValue(): V =
                  nextEntry.getValue()

                def setValue(value: V): V = {
                  checkClass(value, valueClazz)
                  nextEntry.setValue(value)
                }

                override def equals(o: Any): Boolean =
                  nextEntry.equals(o)

                override def hashCode(): Int =
                  nextEntry.hashCode()
              }
            }
          }
        }
      }
    }

    protected final def checkKeyAndValue(key: K, value: V): Unit = {
      checkClass(key, keyClazz)
      checkClass(value, valueClazz)
    }
  }

  private class CheckedSortedMap[K, V](
      inner: SortedMap[K, V], keyClazz: Class[K], valueClazz: Class[V])
      extends CheckedMap[K, V, SortedMap[K, V]](inner, keyClazz, valueClazz)
      with WrappedSortedMap[K, V] {

    override def subMap(fromKey: K, toKey: K): SortedMap[K, V] =
      checkedSortedMap(super.subMap(fromKey, toKey), keyClazz, valueClazz)

    override def headMap(toKey: K): SortedMap[K, V] =
      checkedSortedMap(super.headMap(toKey), keyClazz, valueClazz)

    override def tailMap(fromKey: K): SortedMap[K, V] =
      checkedSortedMap(super.tailMap(fromKey), keyClazz, valueClazz)
  }

  private class CheckedListIterator[E](protected val inner: ListIterator[E],
      protected val elemClazz: Class[E]) extends WrappedListIterator[E] {
    override def set(e: E): Unit = {
      checkElem(e)
      super.set(e)
    }

    override def add(e: E): Unit = {
      checkElem(e)
      super.add(e)
    }

    private def checkElem(elem: E): Unit = {
      checkClass(elem, elemClazz)
    }
  }

  private class EmptyIterator extends Iterator[Any] {
    def hasNext(): Boolean = false

    def next(): Any =
      throw new NoSuchElementException

    def remove(): Unit =
      throw new IllegalStateException
  }

  private class EmptyListIterator extends EmptyIterator with ListIterator[Any] {
    def hasPrevious(): Boolean = false

    def previous(): Any =
      throw new NoSuchElementException

    def nextIndex(): Int = 0

    def previousIndex(): Int = -1

    def set(e: Any): Unit =
      throw new IllegalStateException

    def add(e: Any): Unit =
      throw new UnsupportedOperationException
  }
}


text:
add
***

::

  hg add filename

To add any unversioned files and remove any missing files:

::

  hg addremove

redpajama_set_name: RedPajamaGithub


text:
@implementation Architecture {
    NSArray* (^makeArgs)(NSString*, NSArray*);
    NSString* (^dyldinfo)(NSArray*);
}

//|++++++++++++++++++++++++++++++++++++|//
- (instancetype)initWithURL:(NSURL*)url offset:(uint32_t)offset name:(NSString*)name
{
    self = [super init];

    NSParameterAssert(url);
    NSParameterAssert(name);
    _name = name = [name lowercaseString];
    _offset = offset;

    makeArgs = ^(NSString *tool, NSArray *input) {
        NSMutableArray *args = [NSMutableArray array];
        [args addObject:tool];
        [args addObject:@"-arch"];
        [args addObject:name];
        [args addObjectsFromArray:input];
        [args addObject:url.path];
        return args;
    };

    dyldinfo = ^(NSArray *options) {
        NSMutableArray *args = [NSMutableArray array];
        [args addObject:@"dyldinfo"];
        [args addObjectsFromArray:options];
        [args addObject:url.path];
        NSString *output = [NSTask outputForLaunchedTaskWithLaunchPath:@XCRUN_PATH arguments:args];
        return [DyldInfoUtil extractOutputForArchitecture:name fromInput:output];
    };

    // Mach Header
    @autoreleasepool {
        NSString *machHeader = [NSTask outputForLaunchedTaskWithLaunchPath:@XCRUN_PATH arguments:makeArgs(@"otool", @[@"-h"])];
        _machHeader = [OtoolUtil parseMachHeader:machHeader];
    }

    // Load Commands
    @autoreleasepool {
        NSString *loadCommands = [NSTask outputForLaunchedTaskWithLaunchPath:@XCRUN_PATH arguments:makeArgs(@"otool", @[@"-l"])];
        _loadCommands = [OtoolUtil parseLoadCommands:loadCommands];
    }

    // Libraries
    @autoreleasepool {
        NSString *libraries = dyldinfo(@[@"-dylibs"]);
        _dependentLibraries = [DyldInfoUtil parseDylibs:libraries];
    }

    // Rebase & bind Commands
    @autoreleasepool {
        NSString *opcodes = dyldinfo(@[@"-opcodes"]);
        _rebaseCommands = [DyldInfoUtil parseRebaseCommands:opcodes];
        _bindCommands = [DyldInfoUtil parseBindCommands:opcodes];
        _weakBindCommands = [DyldInfoUtil parseWeakBindCommands:opcodes];
        _lazybindCommands = [DyldInfoUtil parseLazyBindCommands:opcodes];
    }

    return self;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)fixupAddresses
{
    NSArray *fixupAddresses;
    @autoreleasepool {
        NSString *fixups = dyldinfo(@[@"-rebase"]);
        fixupAddresses = [DyldInfoUtil parseFixups:fixups];
    }
    return fixupAddresses;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)bindings
{
    NSArray *bindingAddresses;
    @autoreleasepool {
        NSString *bindings = dyldinfo(@[@"-bind"]);
        bindingAddresses = [DyldInfoUtil parseBindings:bindings];
    }
    return bindingAddresses;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)weakBindings
{
    NSArray *bindingAddresses;
    @autoreleasepool {
        NSString *bindings = dyldinfo(@[@"-weak_bind"]);
        bindingAddresses = [DyldInfoUtil parseWeakBindings:bindings];
    }
    return bindingAddresses;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)lazyBindings
{
    NSArray *bindingAddresses;
    @autoreleasepool {
        NSString *bindings = dyldinfo(@[@"-lazy_bind"]);
        bindingAddresses = [DyldInfoUtil parseLazyBindings:bindings];
    }
    return bindingAddresses;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)exports
{
	NSArray *exportsList;
	@autoreleasepool {
        NSString *exports = dyldinfo(@[@"-export"]);
		exportsList = [DyldInfoUtil parseExports:exports];
	}
	return exportsList;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)functionStarts
{
    NSArray *functionStartsList;
    @autoreleasepool {
        NSString *functionStarts = dyldinfo(@[@"-function_starts"]);
        functionStartsList = [DyldInfoUtil parseFunctionStarts:functionStarts];
    }
    return functionStartsList;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)dataInCodeEntries
{
    NSArray *dataInCodeEntriesList;
    @autoreleasepool {
        NSString *dataInCodeEntries = [NSTask outputForLaunchedTaskWithLaunchPath:@XCRUN_PATH arguments:makeArgs(@"otool", @[@"-G"])];
        dataInCodeEntriesList = [OtoolUtil parseDataInCodeEntries:dataInCodeEntries];
    }
    return dataInCodeEntriesList;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)bsdSymbols
{
    NSArray *symbolsList;
    @autoreleasepool {
        NSString *symbols = [NSTask outputForLaunchedTaskWithLaunchPath:@XCRUN_PATH arguments:makeArgs(@"nm", @[@"-ap", @"-no-dyldinfo", @"-f", @"bsd"])];
        symbolsList = [NMUtil parseBSDSymbols:symbols];
    }
    return symbolsList;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)darwinSymbols
{
    NSArray *symbolsList;
    @autoreleasepool {
        NSString *symbols = [NSTask outputForLaunchedTaskWithLaunchPath:@XCRUN_PATH arguments:makeArgs(@"nm", @[@"-ap", @"-no-dyldinfo", @"-f", @"darwin"])];
        symbolsList = [NMUtil parseDarwinSymbols:symbols];
    }
    return symbolsList;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSArray*)indirectSymbols
{
    NSArray *symbolsList;
    @autoreleasepool {
        NSString *symbols = [NSTask outputForLaunchedTaskWithLaunchPath:@XCRUN_PATH arguments:makeArgs(@"otool", @[@"-I"])];
        symbolsList = [OtoolUtil parseIndirectSymbols:symbols];
    }
    return symbolsList;
}

//|++++++++++++++++++++++++++++++++++++|//
- (NSDictionary*)objcInfo
{
    NSDictionary *objcInfo;
    @autoreleasepool {
        NSString *info = [NSTask outputForLaunchedTaskWithLaunchPath:@XCRUN_PATH arguments:makeArgs(@"otool", @[@"-ov"])];
        objcInfo = [OtoolUtil parseObjCImageInfo:info];
    }
    return objcInfo;
}

@end

//----------------------------------------------------------------------------//
@implementation Binary

//|++++++++++++++++++++++++++++++++++++|//
+ (instancetype)binaryAtURL:(NSURL*)url
{
    static NSMutableDictionary *memo;
    if (memo == nil)
        memo = [[NSMutableDictionary alloc] init];

    if (memo[url] == nil)
        @autoreleasepool { memo[url] = [[self alloc] initWithURL:url]; }

    return memo[url];
}

//|++++++++++++++++++++++++++++++++++++|//
- (instancetype)initWithURL:(NSURL*)url
{
    self = [super init];

    _url = url;

    // Fat header
    {
        NSString *otoolFatHeader = [NSTask outputForLaunchedTaskWithLaunchPath:@OTOOL_PATH arguments:@[@"-f", url.path]];
        if ([otoolFatHeader rangeOfString:@"No such file or directory"].location != NSNotFound)
            return nil;

        _fatHeader = [OtoolUtil parseFatHeader:otoolFatHeader];

        NSString *otoolVerboseFatHeader = [NSTask outputForLaunchedTaskWithLaunchPath:@OTOOL_PATH arguments:@[@"-f", @"-v", url.path]];
        if ([otoolVerboseFatHeader rangeOfString:@"No such file or directory"].location != NSNotFound)
            return nil;

        _fatHeader_verbose = [OtoolUtil parseFatHeader:otoolVerboseFatHeader];
    }

    if (_fatHeader_verbose)
    {
        NSMutableArray *architectures = [[NSMutableArray alloc] init];

        NSDictionary *arches = _fatHeader_verbose[@"architecture"];
        for (NSString *arch in arches) {
            [architectures addObject:[[Architecture alloc] initWithURL:_url offset:(uint32_t)[[arches[arch] objectForKey:@"offset"] integerValue] name:arch]];
        }

        _architectures = architectures;
    }
    else
    {
        // Get the arch name
        NSString *args = [NSString stringWithFormat:@"%@ -h -v %@ | tail -n 1 | awk '{print $2}' | tr -d '\n'", @OTOOL_PATH, url.path];
        NSString *archName = [NSTask outputForLaunchedTaskWithLaunchPath:@SHELL_PATH arguments:@[@"-c", args]];
        Architecture *arch = [[Architecture alloc] initWithURL:_url offset:0 name:archName];
        _architectures = @[arch];
    }

    return self;
}

@end


text:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:id="@+id/scrollView"
    android:scrollbars="vertical"
    android:fillViewport="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin"
        tools:context="com.example.picoclient.testclient.MainActivity$PlaceholderFragment"
        android:orientation="vertical"
        android:weightSum="1">

        <RelativeLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="140dp">

            <TextView
                android:text="@string/app_status"
                android:layout_width="match_parent"
                android:layout_height="fill_parent"
                android:id="@+id/textStatus"
                android:minWidth="@dimen/dialog_fixed_width_minor"
                android:gravity="bottom|center"
                style="@style/TextAppearance.AppCompat.Light.Base.Widget.PopupMenu.Large"
                android:height="100px"
                android:padding="10px"
                android:textAlignment="center"
                android:textIsSelectable="false"
                android:textSize="@dimen/statusFontSize" />

            <!--Depth is determined by order of code. We want the following to be on top-->
            <TextView
                style="@style/TextAppearance.AppCompat.Light.Base.Widget.PopupMenu.Large"
                android:text="@string/secret"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/secret_key_text_view"
                android:gravity="bottom|left"
                android:textAlignment="center"
                android:textIsSelectable="false"
                android:textSize="@dimen/time_left_unlocked_fontsize"
                android:typeface="sans" />

            <!--<TextView-->
                <!--android:text="@string/time_to_lock"-->
                <!--android:layout_width="match_parent"-->
                <!--android:layout_height="wrap_content"-->
                <!--android:id="@+id/text_time_left"-->
                <!--android:gravity="top|left"-->
                <!--style="@style/TextAppearance.AppCompat.Light.Base.Widget.PopupMenu.Large"-->
                <!--android:textAlignment="center"-->
                <!--android:textIsSelectable="false"-->
                <!--android:textSize="@dimen/time_left_unlocked_fontsize"-->
                <!--android:layout_alignParentBottom="true"-->
                <!--android:layout_alignParentLeft="true"-->
                <!--android:layout_alignParentStart="true" />-->

        </RelativeLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Pair with server"
                android:onClick="onCreateFile"
                android:id="@+id/createFileButton"
                android:layout_weight="1" />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Request Keys"
                android:onClick="onRequestRevKey"
                android:id="@+id/requestRevKeyButton"
                android:layout_weight="1" />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Decrypt secret"
                android:onClick="onDecrypt"
                android:id="@+id/decryptFileButton"
                android:layout_weight="1" />
        </LinearLayout>

        <!--<Button-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:text="Get key count"-->
        <!--android:onClick="onKeyCount"-->
        <!--android:id="@+id/getKeyCountButton"-->
        <!--android:layout_alignParentBottom="true" />-->

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Debugging actions"
            android:id="@+id/textView"/>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="right">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Lock app"
                android:onClick="onLockOrUnlockApp"
                android:id="@+id/lockOrUnlockButton"
                android:layout_alignParentBottom="true"
                android:layout_weight="1"
                />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="View file"
                android:onClick="onShowFile"
                android:id="@+id/readFileButton"
                android:layout_weight="1"
                android:layout_gravity="center_horizontal"
                />
        </LinearLayout>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Start BG service"
                android:onClick="toggleBGService"
                android:id="@+id/toggleServiceBtn"
                android:layout_weight="1"
                />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Start polling"
                android:onClick="onTogglePolling"
                android:id="@+id/togglePollButton"
                android:layout_weight="1"
                />

        </LinearLayout>

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="View memory"
            android:onClick="viewAppPref"
            android:id="@+id/viewAppPrefButton"
            android:layout_alignParentBottom="true"
            android:visibility="gone"/>

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Upload DB"
                android:onClick="uploadDB"
                android:id="@+id/stopServiceBtn"
                android:layout_weight="1"
                />

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Export DB to SDcard"
                android:onClick="exportDB"
                android:id="@+id/exportDBBtn"
                android:layout_weight="1"
                />
        </LinearLayout>

        <!--<Button-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:text="Start temp function"-->
        <!--android:onClick="tempFunction"-->
        <!--android:id="@+id/tempButton"-->
        <!--android:layout_alignParentBottom="true" />-->

        <!--<TextView-->
            <!--android:layout_width="match_parent"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:textAppearance="?android:attr/textAppearanceLarge"-->
            <!--android:id="@+id/lastLog"-->
            <!--android:layout_gravity="center_horizontal" />-->

        <ProgressBar
            style="?android:attr/progressBarStyleHorizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/uploadProgressBar"
            android:layout_gravity="center_horizontal"
            android:visibility="gone"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:visibility="gone"
            android:id="@+id/uploadProgressText" />

        <!--<ProgressBar-->
            <!--style="?android:attr/progressBarStyleSmall"-->
            <!--android:layout_width="wrap_content"-->
            <!--android:layout_height="wrap_content"-->
            <!--android:id="@+id/uploadProgressBar"-->
            <!--android:layout_gravity="center_horizontal" />-->

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:text="Version number"
            android:id="@+id/versionTextView" />

    </LinearLayout>

</ScrollView>


text:
require 'spec_helper'
require 'vagrant-proxyconf/config/git_proxy'

describe VagrantPlugins::ProxyConf::Config::GitProxy do
  let(:instance) { described_class.new }
  before(:each) { ENV.delete('VAGRANT_GIT_HTTP_PROXY') }
end


text:
package com.amazonaws.services.opsworks.model;

import java.io.Serializable;
import javax.annotation.Generated;

import com.amazonaws.AmazonWebServiceRequest;

/**
 *
 * @see AWS API
 *      Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UnassignVolumeRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {

    /**
     *

     * The volume ID.
     *

     */
    private String volumeId;

    /**
     *

     * The volume ID.
     *

     *
     * @param volumeId
     *        The volume ID.
     */

    public void setVolumeId(String volumeId) {
        this.volumeId = volumeId;
    }

    /**
     *

     * The volume ID.
     *

     *
     * @return The volume ID.
     */

    public String getVolumeId() {
        return this.volumeId;
    }

    /**
     *

     * The volume ID.
     *

     *
     * @param volumeId
     *        The volume ID.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public UnassignVolumeRequest withVolumeId(String volumeId) {
        setVolumeId(volumeId);
        return this;
    }

    /**
     * Returns a string representation of this object; useful for testing and debugging.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getVolumeId() != null)
            sb.append("VolumeId: ").append(getVolumeId());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof UnassignVolumeRequest == false)
            return false;
        UnassignVolumeRequest other = (UnassignVolumeRequest) obj;
        if (other.getVolumeId() == null ^ this.getVolumeId() == null)
            return false;
        if (other.getVolumeId() != null && other.getVolumeId().equals(this.getVolumeId()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getVolumeId() == null) ? 0 : getVolumeId().hashCode());
        return hashCode;
    }

    @Override
    public UnassignVolumeRequest clone() {
        return (UnassignVolumeRequest) super.clone();
    }

}


text:
package org.pitest.classinfo;

import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.pitest.functional.F5;

public abstract class MethodFilteringAdapter extends ClassVisitor {

  private final F5<Integer, String, String, String, String[], Boolean> filter;

  public MethodFilteringAdapter(final ClassVisitor writer,
      final F5<Integer, String, String, String, String[], Boolean> filter) {
    super(Opcodes.ASM5, writer);
    this.filter = filter;
  }

  private boolean shouldInstrument(final int access, final String name,
      final String desc, final String signature, final String[] exceptions) {
    return this.filter.apply(access, name, desc, signature, exceptions);
  }

  @Override
  public final MethodVisitor visitMethod(final int access, final String name,
      final String desc, final String signature, final String[] exceptions) {
    final MethodVisitor methodVisitor = this.cv.visitMethod(access, name, desc,
        signature, exceptions);
    if (shouldInstrument(access, name, desc, signature, exceptions)) {
      return visitMethodIfRequired(access, name, desc, signature, exceptions,
          methodVisitor);
    } else {
      return methodVisitor;
    }
  }

  public abstract MethodVisitor visitMethodIfRequired(int access, String name,
      String desc, String signature, String[] exceptions,
      MethodVisitor methodVisitor);

}


text:
<?xml version="1.0" encoding="utf-8" ?>
<Settings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2011/01/fabric">

        <Parameter Name="ReplicatorEndpoint" Value="ReplicatorEndpoint" />

        <Parameter Name="ElasticSearchUri" Value="" />
        <Parameter Name="ElasticSearchIndexName" Value="mouselogs" />

        <Parameter Name="ElasticSearchUri" Value="" />
        <Parameter Name="ElasticSearchIndexName" Value="mousemetrics" />

</Settings>


text:
from corehq.apps.commtrack.models import SupplyPointCase
from corehq.apps.products.models import Product

"""
helper code to populate the various commtrack models, for ease of
development/testing, before we have proper UIs and imports
"""

def make_product(domain, name, code):
    p = Product()
    p.domain = domain
    p.name = name
    p.code = code.lower()
    p.save()
    return p

def make_supply_point(domain, location):
    return SupplyPointCase.create_from_location(domain, location)


text:
package org.openbaton.vnfm.generic.utils;

import java.util.HashMap;
import java.util.Map;
import org.openbaton.catalogue.mano.common.Ip;
import org.openbaton.catalogue.mano.record.VNFCInstance;
import org.openbaton.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.openbaton.catalogue.nfvo.ConfigurationParameter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EnvMapUtils {

  private static final Logger log = LoggerFactory.getLogger(EnvMapUtils.class);

  public static Map<String, String> createForLifeCycleEventExecutionOnVNFCInstance(
      VNFCInstance vnfcInstance) {
    Map<String, String> tempEnv = new HashMap<>();
    tempEnv = putOwnIpAndFloatingIp(tempEnv, vnfcInstance);
    tempEnv = putVNFCInstanceHostnameInMap(tempEnv, vnfcInstance);
    tempEnv = modifyUnsafeEnvVarNames(tempEnv);
    return tempEnv;
  }

  public static Map<String, String> createConfigurationParametersAndProvidesMapFromVNFR(
      VirtualNetworkFunctionRecord vnfr) {
    Map<String, String> res = new HashMap<>();

    if (vnfr.getProvides() == null
        || vnfr.getProvides().getConfigurationParameters() == null
        || vnfr.getConfigurations() == null
        || vnfr.getConfigurations().getConfigurationParameters() == null) return res;
    for (ConfigurationParameter configurationParameter :
        vnfr.getProvides().getConfigurationParameters()) {
      res.put(configurationParameter.getConfKey(), configurationParameter.getValue());
    }
    for (ConfigurationParameter configurationParameter :
        vnfr.getConfigurations().getConfigurationParameters()) {
      res.put(configurationParameter.getConfKey(), configurationParameter.getValue());
    }
    res = modifyUnsafeEnvVarNames(res);
    return res;
  }

  public static Map<String, String> modifyUnsafeEnvVarNames(Map<String, String> env) {

    Map<String, String> result = new HashMap<>();

    for (Map.Entry<String, String> entry : env.entrySet()) {
      result.put(entry.getKey().replaceAll("[^A-Za-z0-9_]", "_"), entry.getValue());
    }

    return result;
  }

  private static Map<String, String> putVNFCInstanceHostnameInMap(
      Map<String, String> map, VNFCInstance vnfcInstance) {
    map.put("hostname", vnfcInstance.getHostname());
    return map;
  }

  public static Map<String, String> clearVNFCInstanceHostnameInMap(Map<String, String> map) {
    map.remove("hostname");
    return map;
  }

  public static Map<String, String> clearEnvFromTempValues(
      Map<String, String> env, Map<String, String> tempEnv) {
    for (String key : tempEnv.keySet()) {
      env.remove(key);
    }
    return env;
  }

  private static Map<String, String> putOwnIpAndFloatingIp(
      Map<String, String> map, VNFCInstance vnfcInstance) {
    //Adding own ips
    if (vnfcInstance.getIps() != null) {
      for (Ip ip : vnfcInstance.getIps()) {
        log.debug("Adding net: " + ip.getNetName() + " with value: " + ip.getIp());
        map.put(ip.getNetName(), ip.getIp());
      }
    }

    //Adding own floating ip
    if (vnfcInstance.getFloatingIps() != null) {
      for (Ip fip : vnfcInstance.getFloatingIps()) {
        log.debug("adding floatingIp: " + fip.getNetName() + " = " + fip.getIp());
        map.put(fip.getNetName() + "_floatingIp", fip.getIp());
      }
    }
    return map;
  }

  public static Map<String, String> clearOwnIpAndFloatingIpInEnv(
      Map<String, String> env, VNFCInstance vnfcInstance) {
    //Clearing own ips
    for (Ip ip : vnfcInstance.getIps()) {
      env.remove(ip.getNetName());
    }
    //Clearing own floating ip
    for (Ip fip : vnfcInstance.getFloatingIps()) {
      env.remove(fip.getNetName() + "_floatingIp");
    }
    return env;
  }
}


text:
namespace lldb_private {

class Unwind {
protected:
  // Classes that inherit from Unwind can see and modify these
  Unwind(Thread &thread) : m_thread(thread), m_unwind_mutex() {}

public:
  virtual ~Unwind() {}

  void Clear() {
    std::lock_guard<std::recursive_mutex> guard(m_unwind_mutex);
    DoClear();
  }

  uint32_t GetFrameCount() {
    std::lock_guard<std::recursive_mutex> guard(m_unwind_mutex);
    return DoGetFrameCount();
  }

  uint32_t GetFramesUpTo(uint32_t end_idx) {
    lldb::addr_t cfa;
    lldb::addr_t pc;
    uint32_t idx;
    bool behaves_like_zeroth_frame = (end_idx == 0);

    for (idx = 0; idx < end_idx; idx++) {
      if (!DoGetFrameInfoAtIndex(idx, cfa, pc, behaves_like_zeroth_frame)) {
        break;
      }
    }
    return idx;
  }

  bool GetFrameInfoAtIndex(uint32_t frame_idx, lldb::addr_t &cfa,
                           lldb::addr_t &pc, bool &behaves_like_zeroth_frame) {
    std::lock_guard<std::recursive_mutex> guard(m_unwind_mutex);
    return DoGetFrameInfoAtIndex(frame_idx, cfa, pc, behaves_like_zeroth_frame);
  }

  lldb::RegisterContextSP CreateRegisterContextForFrame(StackFrame *frame) {
    std::lock_guard<std::recursive_mutex> guard(m_unwind_mutex);
    return DoCreateRegisterContextForFrame(frame);
  }

  Thread &GetThread() { return m_thread; }

protected:
  // Classes that inherit from Unwind can see and modify these
  virtual void DoClear() = 0;

  virtual uint32_t DoGetFrameCount() = 0;

  virtual bool DoGetFrameInfoAtIndex(uint32_t frame_idx, lldb::addr_t &cfa,
                                     lldb::addr_t &pc,
                                     bool &behaves_like_zeroth_frame) = 0;

  virtual lldb::RegisterContextSP
  DoCreateRegisterContextForFrame(StackFrame *frame) = 0;

  Thread &m_thread;
  std::recursive_mutex m_unwind_mutex;

private:
  DISALLOW_COPY_AND_ASSIGN(Unwind);
};

} // namespace lldb_private

#endif // liblldb_Unwind_h_


text:
<?php
// Instance Values.
$controls = -1; // for unique identifying of bootstrap controls without given id's.
class BootStrap {
  static function generateControlNumber() {
    ++$GLOBALS['controls'];
    return $GLOBALS['controls'];
  }
  static function getLastControlNumber() {
    return $GLOBALS['controls'];
  }
}
class BSJumbotron extends BootStrap {
  private $top;
  private $bottom;
  private $jumbo;
  function __construct() {
    $this->jumbo = new DIV();
    $a = func_num_args();
    switch ($a) {
      case 0:
        break;
      case 1:
        $this->jumbo-setId(func_get_arg(0));
        break;
      default:
        throw new InvalidArgsException("Wrong Argument Count");
    }
    $this->jumbo->addClass("jumbotron");
  }
  function setTopContent($top) {
    $this->top = $top;
  }
  function setTopText($text) {
    $this->top = new P($text); // Supposed to be Header
  }
  function setBottomContent($bottom) {
    $this->bottom = $bottom;
  }
  function setBottomText($text) {
    $this->bottom = new P($text);
  }
  function addCSSRule($rule, $val) {
    $this->jumbo->addCssRule($rule, $val);
  }
  function getView() {
    if ($this->top != null || $this->bottom != null) {
      $this->top == null ? "" : $this->jumbo->appendChild($this->top);
      $this->bottom == null ? "" : $this->jumbo->appendChild($this->bottom);
      return $this->jumbo->getView();
    }
    return "";
  }
}
class BSColumn extends BootStrap {
  private $devices = array("md");
  private $span;
  private $padding; // Column padding.
  private $view; // The HTML Object in the column.
  function __construct($span) {
    $this->span = $span;
  }
  function setSpan($span) {
    $this->span = $span;
  }
  function getSpan() {
    return $this->span;
  }
  function setDeviceConfig($device) {
    $this->devices = array($device);
  }
  function addDeviceConfig($device) {
    $this->devices[] = $device;
  }
  function setContent($content) {
    $this->view = $content;
  }
  function setPadding($padding) {
    $this->padding = $padding;
  }
  function getColumn() {
    $column = new DIV();
    if ($this->padding != 0) {
      $column->addCssRule("padding", $this->padding);
    }
    if (count($this->devices) > 1) {
      foreach ($this->devices as $device) {
        $column->addClass("col-$device-$this->span");
      }
    } else {
      $column->addClass("col-" . $this->devices[0] . "-$this->span");
    }
    $this->view == null ? "" : $column->appendChild($this->view);
    return $column;
  }
}
class BSRow extends BootStrap {
  private $devices = array("md");
  private $columns = array();
  function addColumn($column) {
    if (count($this->columns) > 0) {
      $x = 0;
      foreach ($this->columns as $col) {
        $x += $col->getSpan();
      }
      if ($x > 12) {
        throw new BSSpanLimitException($x);
      }
    } elseif ($column->getSpan() > 12) {
      throw new BSSpanLimitException($column->getSpan());
    }
    $this->columns[] = $column;
  }
  function getView() {
    $row = new DIV();
    $row->addClass("row");
    foreach ($this->columns as $column) {
      $row->appendChild($column->getColumn());
    }
    return $row->getView();
  }
}
class BSFormInput extends BootStrap {
  private $root;
  private $label;
  protected $input;
  function __construct() {
    // (0)id, (1)type, (2)label
    // (0)id, (1)type, (2)label, (3)name
    // (0)id, (1)type, (2)label, (3)name, (4)placeholder
    $a = func_num_args();
    if ($a >= 3) {
      $this->root = new DIV("bs-" . (func_get_arg(0) == "" ? BootStrap::generateControlNumber() : func_get_arg(0)));
      $this->label = new Label((func_get_arg(0) == "" ? BootStrap::getLastControlNumber() : func_get_arg(0)), func_get_arg(2));
      $this->input = new FormInput((func_get_arg(0) == "" ? BootStrap::getLastControlNumber() : func_get_arg(0)));
    }
    switch ($a) {
      case 0:
        break;
      case 5:
        $this->input->setPlaceholder(func_get_arg(4));
      case 4:
        $this->input->setName(func_get_arg(3));
      case 3:
        $this->input->setType(func_get_arg(1));
        break;
      default:
        throw new InvalidArgsException("Wrong argument count");
    }
  }
  function setId($id) {
    $this->root == null ? $this->root = new DIV("bs-$id") : $this->root->setId("bs-$id");
    $this->input == null ? $this->input = new FormInput($id) : $this->input->setId($id);
    $this->label == null ? $this->label = new Label($id, "") : $this->label->setFor($id);
  }
  function setLabel($text) {
    $this->label == null ? $this->label = new Label("", $text) : $this->label->setText($text);
  }
  function setType($type) {
    if ($this->input == null) {
      $this->input = new FormInput("");
      $this->input->setType($type);
    } else {
      $this->input->setType($type);
    }
  }
  function setName($name) {
    $this->input->setName($name);
  }
  function setPlaceholder($placeholder) {
    $this->input->setPlaceholder($placeholder);
  }
  function getView() {
    if ($this->input != null) {
      $this->root->addClass("form-group");
      $this->root->appendChild($this->label);
      $this->input->addClass("form-control");
      $this->root->appendChild($this->input);
      return $this->root->getView();
    }
    return "";
  }
}
class BSEmailInput extends BSFormInput {
  function __construct() {
    // (0)id, (1)label
    // (0)id, (1)label, (2)name
    // (0)id, (1)label, (2)name, (3)placeholder
    $a = func_num_args();
    switch ($a) {
      case 2:
        parent::__construct(func_get_arg(0), "email", func_get_arg(1));
        break;
    }
    if ($a >= 2) {
      $this->root = new DIV("bs-" . (func_get_arg(0) == "" ? BootStrap::generateControlNumber() : func_get_arg(0)));
      $this->label = new Label((func_get_arg(0) == "" ? BootStrap::getLastControlNumber() : func_get_arg(0)), func_get_arg(1));
      //$this->input = new BSFormInput((func_get_arg(0) == "" ? BootStrap::getLastControlNumber() : func_get_arg(0)));
      $this->input->setType("email");
    }
    switch ($a) {
      case 0:
        break;
      case 4:
        $this->input->setPlaceholder(func_get_arg(3));
      case 3:
        $this->input->setName(func_get_arg(2));
        break;
      case 2:
        break;
      default:
        throw new InvalidArgsException("Wrong argument count");
    }
    return $this;
  }
  function setType($type) {
    // No Action Here.
  }
}
class BSForm extends BootStrap {
  private $form;
  function __construct() {
    $this->form = new Form();
  }
  function useGet() {
    $this->form->useGet();
  }
  function usePost() {
    $this->form->usePost();
  }
  function setAction($action) {
    $this->form->setAction($action);
  }
  function addInput() {
    // TODO overload
    $a = func_num_args();
    switch($a) {
      case 1:
        $this->form->appendChild(func_get_arg(0));
        break;
      case 3:
      // type, name, placeholder.
      case 4:
        // type, id, name, placeholder.
    }
  }
  function appendChild() {

  }
  function getView() {
    return $this->form->getView();
  }
}
/**
 * BootStrap Progress Bar
 */
class BSProgressBar extends BootStrap {
  private $text; // Text to show within ptogress bar.
  private $showValue; // boolean value to show progress value or not.
  private $value;// the progress value.
  private $id; // id of progress bar.
  private $screenReaderText;
  /**
   * [__construct BootStrap Progress Bar Constructor]
   */
  function __construct() {
    //(0)value
    //(0)id, (1)value
    //(0)id, (1)value (2)showValue
    //(0)id, (1)value, (2)showValue, (3)text
    $a = func_num_args();
    switch($a) {
      case 4:
        $this->text = func_get_arg(3);
      case 3:
        $this->showValue = func_get_arg(2);
      case 2:
        $this->value = func_get_arg(1);
        $this->id = func_get_arg(0);
        break;
      case 1:
        $this->value = func_get_arg(0);
        break;
      default:
        throw new InvalidArgsException("No Arguments");
    }
  }
  function getView() {
    $bar = new DIV("bs-" . ($this->id == "" ? BootStrap::generateControlNumber() : $this->id));
    $bar->addClass("progress");
    $realBar = new DIV();
    $realBar->addClass("progress-bar");
    $realBar->setAttribute("role", "progressbar");
    $realBar->setAttribute("aria-valuenow", $this->value);
    $realBar->setAttribute("aria-valuemin", 0);
    $realBar->setAttribute("aria-valuemax", 100);
    $realBar->addCssRule("width", $this->value . "%");
    if ($this->screenReaderText != "") {
      $label = new Span($this->screenReaderText);
      $label->addClass("sr-only");
      $realBar->appendChild($label);
    }
    if ($this->showValue) {
      $label = new Span($this->value . "%");
      $realBar->appendChild($label);
    }
    $bar->appendChild($realBar);
    return $bar->getView();
  }
}
?>


text:
/**
 *
 */
package com.yzong.dsf14.mapred.framework;

import java.io.File;
import java.util.Queue;
import java.util.concurrent.SynchronousQueue;

import org.apache.commons.lang.RandomStringUtils;

import com.yzong.dsf14.mapred.dfs.DfsConfig;

/**
 * @author Jimmy Zong <yzong@cmu.edu>
 *
 */
public class MapRedController {

  public DfsConfig DfsConfig;
  public MapRedConfig MapRedConfig;
  public String SessionID;
  public Queue<MapRedJob> JobQueue;
  public String DirPath;

  public MapRedController(DfsConfig dfsStatus, MapRedConfig mrStatus) {
    this.MapRedConfig = mrStatus;
    this.SessionID = RandomStringUtils.randomAlphanumeric(8);
    System.out.printf("Initializing MapReduce session `%s`...\n", SessionID);
    this.MapRedConfig = mrStatus; // Save cluster info
    this.JobQueue = new SynchronousQueue<MapRedJob>();
    /* Create a `tmp` directory for holding temp files */
    new File("./tmp-MR-" + SessionID).mkdir();
    this.DirPath = "./tmp-MR-" + SessionID;
  }

  public boolean waitForMR() {
    return false;
  }
}


text:
package com.blazebit.message.apt;

import com.blazebit.i18n.LocaleUtils;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.ObjectWrapper;
import freemarker.template.Template;
import org.apache.deltaspike.core.api.message.MessageBundle;

import javax.annotation.processing.SupportedSourceVersion;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.ElementKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic.Kind;
import javax.tools.FileObject;
import javax.tools.JavaFileObject;
import javax.tools.StandardLocation;
import java.io.*;
import java.lang.annotation.Annotation;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Christian
 */
@SupportedSourceVersion(SourceVersion.RELEASE_6)
public abstract class MessageBundleProcessor extends AbstractInterfaceProcessor<MessageBundleElementInfo, MessageBundleInfo2> {

    @Override
    protected Set<Class<? extends Annotation>> getAnnotationsToProcess() {
        Set<Class<? extends Annotation>> classes = new HashSet<Class<? extends Annotation>>();
        classes.add(MessageBundle.class);
        return classes;
    }

    @Override
    protected MessageBundleInfo2 processElement(InterfaceInfo<MessageBundleElementInfo> interfaceInfo, Class<? extends Annotation> annotationClass) {
        if (interfaceInfo.getElement().getKind() != ElementKind.INTERFACE) {
            processingEnv.getMessager().printMessage(Kind.ERROR, "The annotation '" + annotationClass.getName() + "' can only be applied on interfaces!", interfaceInfo.getElement());
        }

        TypeMirror serializableType = processingEnv.getElementUtils().getTypeElement(Serializable.class.getName()).asType();
        TypeMirror interfaceType = interfaceInfo.getElement().asType();

        if (!processingEnv.getTypeUtils().isSubtype(interfaceType, serializableType)) {
            processingEnv.getMessager().printMessage(Kind.ERROR, "The message bundle interface must extend java.io.Serializable!", interfaceInfo.getElement());
        }

        String qualifiedEnumClassName = getQualifiedEnumClassName(interfaceInfo);
        String simpleEnumClassName = getSimpleEnumClassName(interfaceInfo);
        String propertiesBasePath = getPropertiesBasePath(interfaceInfo);
        String propertiesBaseName = getPropertiesBaseName(interfaceInfo);
        String templateLocation = getTemplateLocation(interfaceInfo);
        Collection<Locale> locales = getLocales(interfaceInfo);
        MessageBundleInfo2 messageBundleInfo = new MessageBundleInfo2(interfaceInfo, qualifiedEnumClassName, simpleEnumClassName, propertiesBasePath, propertiesBaseName, templateLocation, locales);

        validatePropertiesFiles(messageBundleInfo);

        return messageBundleInfo;
    }

    protected File getResourceFile(String propertiesBasePath, String propertiesFileName) {
        try {
            FileObject fileObject = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, propertiesBasePath, propertiesFileName);
            return new File(fileObject.toUri());
        } catch (FileNotFoundException ex) {
            throw new IllegalArgumentException("Could not find the properties file '" + propertiesFileName + "' at the location '" + propertiesBasePath + "'!", ex);
        } catch (IOException ex) {
            throw new IllegalArgumentException("Could not load the properties file '" + propertiesFileName + "' from the location '" + propertiesBasePath + "'!", ex);
        }
    }

    protected String getPropertiesFileName(String propertiesBaseName, Locale locale) {
        StringBuilder sb = new StringBuilder(propertiesBaseName);

        if (locale.getLanguage() != null && !locale.getLanguage().isEmpty()) {
            sb.append('_').append(locale.getLanguage());
        }

        if (locale.getCountry() != null && !locale.getCountry().isEmpty()) {
            sb.append('_').append(locale.getCountry());
        }

        sb.append(".properties");

        return sb.toString();
    }

    protected String getQualifiedEnumClassName(InterfaceInfo<MessageBundleElementInfo> interfaceInfo) {
        return interfaceInfo.getQualifiedName() + "Enum";
    }

    protected String getSimpleEnumClassName(InterfaceInfo<MessageBundleElementInfo> interfaceInfo) {
        return interfaceInfo.getSimpleName() + "Enum";
    }

    protected String getTemplateLocation(InterfaceInfo<MessageBundleElementInfo> interfaceInfo) {
        MessageBundleConfig config = interfaceInfo.getElement().getAnnotation(MessageBundleConfig.class);
        return config.templateLocation();
    }

    protected String getPropertiesBasePath(InterfaceInfo<MessageBundleElementInfo> interfaceInfo) {
        MessageBundleConfig config = interfaceInfo.getElement().getAnnotation(MessageBundleConfig.class);
        String basePath = config.base();

        if (basePath.isEmpty()) {
            basePath = interfaceInfo.getQualifiedName().replaceAll("\\.", "/");
        }

        int slashIndex = basePath.lastIndexOf('/');

        if (slashIndex == -1) {
            return "";
        }

        return basePath.substring(0, slashIndex);
    }

    protected String getPropertiesBaseName(InterfaceInfo<MessageBundleElementInfo> interfaceInfo) {
        MessageBundleConfig config = interfaceInfo.getElement().getAnnotation(MessageBundleConfig.class);
        String basePath = config.base();

        if (basePath.isEmpty()) {
            basePath = interfaceInfo.getQualifiedName().replaceAll("\\.", "/");
        }

        int slashIndex = basePath.lastIndexOf('/');

        if (slashIndex == -1) {
            return basePath;
        }

        return basePath.substring(slashIndex + 1);
    }

    protected Collection<Locale> getLocales(InterfaceInfo<MessageBundleElementInfo> interfaceInfo) {
        MessageBundleConfig config = interfaceInfo.getElement().getAnnotation(MessageBundleConfig.class);
        Collection<Locale> locales = new ArrayList<Locale>(config.locales().length);

        for (String localeString : config.locales()) {
            locales.add(LocaleUtils.getLocale(localeString));
        }

        return locales;
    }

    @Override
    protected MessageBundleElementInfo processMethod(InterfaceMethodInfo methodInfo) {
        String enumKey = getEnumKey(methodInfo);
        MessageBundleElementInfo messageBundleElementInfo = new MessageBundleElementInfo(methodInfo, enumKey);

        if (validateMethod(messageBundleElementInfo)) {
            return messageBundleElementInfo;
        }

        return null;
    }

    protected boolean validateMethod(MessageBundleElementInfo messageBundleElementInfo) {
        String returnTypeName = messageBundleElementInfo.getElement().getReturnType().toString();
        String expectedReturnTypeName = String.class.getName();

        if (!messageBundleElementInfo.getName().startsWith("get") || !returnTypeName.equals(expectedReturnTypeName)) {
            String msg = "Only getter methods with the return type '" + expectedReturnTypeName + "' are allowed!";
            processingEnv.getMessager().printMessage(Kind.ERROR, msg, messageBundleElementInfo.getElement());
            return false;
        }

        return true;
    }

    protected abstract String getEnumKey(InterfaceMethodInfo methodInfo);

    @Override
    protected void processInterfaceInfo(MessageBundleInfo2 messageBundleInfo) {
        File enumClassJavaFile = getJavaSourceFile(messageBundleInfo.getPackageName(), messageBundleInfo.getSimpleEnumClassName());

        if (enumClassJavaFile.lastModified() == messageBundleInfo.getLastModified()) {
            // Skip unchanged files
            return;
        }

        Writer writer = null;

        try {
            JavaFileObject jfo = processingEnv.getFiler().createSourceFile(messageBundleInfo.getQualifiedEnumClassName());
            writer = jfo.openWriter();
            generateEnumClass(messageBundleInfo, writer);
        } catch (Exception ex) {
            String msg = "Error while generating enum class!";
            printMessage(Kind.ERROR, msg, messageBundleInfo.getElement(), ex);
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    // Ignore
                }
            }
        }

        enumClassJavaFile.setLastModified(messageBundleInfo.getLastModified());
    }

    protected void generateEnumClass(MessageBundleInfo2 info, Writer writer) throws Exception {
        Map<String, Object> parameters = getTemplateParameters(info);
        Template template = getTemplate(info);
        template.process(parameters, writer);
    }

    protected Template getTemplate(MessageBundleInfo2 info) throws IOException {
        final Configuration configuration = new Configuration();
        configuration.setTemplateLoader(new ClassTemplateLoader(MessageBundleProcessor.class, "/"));
        configuration.setAutoFlush(true);
        configuration.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);
        return configuration.getTemplate(info.getTemplateLocation());
    }

    protected Map<String, Object> getTemplateParameters(MessageBundleInfo2 info) {
        Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("packageName", info.getPackageName());
        parameters.put("baseName", new StringBuilder(info.getPropertiesBasePath()).append('/').append(info.getPropertiesBaseName()));
        parameters.put("enumName", info.getSimpleEnumClassName());

        List<String> locales = new ArrayList<String>(info.getLocales().size());
        for (Locale locale : info.getLocales()) {
            locales.add(locale.toString());
        }
        Collections.sort(locales);
        parameters.put("locales", locales);

        List<String> keys = new ArrayList<String>(info.getInterfaceMethodInfos().size());
        for (MessageBundleElementInfo elementInfo : info.getInterfaceMethodInfos()) {
            keys.add(elementInfo.getEnumKey());
        }
        Collections.sort(keys);
        parameters.put("keys", keys);
        return parameters;
    }

    protected void validatePropertiesFiles(MessageBundleInfo2 messageBundleInfo) {
        for (Locale locale : messageBundleInfo.getLocales()) {
            String propertiesFileName = getPropertiesFileName(messageBundleInfo.getPropertiesBaseName(), locale);

            try {
                File propertiesFile = getResourceFile(messageBundleInfo.getPropertiesBasePath(), propertiesFileName);
                Properties properties = new Properties();
                properties.load(new InputStreamReader(new FileInputStream(propertiesFile), "UTF-8"));

                for (MessageBundleElementInfo elementInfo : messageBundleInfo.getInterfaceMethodInfos()) {
                    String enumKey = elementInfo.getEnumKey();
                    String propertiesValue = properties.remove(enumKey).toString();

                    if (propertiesValue == null) {
                        String msg = "The entry for the enum key '" + enumKey + "' is missing in the properties file '" + propertiesFileName + "'!";
                        processingEnv.getMessager().printMessage(Kind.ERROR, msg, elementInfo.getElement());
                    } else {
                        validatePropertiesFileEntry(elementInfo, locale, propertiesValue);
                    }
                }

                for (Object propertiesKey : properties.keySet()) {
                    String msg = "The entry '" + propertiesKey + "' in the properties file '" + propertiesFileName + "' has no corresponding enum key!";
                    processingEnv.getMessager().printMessage(Kind.ERROR, msg, messageBundleInfo.getElement());
                }
            } catch (Exception ex) {
                printMessage(Kind.ERROR, "Error while loading properties files.", messageBundleInfo.getElement(), ex);
            }
        }
    }

    protected void validatePropertiesFileEntry(MessageBundleElementInfo elementInfo, Locale locale, String propertiesValue) {
        int methodParameterCount = elementInfo.getQualifiedParameterTypeNames().size();
        int propertiesValueParameterCount = getParameterCount(propertiesValue);

        if (methodParameterCount != propertiesValueParameterCount) {
            String msg = "The method accepts " + methodParameterCount + " parameters, but the properties entry '"
                    + elementInfo.getEnumKey() + "' for the locale '" + locale.toString() + "' requires " + propertiesValueParameterCount + " parameters!";
            processingEnv.getMessager().printMessage(Kind.ERROR, msg, elementInfo.getElement());
        }
    }

    private static final Pattern PROPERTY_VALUE_PARAMETER_PATTERN = Pattern.compile("\\{(.*?)\\}");

    private static int getParameterCount(final String value) {
        int count = 0;
        if (value != null) {
            final Matcher matcher = PROPERTY_VALUE_PARAMETER_PATTERN.matcher(value);
            while (matcher.find()) {
                count++;
            }
        }
        return count;
    }
}


text:
![Paul Klee - Color Chart (1931)](klee.jpg)

## Colors

We haven't much of a chance to talk about GLSL vector types. Before going further it's important to learn more about these variables and the subject of colors is a great way to find out more about them.

If you are familiar with object oriented programming paradigms you've probably noticed that we have been accessing the data inside the vectors like any regular C-like `struct`.

```glsl
vec3 red = vec3(1.0,0.0,0.0);
red.x = 1.0;
red.y = 0.0;
red.z = 0.0;
```

Defining color using an *x*, *y* and *z* notation can be confusing and misleading, right? That's why there are other ways to access this same information, but with different names. The values of `.x`, `.y` and `.z` can also be called `.r`, `.g` and `.b`, and `.s`, `.t` and `.p`. (`.s`, `.t` and `.p` are usually used for spatial coordinates of a texture, which we'll see in a later chapter.) You can also access the data in a vector by using the index position, `[0]`, `[1]` and `[2]`.

The following lines show all the ways to access the same data:

```glsl
vec4 vector;
vector[0] = vector.r = vector.x = vector.s;
vector[1] = vector.g = vector.y = vector.t;
vector[2] = vector.b = vector.z = vector.p;
vector[3] = vector.a = vector.w = vector.q;
```

These different ways of pointing to the variables inside a vector are just nomenclatures designed to help you write clear code. This flexibility embedded in shading language is a door for you to start thinking interchangably about color and space coordinates.

Another great feature of vector types in GLSL is that the properties can be combined in any order you want, which makes it easy to cast and mix values. This ability is called *swizzle*.

```glsl
vec3 yellow, magenta, green;

// Making Yellow
yellow.rg = vec2(1.0);  // Assigning 1. to red and green channels
yellow[2] = 0.0;        // Assigning 0. to blue channel

// Making Magenta
magenta = yellow.rbg;   // Assign the channels with green and blue swapped

// Making Green
green.rgb = yellow.bgb; // Assign the blue channel of Yellow (0) to red and blue channels
```

#### For your toolbox

You might not be used to picking colors with numbers - it can be very counterintuitive. Lucky for you, there are a lot of smart programs that make this job easy. Find one that fits your needs and then train it to deliver colors in `vec3` or `vec4` format. For example, here are the templates I use on [Spectrum](http://www.eigenlogik.com/spectrum/mac):

```
vec3({{rn}},{{gn}},{{bn}})
vec4({{rn}},{{gn}},{{bn}},1.0)
```

### Mixing color

Now that you know how colors are defined, it's time to integrate this with our previous knowledge. In GLSL there is a very useful function, [`mix()`](../glossary/?search=mix), that lets you mix two values in percentages. Can you guess what the percentage range is? Yes, values between 0.0 and 1.0! Which is perfect for you, after those long hours practicing your karate moves with the fence - it is time to use them!

![](mix-f.jpg)

Check the following code at line 18 and see how we are using the absolute values of a sin wave over time to mix `colorA` and `colorB`.

Show off your skills by:

* Make an expressive transition between colors. Think of a particular emotion. What color seems most representative of it? How does it appear? How does it fade away? Think of another emotion and the matching color for it. Change the beginning and ending color of the above code to match those emotions. Then animate the transition using shaping functions. Robert Penner developed a series of popular shaping functions for computer animation known as [easing functions](http://easings.net/), you can use [this example](../edit.php#06/easing.frag) as research and inspiration but the best result will come from making your own transitions.

### Playing with gradients

The [`mix()`](../glossary/?search=mix) function has more to offer. Instead of a single `float`, we can pass a variable type that matches the two first arguments, in our case a `vec3`. By doing that we gain control over the mixing percentages of each individual color channel, `r`, `g` and `b`.

![](mix-vec.jpg)

Take a look at the following example. Like the examples in the previous chapter, we are hooking the transition to the normalized *x* coordinate and visualizing it with a line. Right now all the channels go along the same line.

Now, uncomment line number 25 and watch what happens. Then try uncommenting lines 26 and 27. Remember that the lines visualize the amount of `colorA` and `colorB` to mix per channel.

You probably recognize the three shaping functions we are using on lines 25 to 27. Play with them! It's time for you to explore and show off your skills from the previous chapter and make interesting gradients. Try the following exercises:

![William Turner - The Fighting Temeraire (1838)](turner.jpg)

* Compose a gradient that resembles a William Turner sunset

* Animate a transition between a sunrise and sunset using `u_time`.

* Can you make a rainbow using what we have learned so far?

* Use the `step()` function to create a colorful flag.

### HSB

We can't talk about color without speaking about color space. As you probably know there are different ways to organize color besides by red, green and blue channels.

[HSB](http://en.wikipedia.org/wiki/HSL_and_HSV) stands for Hue, Saturation and Brightness (or Value) and is a more intuitive and useful organization of colors. Take a moment to read the `rgb2hsv()` and `hsv2rgb()` functions in the following code.

By mapping the position on the x axis to the Hue and the position on the y axis to the Brightness, we obtain a nice spectrum of visible colors. This spatial distribution of color can be very handy; it's more intuitive to pick a color with HSB than with RGB.

### HSB in polar coordinates

HSB was originally designed to be represented in polar coordinates (based on the angle and radius) instead of cartesian coordinates (based on x and y). To map our HSB function to polar coordinates we need to obtain the angle and distance from the center of the billboard to the pixel coordinate. For that we will use the [`length()`](../glossary/?search=length) function and [`atan(y,x)`](../glossary/?search=atan) (which is the GLSL version of the commonly used `atan2(y,x)`).

When using vector and trigonometric functions, `vec2`, `vec3` and `vec4` are treated as vectors even when they represent colors. We will start treating colors and vectors similarly, in fact you will come to find this conceptual flexibility very empowering.

**Note:** If you were wondering, there are more geometric functions besides [`length`](../glossary/?search=length) like: [`distance()`](../glossary/?search=distance), [`dot()`](../glossary/?search=dot), [`cross`](../glossary/?search=cross), [`normalize()`](../glossary/?search=normalize), [`faceforward()`](../glossary/?search=faceforward), [`reflect()`](../glossary/?search=reflect) and [`refract()`](../glossary/?search=refract). Also GLSL has special vector relational functions such as: [`lessThan()`](../glossary/?search=lessThan), [`lessThanEqual()`](../glossary/?search=lessThanEqual), [`greaterThan()`](../glossary/?search=greaterThan), [`greaterThanEqual()`](../glossary/?search=greaterThanEqual), [`equal()`](../glossary/?search=equal) and [`notEqual()`](../glossary/?search=notEqual).

Once we obtain the angle and length we need to "normalize" their values to the range between 0.0 to 1.0. On line 27, [`atan(y,x)`](../glossary/?search=atan) will return an angle in radians between -PI and PI (-3.14 to 3.14), so we need to divide this number by `TWO_PI` (defined at the top of the code) to get values between -0.5 to 0.5, which by simple addition we change to the desired range of 0.0 to 1.0. The radius will return a maximum of 0.5 (because we are calculating the distance from the center of the viewport) so we need to double this range (by multiplying by two) to get a maximum of 1.0.

As you can see, our game here is all about transforming and mapping ranges to the 0.0 to 1.0 that we like.

Try the following exercises:

* Modify the polar example to get a spinning color wheel, just like the waiting mouse icon.

* Use a shaping function together with the conversion function from HSB to RGB to expand a particular hue value and shrink the rest.

![William Home Lizars - Red, blue and yellow spectra, with the solar spectrum (1834)](spectrums.jpg)

* If you look closely at the color wheel used on color pickers (see the image below), they use a different spectrum according to RYB color space. For example, the opposite color of red should be green, but in our example it is cyan. Can you find a way to fix that in order to look exactly like the following image? [Hint: this is a great moment to use shaping functions.]

![](colorwheel.png)

* Read [Josep's Alvers book Interaction of Color](http://www.goodreads.com/book/show/111113.Interaction_of_Color) and use the following shaders examples as practice.

#### Note about functions and arguments

Before jumping to the next chapter let's stop and rewind. Go back and take look at the functions in previous examples. You will notice `in` before the type of the arguments. This is a [*qualifier*](http://www.shaderific.com/glsl-qualifiers/#inputqualifier) and in this case it specifies that the variable is read only. In future examples we will see that it is also possible to define arguments as `out` or `inout`. This last one, `inout`, is conceptually similar to passing an argument by reference which will give us the possibility to modify a passed variable.

```glsl
int newFunction(in vec4 aVec4,      // read-only
                out vec3 aVec3,     // write-only
                inout int aInt);    // read-write
```

You may not believe it but now we have all the elements to make cool drawings. In the next chapter we will learn how to combine all our tricks to make geometric forms by *blending* the space. Yep... *blending* the space.