text:
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2010, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.collection
package immutable

import scala.annotation.unchecked.uncheckedVariance
import compat.Platform

import scala.collection.generic._
import scala.collection.mutable.Builder

object Vector extends SeqFactory[Vector] {
  private[immutable] val BF = new GenericCanBuildFrom[Nothing] {
    override def apply() = newBuilder[Nothing]
  }
  @inline implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, Vector[A]] =
    BF.asInstanceOf[CanBuildFrom[Coll, A, Vector[A]]]
  def newBuilder[A]: Builder[A, Vector[A]] = new VectorBuilder[A]
  private[immutable] val NIL = new Vector[Nothing](0, 0, 0)
  @inline override def empty[A]: Vector[A] = NIL
}

// in principle, most members should be private. however, access privileges must
// be carefully chosen to not prevent method inlining

@serializable
final class Vector[+A](startIndex: Int, endIndex: Int, focus: Int) extends IndexedSeq[A]
                 with GenericTraversableTemplate[A, Vector]
                 with IndexedSeqLike[A, Vector[A]]
                 with VectorPointer[A @uncheckedVariance] { self =>

override def companion: GenericCompanion[Vector] = Vector

  //assert(startIndex >= 0, startIndex+"<0")
  //assert(startIndex <= endIndex, startIndex+">"+endIndex)
  //assert(focus >= 0, focus+"<0")
  //assert(focus <= endIndex, focus+">"+endIndex)

  private[immutable] var dirty = false

  def length = endIndex - startIndex

  override def lengthCompare(len: Int): Int = length - len

  @inline override def iterator: VectorIterator[A] = {
    val s = new VectorIterator[A](startIndex, endIndex)
    s.initFrom(this)
    if (dirty) s.stabilize(focus)
    if (s.depth > 1) s.gotoPos(startIndex, startIndex ^ focus)
    s
  }

  // can still be improved
  override /*SeqLike*/
  def reverseIterator: Iterator[A] = new Iterator[A] {
    private var i = self.length
    def hasNext: Boolean = 0 < i
    def next: A =
      if (0 < i) {
        i -= 1
        self(i)
      } else Iterator.empty.next
  }

  // TODO: reverse

  // TODO: check performance of foreach/map etc. should override or not?
  // Ideally, clients will inline calls to map all the way down, including the iterator/builder methods.
  // In principle, escape analysis could even remove the iterator/builder allocations and do it
  // with local variables exclusively. But we're not quite there yet ...

  @deprecated("this method is experimental and will be removed in a future release")
  @inline def foreachFast[U](f: A => U): Unit = iterator.foreachFast(f)
  @deprecated("this method is experimental and will be removed in a future release")
  @inline def mapFast[B, That](f: A => B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
    val b = bf(repr)
    foreachFast(x => b += f(x))
    b.result
  }

  def apply(index: Int): A = {
    val idx = checkRangeConvert(index)
    //println("get elem: "+index + "/"+idx + "(focus:" +focus+" xor:"+(idx^focus)+" depth:"+depth+")")
    getElem(idx, idx ^ focus)
  }

  private def checkRangeConvert(index: Int) = {
    val idx = index + startIndex
    if (0 <= index && idx < endIndex)
      idx
    else
      throw new IndexOutOfBoundsException(index.toString)
  }

  // SeqLike api

  @inline override def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
    // just ignore bf
    updateAt(index, elem).asInstanceOf[That]
  }

  @inline override def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
    // just ignore bf
    appendFront(elem).asInstanceOf[That]
  }

  @inline override def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[Vector[A], B, That]): That = {
    // just ignore bf
    appendBack(elem).asInstanceOf[That]
  }

  override def take(n: Int): Vector[A] = {
    if (n <= 0)
      Vector.empty
    else if (startIndex + n < endIndex)
      dropBack0(startIndex + n)
    else
      this
  }

  override def drop(n: Int): Vector[A] = {
    if (n <= 0)
      this
    else if (startIndex + n < endIndex)
      dropFront0(startIndex + n)
    else
      Vector.empty
  }

  override def takeRight(n: Int): Vector[A] = {
    if (n <= 0)
      Vector.empty
    else if (endIndex - n > startIndex)
      dropFront0(endIndex - n)
    else
      this
  }

  override def dropRight(n: Int): Vector[A] = {
    if (n <= 0)
      this
    else if (endIndex - n > startIndex)
      dropBack0(endIndex - n)
    else
      Vector.empty
  }

  override /*IterableLike*/ def head: A = {
    if (isEmpty) throw new UnsupportedOperationException("empty.head")
    apply(0)
  }

  override /*TraversableLike*/ def tail: Vector[A] = {
    if (isEmpty) throw new UnsupportedOperationException("empty.tail")
    drop(1)
  }

  override /*TraversableLike*/ def last: A = {
    if (isEmpty) throw new UnsupportedOperationException("empty.last")
    apply(length-1)
  }

  override /*TraversableLike*/ def init: Vector[A] = {
    if (isEmpty) throw new UnsupportedOperationException("empty.init")
    dropRight(1)
  }

  override /*IterableLike*/ def slice(from: Int, until: Int): Vector[A] =
    take(until).drop(from)

  override /*IterableLike*/ def splitAt(n: Int): (Vector[A], Vector[A]) = (take(n), drop(n))

  // semi-private api

  private[immutable] def updateAt[B >: A](index: Int, elem: B): Vector[B] = {
    val idx = checkRangeConvert(index)
    val s = new Vector[B](startIndex, endIndex, idx)
    s.initFrom(this)
    s.dirty = dirty
    s.gotoPosWritable(focus, idx, focus ^ idx)  // if dirty commit changes; go to new pos and prepare for writing
    s.display0(idx & 0x1f) = elem.asInstanceOf[AnyRef]
    s
  }

  private def gotoPosWritable(oldIndex: Int, newIndex: Int, xor: Int) = if (dirty) {
    gotoPosWritable1(oldIndex, newIndex, xor)
  } else {
    gotoPosWritable0(newIndex, xor)
    dirty = true
  }

  private def gotoFreshPosWritable(oldIndex: Int, newIndex: Int, xor: Int) = if (dirty) {
    gotoFreshPosWritable1(oldIndex, newIndex, xor)
  } else {
    gotoFreshPosWritable0(oldIndex, newIndex, xor)
    dirty = true
  }

  private[immutable] def appendFront[B>:A](value: B): Vector[B] = {
    if (endIndex != startIndex) {
      var blockIndex = (startIndex - 1) & ~31
      var lo = (startIndex - 1) & 31

      if (startIndex != blockIndex + 32) {
        val s = new Vector(startIndex - 1, endIndex, blockIndex)
        s.initFrom(this)
        s.dirty = dirty
        s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
        s.display0(lo) = value.asInstanceOf[AnyRef]
        s
      } else {

        val freeSpace = ((1<<5*(depth)) - endIndex) // free space at the right given the current tree-structure depth
        val shift = freeSpace & ~((1<<5*(depth-1))-1) // number of elements by which we'll shift right (only move at top level)
        val shiftBlocks = freeSpace >>> 5*(depth-1) // number of top-level blocks

        //println("----- appendFront " + value + " at " + (startIndex - 1) + " reached block start")
        if (shift != 0) {
          // case A: we can shift right on the top level
          debug
          //println("shifting right by " + shiftBlocks + " at level " + (depth-1) + " (had "+freeSpace+" free space)")

          if (depth > 1) {
            val newBlockIndex = blockIndex + shift
            val newFocus = focus + shift
            val s = new Vector(startIndex - 1 + shift, endIndex + shift, newBlockIndex)
            s.initFrom(this)
            s.dirty = dirty
            s.shiftTopLevel(0, shiftBlocks) // shift right by n blocks
            s.debug
            s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // maybe create pos; prepare for writing
            s.display0(lo) = value.asInstanceOf[AnyRef]
            //assert(depth == s.depth)
            s
          } else {
            val newBlockIndex = blockIndex + 32
            val newFocus = focus

            //assert(newBlockIndex == 0)
            //assert(newFocus == 0)

            val s = new Vector(startIndex - 1 + shift, endIndex + shift, newBlockIndex)
            s.initFrom(this)
            s.dirty = dirty
            s.shiftTopLevel(0, shiftBlocks) // shift right by n elements
            s.gotoPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // prepare for writing
            s.display0(shift-1) = value.asInstanceOf[AnyRef]
            s.debug
            s
          }
        } else if (blockIndex < 0) {
          // case B: we need to move the whole structure
          val move = (1 << 5*(depth+1)) - (1 << 5*(depth))
          //println("moving right by " + move + " at level " + (depth-1) + " (had "+freeSpace+" free space)")

          val newBlockIndex = blockIndex + move
          val newFocus = focus + move

          val s = new Vector(startIndex - 1 + move, endIndex + move, newBlockIndex)
          s.initFrom(this)
          s.dirty = dirty
          s.debug
          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex) // could optimize: we know it will create a whole branch
          s.display0(lo) = value.asInstanceOf[AnyRef]
          s.debug
          //assert(s.depth == depth+1)
          s
        } else {
          val newBlockIndex = blockIndex
          val newFocus = focus

          val s = new Vector(startIndex - 1, endIndex, newBlockIndex)
          s.initFrom(this)
          s.dirty = dirty
          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
          s.display0(lo) = value.asInstanceOf[AnyRef]
          //assert(s.depth == depth)
          s
        }

      }
    } else {
      // empty vector, just insert single element at the back
      val elems = new Array[AnyRef](32)
      elems(31) = value.asInstanceOf[AnyRef]
      val s = new Vector(31,32,0)
      s.depth = 1
      s.display0 = elems
      s
    }
  }

  private[immutable] def appendBack[B>:A](value: B): Vector[B] = {
//    //println("------- append " + value)
//    debug()
    if (endIndex != startIndex) {
      var blockIndex = endIndex & ~31
      var lo = endIndex & 31

      if (endIndex != blockIndex) {
        //println("will make writable block (from "+focus+") at: " + blockIndex)
        val s = new Vector(startIndex, endIndex + 1, blockIndex)
        s.initFrom(this)
        s.dirty = dirty
        s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
        s.display0(lo) = value.asInstanceOf[AnyRef]
        s
      } else {
        val shift = startIndex & ~((1<<5*(depth-1))-1)
        val shiftBlocks = startIndex >>> 5*(depth-1)

        //println("----- appendBack " + value + " at " + endIndex + " reached block end")

        if (shift != 0) {
          debug
          //println("shifting left by " + shiftBlocks + " at level " + (depth-1) + " (had "+startIndex+" free space)")
          if (depth > 1) {
            val newBlockIndex = blockIndex - shift
            val newFocus = focus - shift
            val s = new Vector(startIndex - shift, endIndex + 1 - shift, newBlockIndex)
            s.initFrom(this)
            s.dirty = dirty
            s.shiftTopLevel(shiftBlocks, 0) // shift left by n blocks
            s.debug
            s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
            s.display0(lo) = value.asInstanceOf[AnyRef]
            s.debug
            //assert(depth == s.depth)
            s
          } else {
            val newBlockIndex = blockIndex - 32
            val newFocus = focus

            //assert(newBlockIndex == 0)
            //assert(newFocus == 0)

            val s = new Vector(startIndex - shift, endIndex + 1 - shift, newBlockIndex)
            s.initFrom(this)
            s.dirty = dirty
            s.shiftTopLevel(shiftBlocks, 0) // shift right by n elements
            s.gotoPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
            s.display0(32 - shift) = value.asInstanceOf[AnyRef]
            s.debug
            s
          }
        } else {
          val newBlockIndex = blockIndex
          val newFocus = focus

          val s = new Vector(startIndex, endIndex + 1, newBlockIndex)
          s.initFrom(this)
          s.dirty = dirty
          s.gotoFreshPosWritable(newFocus, newBlockIndex, newFocus ^ newBlockIndex)
          s.display0(lo) = value.asInstanceOf[AnyRef]
          //assert(s.depth == depth+1) might or might not create new level!
          if (s.depth == depth+1) {
            //println("creating new level " + s.depth + " (had "+0+" free space)")
            s.debug
          }
          s
        }
      }
    } else {
      val elems = new Array[AnyRef](32)
      elems(0) = value.asInstanceOf[AnyRef]
      val s = new Vector(0,1,0)
      s.depth = 1
      s.display0 = elems
      s
    }
  }

  // low-level implementation (needs cleanup, maybe move to util class)

  private def shiftTopLevel(oldLeft: Int, newLeft: Int) = (depth - 1) match {
    case 0 =>
      display0 = copyRange(display0, oldLeft, newLeft)
    case 1 =>
      display1 = copyRange(display1, oldLeft, newLeft)
    case 2 =>
      display2 = copyRange(display2, oldLeft, newLeft)
    case 3 =>
      display3 = copyRange(display3, oldLeft, newLeft)
    case 4 =>
      display4 = copyRange(display4, oldLeft, newLeft)
    case 5 =>
      display5 = copyRange(display5, oldLeft, newLeft)
  }

  private def zeroLeft(array: Array[AnyRef], index: Int): Unit = {
    var i = 0; while (i < index) { array(i) = null; i+=1 }
  }

  private def zeroRight(array: Array[AnyRef], index: Int): Unit = {
    var i = index; while (i < array.length) { array(i) = null; i+=1 }
  }

  private def copyLeft(array: Array[AnyRef], right: Int): Array[AnyRef] = {
//    if (array eq null)
//      println("OUCH!!! " + right + "/" + depth + "/"+startIndex + "/" + endIndex + "/" + focus)
    val a2 = new Array[AnyRef](array.length)
    Platform.arraycopy(array, 0, a2, 0, right)
    a2
  }
  private def copyRight(array: Array[AnyRef], left: Int): Array[AnyRef] = {
    val a2 = new Array[AnyRef](array.length)
    Platform.arraycopy(array, left, a2, left, a2.length - left)
    a2
  }

  private def preClean(depth: Int) = {
    this.depth = depth
    (depth - 1) match {
      case 0 =>
        display1 = null
        display2 = null
        display3 = null
        display4 = null
        display5 = null
      case 1 =>
        display2 = null
        display3 = null
        display4 = null
        display5 = null
      case 2 =>
        display3 = null
        display4 = null
        display5 = null
      case 3 =>
        display4 = null
        display5 = null
      case 4 =>
        display5 = null
      case 5 =>
    }
  }

  // requires structure is at index cutIndex and writable at level 0
  private def cleanLeftEdge(cutIndex: Int) = {
    if (cutIndex < (1 << 5)) {
      zeroLeft(display0, cutIndex)
    } else
    if (cutIndex < (1 << 10)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5))
    } else
    if (cutIndex < (1 << 15)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
      display2 = copyRight(display2, (cutIndex >>> 10))
    } else
    if (cutIndex < (1 << 20)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
      display3 = copyRight(display3, (cutIndex >>> 15))
    } else
    if (cutIndex < (1 << 25)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
      display3 = copyRight(display3, (cutIndex >>> 15) & 0x1f)
      display4 = copyRight(display4, (cutIndex >>> 20))
    } else
    if (cutIndex < (1 << 30)) {
      zeroLeft(display0, cutIndex & 0x1f)
      display1 = copyRight(display1, (cutIndex >>>  5) & 0x1f)
      display2 = copyRight(display2, (cutIndex >>> 10) & 0x1f)
      display3 = copyRight(display3, (cutIndex >>> 15) & 0x1f)
      display4 = copyRight(display4, (cutIndex >>> 20) & 0x1f)
      display5 = copyRight(display5, (cutIndex >>> 25))
    } else {
      throw new IllegalArgumentException()
    }
  }

  // requires structure is writable and at index cutIndex
  private def cleanRightEdge(cutIndex: Int) = {

    // we're actually sitting one block left if cutIndex lies on a block boundary
    // this means that we'll end up erasing the whole block!!

    if (cutIndex <= (1 << 5)) {
      zeroRight(display0, cutIndex)
    } else
    if (cutIndex <= (1 << 10)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (cutIndex >>>  5))
    } else
    if (cutIndex <= (1 << 15)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
      display2 = copyLeft(display2, (cutIndex >>> 10))
    } else
    if (cutIndex <= (1 << 20)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
      display3 = copyLeft(display3, (cutIndex >>> 15))
    } else
    if (cutIndex <= (1 << 25)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
      display3 = copyLeft(display3, (((cutIndex-1) >>> 15) & 0x1f) + 1)
      display4 = copyLeft(display4, (cutIndex >>> 20))
    } else
    if (cutIndex <= (1 << 30)) {
      zeroRight(display0, ((cutIndex-1) & 0x1f) + 1)
      display1 = copyLeft(display1, (((cutIndex-1) >>>  5) & 0x1f) + 1)
      display2 = copyLeft(display2, (((cutIndex-1) >>> 10) & 0x1f) + 1)
      display3 = copyLeft(display3, (((cutIndex-1) >>> 15) & 0x1f) + 1)
      display4 = copyLeft(display4, (((cutIndex-1) >>> 20) & 0x1f) + 1)
      display5 = copyLeft(display5, (cutIndex >>> 25))
    } else {
      throw new IllegalArgumentException()
    }
  }

  private def requiredDepth(xor: Int) = {
    if (xor < (1 <<  5)) 1
    else if (xor < (1 << 10)) 2
    else if (xor < (1 << 15)) 3
    else if (xor < (1 << 20)) 4
    else if (xor < (1 << 25)) 5
    else if (xor < (1 << 30)) 6
    else throw new IllegalArgumentException()
  }

  private def dropFront0(cutIndex: Int): Vector[A] = {
    var blockIndex = cutIndex & ~31
    var lo = cutIndex & 31

    val xor = cutIndex ^ (endIndex - 1)
    val d = requiredDepth(xor)
    val shift = (cutIndex & ~((1 << (5*d))-1))

    //println("cut front at " + cutIndex + ".." + endIndex + " (xor: "+xor+" shift: " + shift + " d: " + d +")")

/*
    val s = new Vector(cutIndex-shift, endIndex-shift, blockIndex-shift)
    s.initFrom(this)
    if (s.depth > 1)
      s.gotoPos(blockIndex, focus ^ blockIndex)
    s.depth = d
    s.stabilize(blockIndex-shift)
    s.cleanLeftEdge(cutIndex-shift)
    s
*/

    // need to init with full display iff going to cutIndex requires swapping block at level >= d

    val s = new Vector(cutIndex-shift, endIndex-shift, blockIndex-shift)
    s.initFrom(this)
    s.dirty = dirty
    s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
    s.preClean(d)
    s.cleanLeftEdge(cutIndex - shift)
    s
  }

  private def dropBack0(cutIndex: Int): Vector[A] = {
    var blockIndex = (cutIndex - 1) & ~31
    var lo = ((cutIndex - 1) & 31) + 1

    val xor = startIndex ^ (cutIndex - 1)
    val d = requiredDepth(xor)
    val shift = (startIndex & ~((1 << (5*d))-1))

/*
    println("cut back at " + startIndex + ".." + cutIndex + " (xor: "+xor+" d: " + d +")")
    if (cutIndex == blockIndex + 32)
      println("OUCH!!!")
*/
    val s = new Vector(startIndex-shift, cutIndex-shift, blockIndex-shift)
    s.initFrom(this)
    s.dirty = dirty
    s.gotoPosWritable(focus, blockIndex, focus ^ blockIndex)
    s.preClean(d)
    s.cleanRightEdge(cutIndex-shift)
    s
  }

}

final class VectorIterator[+A](_startIndex: Int, _endIndex: Int) extends Iterator[A] with VectorPointer[A @uncheckedVariance] {

  private var blockIndex: Int = _startIndex & ~31
  private var lo: Int = _startIndex & 31
  private var endIndex: Int = _endIndex

  private var endLo = math.min(endIndex - blockIndex, 32)

  def hasNext = _hasNext

  private var _hasNext = blockIndex + lo < endIndex

  def next(): A = {
    if (!_hasNext) throw new NoSuchElementException("reached iterator end")

    val res = display0(lo).asInstanceOf[A]
    lo += 1

    if (lo == endLo) {
      if (blockIndex + lo < endIndex) {
        val newBlockIndex = blockIndex+32
        gotoNextBlockStart(newBlockIndex, blockIndex ^ newBlockIndex)

        blockIndex = newBlockIndex
        endLo = math.min(endIndex - blockIndex, 32)
        lo = 0
      } else {
        _hasNext = false
      }
    }

    res
  }

  // TODO: drop (important?)

  @deprecated("this method is experimental and will be removed in a future release")
  @inline def foreachFast[U](f: A =>  U) { while (hasNext) f(next()) }
}

final class VectorBuilder[A]() extends Builder[A,Vector[A]] with VectorPointer[A @uncheckedVariance] {

  // possible alternative: start with display0 = null, blockIndex = -32, lo = 32
  // to avoid allocating initial array if the result will be empty anyways

  display0 = new Array[AnyRef](32)
  depth = 1

  private var blockIndex = 0
  private var lo = 0

  def += (elem: A): this.type = {
    if (lo >= display0.length) {
      val newBlockIndex = blockIndex+32
      gotoNextBlockStartWritable(newBlockIndex, blockIndex ^ newBlockIndex)
      blockIndex = newBlockIndex
      lo = 0
    }
    display0(lo) = elem.asInstanceOf[AnyRef]
    lo += 1
    this
  }

  def result: Vector[A] = {
    val size = blockIndex + lo
    if (size == 0)
      return Vector.empty
    val s = new Vector[A](0, size, 0) // should focus front or back?
    s.initFrom(this)
    if (depth > 1) s.gotoPos(0, size - 1) // we're currently focused to size - 1, not size!
    s
  }

  def clear: Unit = {
    display0 = new Array[AnyRef](32)
    depth = 1
    blockIndex = 0
    lo = 0
  }
}

private[immutable] trait VectorPointer[T] {
    private[immutable] var depth: Int = _
    private[immutable] var display0: Array[AnyRef] = _
    private[immutable] var display1: Array[AnyRef] = _
    private[immutable] var display2: Array[AnyRef] = _
    private[immutable] var display3: Array[AnyRef] = _
    private[immutable] var display4: Array[AnyRef] = _
    private[immutable] var display5: Array[AnyRef] = _

    // used
    private[immutable] final def initFrom[U](that: VectorPointer[U]): Unit = initFrom(that, that.depth)

    private[immutable] final def initFrom[U](that: VectorPointer[U], depth: Int) = {
      this.depth = depth
      (depth - 1) match {
        case -1 =>
        case 0 =>
          display0 = that.display0
        case 1 =>
          display1 = that.display1
          display0 = that.display0
        case 2 =>
          display2 = that.display2
          display1 = that.display1
          display0 = that.display0
        case 3 =>
          display3 = that.display3
          display2 = that.display2
          display1 = that.display1
          display0 = that.display0
        case 4 =>
          display4 = that.display4
          display3 = that.display3
          display2 = that.display2
          display1 = that.display1
          display0 = that.display0
        case 5 =>
          display5 = that.display5
          display4 = that.display4
          display3 = that.display3
          display2 = that.display2
          display1 = that.display1
          display0 = that.display0
      }
    }

    // requires structure is at pos oldIndex = xor ^ index
    private[immutable] final def getElem(index: Int, xor: Int): T = {
      if (xor < (1 << 5)) { // level = 0
        display0(index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 10)) { // level = 1
        display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 15)) { // level = 2
        display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 20)) { // level = 3
        display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 25)) { // level = 4
        display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else
      if (xor < (1 << 30)) { // level = 5
        display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]((index >> 20) & 31).asInstanceOf[Array[AnyRef]]((index >> 15) & 31).asInstanceOf[Array[AnyRef]]((index >> 10) & 31).asInstanceOf[Array[AnyRef]]((index >> 5) & 31).asInstanceOf[Array[AnyRef]](index & 31).asInstanceOf[T]
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }

    // go to specific position
    // requires structure is at pos oldIndex = xor ^ index,
    // ensures structure is at pos index
    private[immutable] final def gotoPos(index: Int, xor: Int): Unit = {
      if (xor < (1 << 5)) { // level = 0 (could maybe removed)
      } else
      if (xor < (1 << 10)) { // level = 1
        display0 = display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 15)) { // level = 2
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 20)) { // level = 3
        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 25)) { // level = 4
        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 30)) { // level = 5
        display4 = display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]
        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1((index >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }

    // USED BY ITERATOR

    // xor: oldIndex ^ index
    private[immutable] final def gotoNextBlockStart(index: Int, xor: Int): Unit = { // goto block start pos
      if (xor < (1 << 10)) { // level = 1
        display0 = display1((index >> 5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 15)) { // level = 2
        display1 = display2((index >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = display1(0).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 20)) { // level = 3
        display2 = display3((index >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = display2(0).asInstanceOf[Array[AnyRef]]
        display0 = display1(0).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 25)) { // level = 4
        display3 = display4((index >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = display3(0).asInstanceOf[Array[AnyRef]]
        display1 = display2(0).asInstanceOf[Array[AnyRef]]
        display0 = display1(0).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 30)) { // level = 5
        display4 = display5((index >> 25) & 31).asInstanceOf[Array[AnyRef]]
        display3 = display4(0).asInstanceOf[Array[AnyRef]]
        display2 = display3(0).asInstanceOf[Array[AnyRef]]
        display1 = display2(0).asInstanceOf[Array[AnyRef]]
        display0 = display1(0).asInstanceOf[Array[AnyRef]]
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }

    // USED BY BUILDER

    // xor: oldIndex ^ index
    private[immutable] final def gotoNextBlockStartWritable(index: Int, xor: Int): Unit = { // goto block start pos
      if (xor < (1 << 10)) { // level = 1
        if (depth == 1) { display1 = new Array(32); display1(0) = display0; depth+=1}
        display0 = new Array(32)
        display1((index >>  5) & 31) = display0
      } else
      if (xor < (1 << 15)) { // level = 2
        if (depth == 2) { display2 = new Array(32); display2(0) = display1; depth+=1}
        display0 = new Array(32)
        display1 = new Array(32)
        display1((index >>  5) & 31) = display0
        display2((index >> 10) & 31) = display1
      } else
      if (xor < (1 << 20)) { // level = 3
        if (depth == 3) { display3 = new Array(32); display3(0) = display2; depth+=1}
        display0 = new Array(32)
        display1 = new Array(32)
        display2 = new Array(32)
        display1((index >>  5) & 31) = display0
        display2((index >> 10) & 31) = display1
        display3((index >> 15) & 31) = display2
      } else
      if (xor < (1 << 25)) { // level = 4
        if (depth == 4) { display4 = new Array(32); display4(0) = display3; depth+=1}
        display0 = new Array(32)
        display1 = new Array(32)
        display2 = new Array(32)
        display3 = new Array(32)
        display1((index >>  5) & 31) = display0
        display2((index >> 10) & 31) = display1
        display3((index >> 15) & 31) = display2
        display4((index >> 20) & 31) = display3
      } else
      if (xor < (1 << 30)) { // level = 5
        if (depth == 5) { display5 = new Array(32); display5(0) = display4; depth+=1}
        display0 = new Array(32)
        display1 = new Array(32)
        display2 = new Array(32)
        display3 = new Array(32)
        display4 = new Array(32)
        display1((index >>  5) & 31) = display0
        display2((index >> 10) & 31) = display1
        display3((index >> 15) & 31) = display2
        display4((index >> 20) & 31) = display3
        display5((index >> 25) & 31) = display4
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }

    // STUFF BELOW USED BY APPEND / UPDATE

    private[immutable] final def copyOf(a: Array[AnyRef]) = {
      //println("copy")
      if (a eq null) println ("NULL")
      val b = new Array[AnyRef](a.length)
      Platform.arraycopy(a, 0, b, 0, a.length)
      b
    }

    private[immutable] final def nullSlotAndCopy(array: Array[AnyRef], index: Int) = {
      //println("copy and null")
      val x = array(index)
      array(index) = null
      copyOf(x.asInstanceOf[Array[AnyRef]])
    }

    // make sure there is no aliasing
    // requires structure is at pos index
    // ensures structure is clean and at pos index and writable at all levels except 0

    private[immutable] final def stabilize(index: Int) = (depth - 1) match {
      case 5 =>
        display5 = copyOf(display5)
        display4 = copyOf(display4)
        display3 = copyOf(display3)
        display2 = copyOf(display2)
        display1 = copyOf(display1)
        display5((index >> 25) & 31) = display4
        display4((index >> 20) & 31) = display3
        display3((index >> 15) & 31) = display2
        display2((index >> 10) & 31) = display1
        display1((index >>  5) & 31) = display0
      case 4 =>
        display4 = copyOf(display4)
        display3 = copyOf(display3)
        display2 = copyOf(display2)
        display1 = copyOf(display1)
        display4((index >> 20) & 31) = display3
        display3((index >> 15) & 31) = display2
        display2((index >> 10) & 31) = display1
        display1((index >>  5) & 31) = display0
      case 3 =>
        display3 = copyOf(display3)
        display2 = copyOf(display2)
        display1 = copyOf(display1)
        display3((index >> 15) & 31) = display2
        display2((index >> 10) & 31) = display1
        display1((index >>  5) & 31) = display0
      case 2 =>
        display2 = copyOf(display2)
        display1 = copyOf(display1)
        display2((index >> 10) & 31) = display1
        display1((index >>  5) & 31) = display0
      case 1 =>
        display1 = copyOf(display1)
        display1((index >>  5) & 31) = display0
      case 0 =>
    }

    /// USED IN UPDATE AND APPEND BACK

    // prepare for writing at an existing position

    // requires structure is clean and at pos oldIndex = xor ^ newIndex,
    // ensures structure is dirty and at pos newIndex and writable at level 0
    private[immutable] final def gotoPosWritable0(newIndex: Int, xor: Int): Unit = (depth - 1) match {
      case 5 =>
        display5 = copyOf(display5)
        display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31).asInstanceOf[Array[AnyRef]]
        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 4 =>
        display4 = copyOf(display4)
        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 3 =>
        display3 = copyOf(display3)
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 2 =>
        display2 = copyOf(display2)
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 1 =>
        display1 = copyOf(display1)
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      case 0 =>
        display0 = copyOf(display0)
    }

    // requires structure is dirty and at pos oldIndex,
    // ensures structure is dirty and at pos newIndex and writable at level 0
    private[immutable] final def gotoPosWritable1(oldIndex: Int, newIndex: Int, xor: Int): Unit = {
      if (xor < (1 <<  5)) { // level = 0
        display0 = copyOf(display0)
      } else
      if (xor < (1 << 10)) { // level = 1
        display1 = copyOf(display1)
        display1((oldIndex >> 5) & 31) = display0
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31)
      } else
      if (xor < (1 << 15)) { // level = 2
        display1 = copyOf(display1)
        display2 = copyOf(display2)
        display1((oldIndex >>  5) & 31) = display0
        display2((oldIndex >> 10) & 31) = display1
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 20)) { // level = 3
        display1 = copyOf(display1)
        display2 = copyOf(display2)
        display3 = copyOf(display3)
        display1((oldIndex >>  5) & 31) = display0
        display2((oldIndex >> 10) & 31) = display1
        display3((oldIndex >> 15) & 31) = display2
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 25)) { // level = 4
        display1 = copyOf(display1)
        display2 = copyOf(display2)
        display3 = copyOf(display3)
        display4 = copyOf(display4)
        display1((oldIndex >>  5) & 31) = display0
        display2((oldIndex >> 10) & 31) = display1
        display3((oldIndex >> 15) & 31) = display2
        display4((oldIndex >> 20) & 31) = display3
        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else
      if (xor < (1 << 30)) { // level = 5
        display1 = copyOf(display1)
        display2 = copyOf(display2)
        display3 = copyOf(display3)
        display4 = copyOf(display4)
        display5 = copyOf(display5)
        display1((oldIndex >>  5) & 31) = display0
        display2((oldIndex >> 10) & 31) = display1
        display3((oldIndex >> 15) & 31) = display2
        display4((oldIndex >> 20) & 31) = display3
        display5((oldIndex >> 25) & 31) = display4
        display4 = nullSlotAndCopy(display5, (newIndex >> 25) & 31).asInstanceOf[Array[AnyRef]]
        display3 = nullSlotAndCopy(display4, (newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        display2 = nullSlotAndCopy(display3, (newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        display1 = nullSlotAndCopy(display2, (newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        display0 = nullSlotAndCopy(display1, (newIndex >>  5) & 31).asInstanceOf[Array[AnyRef]]
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }

    // USED IN DROP

    private[immutable] final def copyRange(array: Array[AnyRef], oldLeft: Int, newLeft: Int) = {
      val elems = new Array[AnyRef](32)
      Platform.arraycopy(array, oldLeft, elems, newLeft, 32 - math.max(newLeft,oldLeft))
      elems
    }

    // USED IN APPEND
    // create a new block at the bottom level (and possibly nodes on its path) and prepares for writing

    // requires structure is clean and at pos oldIndex,
    // ensures structure is dirty and at pos newIndex and writable at level 0
    private[immutable] final def gotoFreshPosWritable0(oldIndex: Int, newIndex: Int, xor: Int): Unit = { // goto block start pos
      if (xor < (1 << 5)) { // level = 0
        //println("XXX clean with low xor")
      } else
      if (xor < (1 << 10)) { // level = 1
        if (depth == 1) {
          display1 = new Array(32)
          display1((oldIndex >>  5) & 31) = display0
          depth +=1
        }
        display0 = new Array(32)
      } else
      if (xor < (1 << 15)) { // level = 2
        if (depth == 2) {
          display2 = new Array(32)
          display2((oldIndex >> 10) & 31) = display1
          depth +=1
        }
        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        if (display1 == null) display1 = new Array(32)
        display0 = new Array(32)
      } else
      if (xor < (1 << 20)) { // level = 3
        if (depth == 3) {
          display3 = new Array(32)
          display3((oldIndex >> 15) & 31) = display2
          display2 = new Array(32)
          display1 = new Array(32)
          depth +=1
        }
        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        if (display2 == null) display2 = new Array(32)
        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        if (display1 == null) display1 = new Array(32)
        display0 = new Array(32)
      } else
      if (xor < (1 << 25)) { // level = 4
        if (depth == 4) {
          display4 = new Array(32)
          display4((oldIndex >> 20) & 31) = display3
          display3 = new Array(32)
          display2 = new Array(32)
          display1 = new Array(32)
          depth +=1
        }
        display3 = display4((newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        if (display3 == null) display3 = new Array(32)
        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        if (display2 == null) display2 = new Array(32)
        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        if (display1 == null) display1 = new Array(32)
        display0 = new Array(32)
      } else
      if (xor < (1 << 30)) { // level = 5
        if (depth == 5) {
          display5 = new Array(32)
          display5((oldIndex >>  25) & 31) = display4
          display4 = new Array(32)
          display3 = new Array(32)
          display2 = new Array(32)
          display1 = new Array(32)
          depth +=1
        }
        display4 = display5((newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        if (display4 == null) display4 = new Array(32)
        display3 = display4((newIndex >> 20) & 31).asInstanceOf[Array[AnyRef]]
        if (display3 == null) display3 = new Array(32)
        display2 = display3((newIndex >> 15) & 31).asInstanceOf[Array[AnyRef]]
        if (display2 == null) display2 = new Array(32)
        display1 = display2((newIndex >> 10) & 31).asInstanceOf[Array[AnyRef]]
        if (display1 == null) display1 = new Array(32)
        display0 = new Array(32)
      } else { // level = 6
        throw new IllegalArgumentException()
      }
    }

    // requires structure is dirty and at pos oldIndex,
    // ensures structure is dirty and at pos newIndex and writable at level 0
    private[immutable] final def gotoFreshPosWritable1(oldIndex: Int, newIndex: Int, xor: Int): Unit = {
      stabilize(oldIndex)
      gotoFreshPosWritable0(oldIndex, newIndex, xor)
    }

    // DEBUG STUFF

    private[immutable] def debug(): Unit = {
      return
/*
      //println("DISPLAY 5: " + display5 + " ---> " + (if (display5 ne null) display5.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 4: " + display4 + " ---> " + (if (display4 ne null) display4.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 3: " + display3 + " ---> " + (if (display3 ne null) display3.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 2: " + display2 + " ---> " + (if (display2 ne null) display2.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 1: " + display1 + " ---> " + (if (display1 ne null) display1.map(x=> if (x eq null) "." else x + "->" +x.asInstanceOf[Array[AnyRef]].mkString("")).mkString(" ") else "null"))
      //println("DISPLAY 0: " + display0 + " ---> " + (if (display0 ne null) display0.map(x=> if (x eq null) "." else x.toString).mkString(" ") else "null"))
*/
      //println("DISPLAY 5: " + (if (display5 ne null) display5.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 4: " + (if (display4 ne null) display4.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 3: " + (if (display3 ne null) display3.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 2: " + (if (display2 ne null) display2.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 1: " + (if (display1 ne null) display1.map(x=> if (x eq null) "." else x.asInstanceOf[Array[AnyRef]].deepMkString("[","","]")).mkString(" ") else "null"))
      //println("DISPLAY 0: " + (if (display0 ne null) display0.map(x=> if (x eq null) "." else x.toString).mkString(" ") else "null"))
    }

}


text:
package com.spiralboss;
import java.util.Calendar;
import java.util.Date;

import org.json.simple.JSONObject;

public class BlogResult {

	/**
	 * Title of the blog post. Contains HTML to bold query keywords found in the title.
	 */
	public String Title;

	/**
	 * A short preview extracted from the blog post. Contains HTML to bold query keywords found in the title.
	 */
	public String Abstract;

	/**
	 * The blog provider the blog is hosted by.
	 */
	public String Provider;

	/**
	 * The URL of the blog post containing HTML to bold query keywords found in the URL.
	 */
	public String DisplayURL;

	/**
	 * The date of the blog post.
	 */
	public Date Date;

	/**
	 * UNIX timestamp of the date of the blog post.
	 */
	public long Timestamp;

	/**
	 * Relevancy of the blog post to the query.
	 */
	public float Score;

	/**
	 * Words that match the query.
	 */
	public String KeyTerms;

	/**
	 * The name of the blog post's author.
	 */
	public String Author;

	/**
	 * URL of an associated image that may be part of the blog.
	 */
	public String IconURL;

	/**
	 * URL for clickable link to the blog post.
	 */
	public String ClickURL;

	BlogResult(JSONObject jsonObject) {
		this.Title = (String)jsonObject.get("title");
		this.Abstract = (String)jsonObject.get("abstract");
		this.Provider = (String)jsonObject.get("provider");
		this.DisplayURL = (String)jsonObject.get("dispurl");
		this.KeyTerms = (String)jsonObject.get("keyterms");
		this.Author = (String)jsonObject.get("author");
		this.IconURL = (String)jsonObject.get("icon");
		this.ClickURL = (String)jsonObject.get("clickurl");

		String dateString = (String)jsonObject.get("date");
		if (dateString == null || dateString.length() == 0) {
			this.Timestamp = 0;
			this.Date = null;
		}
		else {
			String[] splitDate = dateString.split("\\/");
			int year = Integer.parseInt(splitDate[0]);
			int month = Integer.parseInt(splitDate[1]);
			int day = Integer.parseInt(splitDate[2]);
			Calendar cal = Calendar.getInstance();
			cal.set(year, month - 1, day);
			this.Date = cal.getTime();
			this.Timestamp = Math.round(this.Date.getTime() / 1000);
		}

		String scoreString = (String)jsonObject.get("score");
		if (scoreString == null || scoreString.length() == 0) this.Score = 0;
		else this.Score = Float.parseFloat(scoreString);
	}

}

redpajama_set_name: RedPajamaGithub


text:
package com.cognifide.qa.bb.aem.core.component.dialog;

import static org.apache.commons.lang3.StringUtils.containsIgnoreCase;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import com.cognifide.qa.bb.aem.core.component.dialog.dialogfields.DialogField;
import com.cognifide.qa.bb.aem.core.component.dialog.dialogfields.Fields;
import com.cognifide.qa.bb.utils.AopUtil;
import com.cognifide.qa.bb.utils.PageObjectInjector;
import com.google.inject.Inject;

/**
 * Default AEM 6.4 Bobcat implementation of the {@link DialogFieldRetriever}
 */
public class DialogFieldRetrieverImpl implements DialogFieldRetriever {

  private static final By FIELD_LOCATOR = By.cssSelector(".coral-Form-fieldwrapper");

  private static final By LABEL_SELECTOR = By
      .cssSelector("label.coral-Form-fieldlabel, label.coral-Form-field");

  private static final By CHECKBOX_LABEL_SELECTOR = By
      .cssSelector("label.coral3-Checkbox-description");
  private static final By IMAGE_LOCATOR = By.cssSelector(".coral-Form-field.cq-FileUpload");
  private static final By CHECKBOX_LOCATOR = By.cssSelector(".coral-Form-field.coral3-Checkbox");
  private static final By RADIO_GROUP_LOCATOR =
      By.cssSelector(".coral-Form-field.coral-RadioGroup");

  @Inject
  private Map<String, DialogField> fieldTypeRegistry;

  @Inject
  private PageObjectInjector pageObjectInjector;

  /**
   * Finds the dialog field of given type within a WebElement based on the provided label. If label
   * is not present, returns the first field from the tab.
   * <p>
   * {@inheritDoc}
   */
  @Override
  public DialogField getDialogField(WebElement parentElement, String label, String type) {
    List<WebElement> fields = getFields(parentElement, type);

    if (fields.isEmpty()) {
      throw new IllegalStateException(String.format(
          "There are no fields in the tab matching the following: type=%s, label='%s', parent element=%s",
          type, label, parentElement));
    }

    WebElement scope = StringUtils.isEmpty(label) ? fields.get(0) : fields.stream() //
        .filter(field -> containsIgnoreCase(getFieldLabel(field, type), label)) //
        .findFirst() //
        .orElseThrow(() -> new IllegalStateException("Dialog field not found"));

    return getFieldObject(scope, type);
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public DialogField getDialogField(WebElement parentElement, String type) {
    WebElement scope = parentElement.findElement(By.tagName("input"));
    return getFieldObject(scope, type);
  }

  private List<WebElement> getFields(WebElement parentElement, String type) {
    List<WebElement> toReturn;
    switch (type) {
      case Fields.IMAGE:
        toReturn = parentElement.findElements(IMAGE_LOCATOR);
        break;
      case Fields.CHECKBOX:
        toReturn = parentElement.findElements(CHECKBOX_LOCATOR);
        break;
      case Fields.RADIO_GROUP_MULTI:
        toReturn = parentElement.findElements(RADIO_GROUP_LOCATOR);
        break;
      default:
        toReturn = parentElement.findElements(FIELD_LOCATOR);
        break;
    }

    return toReturn;
  }

  /**
   * Returns the label of given field. Label may not be present in the field, thus a workaround
   * using list is introduced here.
   *
   * @param field WebElement corresponding to the given field
   * @return label of the field or {@code StringUtils.Empty} when there is none
   */
  private String getFieldLabel(WebElement field, String type) {
    List<WebElement> labelField =
        type.equals(Fields.CHECKBOX) ? field.findElements(CHECKBOX_LABEL_SELECTOR)
            : field.findElements(LABEL_SELECTOR);
    return labelField.isEmpty() ? StringUtils.EMPTY : labelField.get(0).getText();
  }

  private DialogField getFieldObject(WebElement scope, String type) {
    DialogField dialogField = fieldTypeRegistry.get(type);
    return (DialogField) pageObjectInjector
        .inject(AopUtil.getBaseClassForAopObject(dialogField.getClass()), scope);
  }
}


text:
module ShopHelper

  def link_add_to_cart(item)
   link_to_function("", "addToCart(\"#{item}\")", class: 'button foundicon-cart')
  end

  def link_to_clear_cart()
    link_to_function('',"clearCart()", {:class => 'button foundicon-trash', :title => (I18n.t "clear_cart")})
  end

  def link_remove_from_cart(item)
    link_to_function("", "removeFromCart(\"#{item}\")", class: 'button foundicon-minus remove-item')
  end

  def link_remove_all_from_cart(item)
      link_to_function("", "removeFromCart(\"#{item}\", true)", class: 'button foundicon-trash remove-item')
  end

end


text:
import {createElementWithAttributes} from '#core/dom';
import {getValueForExpr} from '#core/types/object';

import {Services} from '#service';
const ALLOWED_AD_PROVIDER = 'gpt';

/**
 * @param {!JsonObject} media
 * @param {!AmpElement} apesterElement
 */
export function handleCompanionBottomAd(media, apesterElement) {
  const bottomAdOptions = getValueForExpr(
    /**@type {!JsonObject}*/ (media),
    'campaignData.bottomAdOptions'
  );
  if (!bottomAdOptions) {
    return;
  }
  const enabledBottomAd = getValueForExpr(
    /**@type {!JsonObject}*/ (bottomAdOptions),
    'enabled'
  );
  if (
    enabledBottomAd &&
    bottomAdOptions['videoPlayer'] === ALLOWED_AD_PROVIDER
  ) {
    const slot = bottomAdOptions['tag'];
    const bannerSizes = [[300, 50]];
    constructCompanionBottomAd(slot, bannerSizes, apesterElement);
  }
}

/**
 * @param {string} slot
 * @param {Array} bannerSizes
 * @param {!AmpElement} apesterElement
 * @return {!Element}
 */
function constructCompanionBottomAd(slot, bannerSizes, apesterElement) {
  const width = bannerSizes[0][0];
  const height = bannerSizes[0][1];
  const refreshInterval = 30;
  const ampAd = createElementWithAttributes(
    /** @type {!Document} */ (apesterElement.ownerDocument),
    'amp-ad',
    {
      'width': `${width}`,
      'height': `${height}`,
      'type': 'doubleclick',
      'layout': 'fixed',
      'data-slot': `${slot}`,
      'data-multi-size-validation': 'false',
      'data-enable-refresh': `${refreshInterval}`,
    }
  );
  ampAd.classList.add('i-amphtml-amp-apester-bottom-ad');
  apesterElement.appendChild(ampAd);
  Services.mutatorForDoc(apesterElement).requestChangeSize(ampAd, height);
  return ampAd;
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.

/**
 * This package contains the implementation classes for MicrosoftSupport.
 * Microsoft Azure Support Resource Provider.
 */
package com.microsoft.azure.management.support.v2020_04_01.implementation;


text:
/*
 * cgeShadowHighlightAdjust.h
 *
 *  Created on: 2013-12-26
 *      Author: Wang Yang
 */

#ifndef _CGESHADOWHIGHLIGHT_H_
#define _CGESHADOWHIGHLIGHT_H_

#include "cgeGLFunctions.h"
#include "CGEImageFilter.h"
#include "cgeImageHandler.h"

namespace CGE
{
	class CGEShadowHighlightFilter : public CGEImageFilterInterface
	{
	public:
		CGEShadowHighlightFilter(){}
		~CGEShadowHighlightFilter(){}

		void setShadow(float value); // range [-200, 100]
		void setHighlight(float value); // range [-100, 200]

		bool init();

	protected:
		static CGEConstString paramShadowName;
		static CGEConstString paramHighlightName;

	private:
	};

	class CGEShadowHighlightFastFilter : public CGEFastAdjustRGBFilter
	{
	public:
		CGEShadowHighlightFastFilter() : m_shadow(0.0f), m_highlight(0.0f) {}
		~CGEShadowHighlightFastFilter() {}

		void setShadowAndHighlight(float shadow, float highlight); //the same to above.

		bool init();

		float getShadow() { return m_shadow; }
		float getHighlight() { return m_highlight; }

	private:
		float m_shadow, m_highlight;
	};

}

#endif


text:
import Node from '../Node.js';
import CompileError from '../../utils/CompileError.js';
import rewritePattern from 'regexpu-core';

export default class Literal extends Node {
	initialise () {
		if ( typeof this.value === 'string' ) {
			this.program.indentExclusionElements.push( this );
		}
	}

	transpile ( code, transforms ) {
		if ( transforms.numericLiteral ) {
			const leading = this.raw.slice( 0, 2 );
			if ( leading === '0b' || leading === '0o' ) {
				code.overwrite( this.start, this.end, String( this.value ), true );
			}
		}

		if ( this.regex ) {
			const { pattern, flags } = this.regex;

			if ( transforms.stickyRegExp && /y/.test( flags ) ) throw new CompileError( this, 'Regular expression sticky flag is not supported' );
			if ( transforms.unicodeRegExp && /u/.test( flags ) ) {
				code.overwrite( this.start, this.end, `/${rewritePattern( pattern, flags )}/${flags.replace( 'u', '' )}` );
			}
		}
	}
}


text:
package com.oneops.transistor.service;

import com.oneops.transistor.service.peristenceless.BomData;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Transactional
public interface BomEnvManager {
	public void takeEnvSnapshot(long envId);
	public void cleanEnvBom(long envId);
	public long discardEnvBom(long envId);
	public long discardEnvManifest(long envId, String userId);

	List<CostData> getEnvCostData(long envId);
	Map<String, List<CostData>> getEnvEstimatedCostData(long envId);
  Map<String,List<CostData>> getEnvEstimatedCostData(long envId, BomData data);

  Map<String, List<CapacityData>> getEnvCapacity(long envId, BomData bomData);

}


text:
using HslCommunication.BasicFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CommonLibrary
{
    /// <summary>
    /// 系统的关于类
    /// </summary>
    public partial class FormAbout : Form
    {
        #region Constructor

        /// <summary>
        /// 实例化一个关于系统的窗口对象
        /// </summary>
        /// <param name="softName">应用程序的名称</param>
        /// <param name="sv">系统的版本</param>
        /// <param name="yearStart">应用起始年份</param>
        /// <param name="belongName">本系统的版权归属人</param>
        public FormAbout(string softName, SystemVersion sv, int yearStart, string belongName)
        {
            InitializeComponent();
            SoftName = softName;
            SV = sv;
            YearStart = yearStart;
            BelongName = belongName;
            Icon = UserSystem.GetFormWindowIcon();
        }

        /// <summary>
        /// 实例化一个关于系统的窗口对象
        /// </summary>
        /// <param name="sv">系统的版本</param>
        /// <param name="yearStart">版权起始年份</param>
        /// <param name="belongName">本系统的版权归属人</param>
        public FormAbout(SystemVersion sv, int yearStart, string belongName)
        {
            InitializeComponent();
            SoftName = Application.ProductName;
            SV = sv;
            YearStart = yearStart;
            BelongName = belongName;
        }

        #endregion

        #region Quick Close

        private void FormAbout_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                Close();
            }
        }

        #endregion

        #region Window Load

        private void FormAbout_Load(object sender, EventArgs e)
        {
            Text = "关于系统";
            label5.Text = "框架版本:" + SoftBasic.FrameworkVersion.ToString();

            label1.Text = SoftName;
            label2.Text = "V" + SV.ToString();
            if (DateTime.Now.Year > YearStart)
            {
                label3.Text = $"(C) {YearStart}-{DateTime.Now.Year} {BelongName} 保留所有权利";
            }
            else
            {
                label3.Text = $"(C) {YearStart} {BelongName} 保留所有权利";
            }
        }

        #endregion

        #region Private Members

        private string SoftName = string.Empty;
        private SystemVersion SV = null;
        private int YearStart = 2017;
        private string BelongName = "Richard.Hu";

        #endregion

    }
}


text:
import time

from selenium.webdriver.support.wait import WebDriverWait
from werkzeug.local import LocalProxy as _Proxy

from contesto import config

class JSONSerializable:
    def to_json(self):
        res = dict()
        attrs = [name for name in vars(self) if not name.startswith('_')]
        for attr in attrs:
            res[attr] = getattr(self, attr)
        return res

class Enum(object):
    def __init__(self, *sequential, **named):
        enums = dict(zip(sequential, range(len(sequential))), **named)
        self.enums = enums

    def __getattr__(self, item):
        return self.enums[item]

    def __iter__(self):
        return iter(self.enums.values())

class LocalProxy(_Proxy):
    @property
    def __class__(self):
        try:
            return type(self._get_current_object())
        except RuntimeError:
            return type(self)

class waiter(WebDriverWait):
    def __init__(self, driver, timeout=None, ignored_exceptions=None, *args, **kwargs):
        from contesto.exceptions import WebDriverException

        if timeout is None:
            timeout = float(config.timeout["normal"])

        if ignored_exceptions is None:
            ignored_exceptions = WebDriverException

        super(waiter, self).__init__(
            driver,
            timeout=timeout,
            ignored_exceptions=ignored_exceptions,
            *args, **kwargs)

    def until(self, method, message=''):
        from contesto.exceptions import TimeoutException

        end_time = time.time() + self._timeout
        while True:
            try:
                value = method(self._driver)
                if value:
                    return value
            except self._ignored_exceptions:
                pass
            time.sleep(self._poll)
            if time.time() > end_time:
                break

        raise TimeoutException(message)


text:
package com.intellij.ide.ui;

import sun.swing.SwingUtilities2;
import java.awt.*;

public enum LCDRenderingScope {
  IDE,
  EXCLUDING_EDITOR,
  OFF;

  public static LCDRenderingScope getWithLongestName() {
    return IDE;
  }

  private static final SwingUtilities2.AATextInfo aaEnabled =
    new SwingUtilities2.AATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_ON, 140);

  private static final SwingUtilities2.AATextInfo lcdEnabled =
    new SwingUtilities2.AATextInfo(RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB, 140);

  private static final SwingUtilities2.AATextInfo aaDisabled = null;

  public static Object getAAHintForSwingComponent() {
    UISettings uiSettings = UISettings.getInstance();
    if (uiSettings.ANTIALIASING_IN_IDE) {
      if (uiSettings.LCD_RENDERING_SCOPE == OFF) {
        return aaEnabled;
      }
      return lcdEnabled;
    }
    return aaDisabled;
  }

  public static Object getKeyForCurrentScope(boolean inEditor) {
    Object renderingHint = RenderingHints.VALUE_TEXT_ANTIALIAS_OFF;

    UISettings uiSettings = UISettings.getInstance();

    if (uiSettings != null && uiSettings.ANTIALIASING_IN_IDE) {
      switch (uiSettings.LCD_RENDERING_SCOPE) {
        case IDE:
          renderingHint = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB;
          break;
        case EXCLUDING_EDITOR:
          if (!inEditor) {
            renderingHint = RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB;
            break;
          }
        case OFF:
          renderingHint = RenderingHints.VALUE_TEXT_ANTIALIAS_ON;
          break;
      }
    }
    return renderingHint;
  }

  @Override
  public String toString() {
    String description ;
    switch (this) {
      case IDE:
        description = "LCD Rendering in IDE and Editor";
        break;
      case EXCLUDING_EDITOR:
        description = "LCD Rendering in IDE";
        break;
      case OFF:
        description = "Without LCD rendering";
        break;
      default:
        description = "LCD Rendering in IDE";
    }
    return description;
  }

  public static boolean shouldRenderEditor(LCDRenderingScope scope) {
    if (!UISettings.getInstance().ANTIALIASING_IN_IDE) return false;
    switch (scope) {
      case IDE:
        return true;
      default:
        return false;
    }
  }
}


text:
<!DOCTYPE HTML>

  <title>Test for Bug 560351</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>

Mozilla Bug 560351


text:
namespace policy {

DlpFilesEventStorage::DlpFilesEventStorage(base::TimeDelta cooldown_timeout,
                                           size_t entries_num_limit)
    : cooldown_delta_(cooldown_timeout),
      task_runner_(base::SequencedTaskRunner::GetCurrentDefault()),
      entries_num_limit_(entries_num_limit) {}
DlpFilesEventStorage::~DlpFilesEventStorage() = default;

DlpFilesEventStorage::EventEntry::EventEntry(base::TimeTicks timestamp)
    : timestamp(timestamp) {}
DlpFilesEventStorage::EventEntry::~EventEntry() = default;

bool DlpFilesEventStorage::StoreEventAndCheckIfItShouldBeReported(
    ino64_t inode,
    const DlpFilesController::DlpFileDestination& dst) {
  if (entries_num_ == entries_num_limit_) {
    // If we end up here we probably have already spammed the server with a lot
    // of events, better to stop for a while.
    return false;
  }

  const base::TimeTicks now = base::TimeTicks::Now();

  const auto inode_it = events_.find(inode);
  if (inode_it == events_.end()) {  // Check for new (inode, dst) pair
    InsertNewInodeAndDestinationPair(inode, dst, now);
    return true;
  }

  auto dst_it = inode_it->second.find(dst);
  if (dst_it == inode_it->second.end()) {  // Check for new dst for this inode
    AddDestinationToInode(inode_it, inode, dst, now);
    // Skip reporting if we don't know the destination (i.e., it is
    // kUnknownComponent) and at least an entry for `inode` is stored in
    // `events_`.
    return (dst.component.has_value() &&
            dst.component.value() !=
                DlpRulesManager::Component::kUnknownComponent) ||
           dst.url_or_path.has_value();
  }

  // Found existing (inode, dst) pair, update it
  UpdateInodeAndDestinationPair(dst_it, now);

  // Report only if enough time has passed.
  return now - dst_it->second.timestamp > cooldown_delta_;
}

base::TimeDelta DlpFilesEventStorage::GetDeduplicationCooldownForTesting()
    const {
  return cooldown_delta_;
}

std::size_t DlpFilesEventStorage::GetSizeForTesting() const {
  return entries_num_;
}

void DlpFilesEventStorage::SetTaskRunnerForTesting(
    scoped_refptr<base::SingleThreadTaskRunner> task_runner) {
  task_runner_ = task_runner;
}

void DlpFilesEventStorage::SimulateElapsedTimeForTesting(base::TimeDelta time) {
  std::vector<std::pair<ino64_t, const DlpFilesController::DlpFileDestination&>>
      expired_entries;
  for (auto& [inode, destinations] : events_) {
    for (auto& [dst, event_value] : destinations) {
      event_value.eviction_timer.Stop();
      if (time >= cooldown_delta_) {
        expired_entries.emplace_back(inode, dst);
      } else {
        const base::TimeDelta remaining = cooldown_delta_ - time;
        event_value.eviction_timer.Start(
            FROM_HERE, remaining,
            base::BindOnce(&DlpFilesEventStorage::OnEvictionTimerUp,
                           base::Unretained(this), inode, dst));
      }
    }
  }
  for (const auto& [inode, dst] : expired_entries) {
    OnEvictionTimerUp(inode, dst);
  }
}

void DlpFilesEventStorage::AddDestinationToInode(
    EventsMap::iterator inode_it,
    ino64_t inode,
    const DlpFilesController::DlpFileDestination& dst,
    const base::TimeTicks timestamp) {
  const auto [it, _] = inode_it->second.emplace(dst, timestamp);
  StartEvictionTimer(inode, dst, it->second);
  entries_num_++;
  DlpCountHistogram(dlp::kActiveFileEventsCount, entries_num_,
                    entries_num_limit_);
}

void DlpFilesEventStorage::InsertNewInodeAndDestinationPair(
    ino64_t inode,
    const DlpFilesController::DlpFileDestination& dst,
    const base::TimeTicks timestamp) {
  const auto [inode_it, _] = events_.emplace(
      inode, std::map<DlpFilesController::DlpFileDestination, EventEntry>());
  const auto [dst_it, __] = inode_it->second.emplace(dst, timestamp);
  StartEvictionTimer(inode, dst, dst_it->second);
  entries_num_++;
  DlpCountHistogram(dlp::kActiveFileEventsCount, entries_num_,
                    entries_num_limit_);
}

void DlpFilesEventStorage::UpdateInodeAndDestinationPair(
    DestinationsMap::iterator dst_it,
    const base::TimeTicks timestamp) {
  dst_it->second.timestamp = timestamp;
  DCHECK(dst_it->second.eviction_timer.IsRunning());
  dst_it->second.eviction_timer.Reset();
  DlpCountHistogram(dlp::kActiveFileEventsCount, entries_num_,
                    entries_num_limit_);
}

void DlpFilesEventStorage::StartEvictionTimer(
    ino64_t inode,
    const DlpFilesController::DlpFileDestination& dst,
    EventEntry& event_value) {
  event_value.eviction_timer.SetTaskRunner(task_runner_);
  event_value.eviction_timer.Start(
      FROM_HERE, cooldown_delta_,
      base::BindOnce(&DlpFilesEventStorage::OnEvictionTimerUp,
                     base::Unretained(this), inode, dst));
}

void DlpFilesEventStorage::OnEvictionTimerUp(
    ino64_t inode,
    DlpFilesController::DlpFileDestination dst) {
  auto event_it = events_.find(inode);
  DCHECK(event_it != events_.end());
  DCHECK(event_it->second.count(dst));
  event_it->second.erase(std::move(dst));
  if (event_it->second.empty()) {
    events_.erase(event_it);
  }
  --entries_num_;
}

}  // namespace policy


text:
package jd.core.parser;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;

import jd.core.JavaDecompilerConstants;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Simple class file parser, which reads only a header part of a class and extracts class version info and class name.
 *
 * @author Josef Cacek
 */
public final class SimpleClassParser {

    private static final Logger LOGGER = LoggerFactory.getLogger(SimpleClassParser.class);

    private static final byte CONSTTYPE_UTF8 = 1;
    private static final byte CONSTTYPE_INTEGER = 3;
    private static final byte CONSTTYPE_FLOAT = 4;
    private static final byte CONSTTYPE_LONG = 5;
    private static final byte CONSTTYPE_DOUBLE = 6;
    private static final byte CONSTTYPE_CLASS = 7;
    private static final byte CONSTTYPE_FIELDREF = 9;
    private static final byte CONSTTYPE_STRING = 8;
    private static final byte CONSTTYPE_METHODREF = 10;
    private static final byte CONSTTYPE_INTERFACEMETHODREF = 11;
    private static final byte CONSTTYPE_NAMEANDTYPE = 12;

    private final int major, minor;
    private final String className;

    /**
     * Constructor which parses basic class information from the given stream. It stops reading right after className index is
     * found.
     *
     * @param is Input stream
     */
    public SimpleClassParser(final InputStream is) throws IOException, ClassFormatException {
        LOGGER.trace("Parsing class from an InputStream");
        final DataInputStream dataInputStream;

        if (is instanceof DataInputStream) {
            dataInputStream = (DataInputStream) is;
        } else {
            dataInputStream = new DataInputStream(new BufferedInputStream(is));
        }

        if (dataInputStream.readInt() != JavaDecompilerConstants.MAGIC_NR_CLASS_FILE) {
            throw new ClassFormatException("Magic number doesn't match a class file.");
        }
        minor = dataInputStream.readUnsignedShort();
        major = dataInputStream.readUnsignedShort();
        LOGGER.trace("Class version: {}.{}", major, minor);

        final int constantPoolSize = dataInputStream.readUnsignedShort();
        final Object[] constantPool = new Object[constantPoolSize];
        // constantPool[0] is unused by the compiler and may be used freely by the implementation.
        for (int i = 1; i < constantPoolSize; i++) {
            final byte tag = dataInputStream.readByte(); // Read tag byte
            switch (tag) {
                case CONSTTYPE_NAMEANDTYPE:
                case CONSTTYPE_FIELDREF:
                case CONSTTYPE_METHODREF:
                case CONSTTYPE_INTERFACEMETHODREF:
                    // two shorts
                    dataInputStream.readUnsignedShort();
                case CONSTTYPE_STRING:
                    // one short
                    dataInputStream.readUnsignedShort();
                    break;
                case CONSTTYPE_INTEGER:
                    dataInputStream.readInt();
                    break;
                case CONSTTYPE_FLOAT:
                    dataInputStream.readFloat();
                    break;
                case CONSTTYPE_CLASS:
                    // we need ref
                    constantPool[i] = dataInputStream.readUnsignedShort();
                    break;
                case CONSTTYPE_LONG:
                    dataInputStream.readLong();
                    i++;
                    break;
                case CONSTTYPE_DOUBLE:
                    dataInputStream.readDouble();
                    i++;
                    break;
                case CONSTTYPE_UTF8:
                    constantPool[i] = dataInputStream.readUTF();
                    break;
                default:
                    throw new ClassFormatException("Invalid byte tag in constant pool: " + tag);
            }
        }

        // final int accessFlags =
        dataInputStream.readUnsignedShort();
        final int classIdx = dataInputStream.readUnsignedShort();
        LOGGER.trace("Parsed class index in constant pool: {}", classIdx);
        if (classIdx < 1 || classIdx >= constantPoolSize || !(constantPool[classIdx] instanceof Integer)) {
            throw new ClassFormatException("Wrong class type index.");
        }
        final int classNameIdx = (Integer) constantPool[classIdx];
        LOGGER.trace("Parsed class name index in constant pool: {}", classNameIdx);
        if (classNameIdx < 1 || classNameIdx >= constantPoolSize || !(constantPool[classNameIdx] instanceof String)) {
            throw new ClassFormatException("Wrong class name index.");
        }
        className = (String) constantPool[classNameIdx];
        LOGGER.trace("Parsed class name: {}", className);
        // final int superClassNameIdx = dataInputStream.readUnsignedShort();
    }

    /**
     * Returns the class major version.
     *
     * @return major
     */
    public int getMajor() {
        return major;
    }

    /**
     * Returns the class minor version.
     *
     * @return minor
     */
    public int getMinor() {
        return minor;
    }

    /**
     * Returns class name
     *
     * @return
     */
    public String getClassName() {
        return className;
    }

    /**
     * Returns class version in a human friendly way e.g. "49.0 (Java 1.5)"
     *
     * @return
     */
    public String getVersionString() {
        return major + "." + minor + " (Java 1." + (major - 44) + ")";
    }

}


text:
package org.motechproject.mobile.omi.ws;

import org.motechproject.mobile.omi.manager.OMIManager;
import org.motechproject.mobile.omi.service.OMIService;

import java.util.Date;
import javax.jws.WebParam;
import javax.jws.WebMethod;
import javax.jws.WebService;
import org.apache.log4j.Logger;
import org.motechproject.ws.*;
import org.motechproject.ws.mobile.MessageService;

/**
 * A web service implementation of the MessageService interface.
 *
 * @author Kofi A. Asamoah (yoofi@dreamoval.com)
 * Date Created 30-07-09
 */
@WebService(targetNamespace = "http://server.ws.motechproject.org/")
public class MessageServiceImpl implements MessageService {

    private OMIManager omiManager;
    private static Logger logger = Logger.getLogger(MessageServiceImpl.class);

    @WebMethod
    public void sendPatientMessages(@WebParam(name="messages") PatientMessage[] messages) {
        logger.debug("Called MessageService.sendPatientMessages with number of messages: " +
            (messages != null ? messages.length : "null"));

        logger.info("Processing request...");
        if( messages != null) {
            OMIService omiService = omiManager.createOMIService();

            for( PatientMessage message:messages) {
                omiService.savePatientMessageRequest(message.getMessageId(), message.getPersonalInfo(),
                        message.getPatientNumber(), message.getPatientNumberType(), message.getLangCode(),
                        message.getMediaType(), message.getNotificationType(), message.getStartDate(),
                        message.getEndDate(), message.getRecipientId());
            }
        }
    }

    @WebMethod
    public MessageStatus sendPatientMessage(@WebParam(name = "messageId") String messageId,
    										@WebParam(name = "personalInfo") NameValuePair[] personalInfo,
    										@WebParam(name = "patientNumber") String patientNumber,
    										@WebParam(name = "patientNumberType") ContactNumberType patientNumberType,
    										@WebParam(name = "langCode") String langCode,
    										@WebParam(name = "mediaType") MediaType messageType,
    										@WebParam(name = "notificationType") Long notificationType,
    										@WebParam(name = "startDate") Date startDate,
    										@WebParam(name = "endDate") Date endDate,
    										@WebParam(name = "recipientId") String recipientId) {
        logger.debug("Called MessageService.sendPatientMessage with parameters:\n\rmessageId - " + messageId +
        			 "\n\rclinic - " + patientNumber +
        			 "\n\rpatientNumbrType - " + patientNumberType +
        			 "\n\rmessageType - " + messageType +
        			 "\n\rstartDate - " + startDate +
        			 "\n\rendDate - " + endDate +
        			 "\n\rrecipientId - " + (recipientId != null ? recipientId : "null"));
        logger.info("Processing request...");
        return omiManager.createOMIService().savePatientMessageRequest(messageId, personalInfo, patientNumber, patientNumberType, langCode, messageType, notificationType, startDate, endDate, recipientId);
    }

    @WebMethod
    public MessageStatus sendCHPSMessage(@WebParam(name = "messageId") String messageId,
                                         @WebParam(name = "personalInfo") NameValuePair[] personalInfo,
                                         @WebParam(name = "workerNumber") String workerNumber,
                                         @WebParam(name = "patientList") Patient[] patientList,
                                         @WebParam(name = "langCode") String langCode,
                                         @WebParam(name = "mediaType") MediaType messageType,
                                         @WebParam(name = "notificationType") Long notificationType,
                                         @WebParam(name = "startDate") Date startDate,
                                         @WebParam(name = "endDate") Date endDate) {
        logger.debug("Called MessageService.sendCHPSMessage with parameters:\n\rmessageId - " + messageId + "\n\rworkerNumber - " + workerNumber + "\n\rstartDate - " + startDate + "\n\rendDate - " + endDate);
        logger.info("Processing request...");
        return this.omiManager.createOMIService().saveCHPSMessageRequest(messageId, personalInfo, workerNumber, patientList, langCode, messageType, notificationType, startDate, endDate);
    }

    @WebMethod
    public MessageStatus sendDefaulterMessage(@WebParam(name = "messageId") String messageId,
                                              @WebParam(name = "workerNumber") String workerNumber,
                                              @WebParam(name = "cares") Care[] cares,
                                              @WebParam(name = "groupingStrategy") CareMessageGroupingStrategy groupingStrategy,
                                              @WebParam(name = "messageType") MediaType mediaType,
                                              @WebParam(name = "startDate") Date startDate,
                                              @WebParam(name = "endDate") Date endDate) {
        logger.info("Processing request...");
        return this.omiManager.createOMIService().sendDefaulterMessage(messageId, workerNumber, cares, groupingStrategy,
                                                                       mediaType, startDate, endDate);
    }

    @WebMethod
    public MessageStatus sendDeliveriesMessage(@WebParam(name = "messageId") String messageId,
                                               @WebParam(name = "workerNumber") String workerNumber,
                                               @WebParam(name = "patients") Patient[] patients,
                                               @WebParam(name = "deliveryStatus") String deliveryStatus,
                                               @WebParam(name = "mediaType") MediaType mediaType,
                                               @WebParam(name = "startDate") Date startDate,
                                               @WebParam(name = "endDate") Date endDate) {
        logger.info("Processing request...");
        return this.omiManager.createOMIService().sendDeliveriesMessage(messageId, workerNumber, patients, deliveryStatus, mediaType, startDate, endDate);
    }

    @WebMethod
    public MessageStatus sendUpcomingCaresMessage(@WebParam(name = "messageId") String messageId,
                                                  @WebParam(name = "workerNumber") String workerNumber,
                                                  @WebParam(name = "patient") Patient patient,
                                                  @WebParam(name = "mediaType") MediaType mediaType,
                                                  @WebParam(name = "startDate") Date startDate,
                                                  @WebParam(name = "endDate") Date endDate) {
        logger.info("Processing request...");
        return this.omiManager.createOMIService().sendUpcomingCaresMessage(messageId, workerNumber, patient, mediaType, startDate, endDate);
    }

    @WebMethod
    public MessageStatus sendBulkCaresMessage(@WebParam(name = "messageId") String messageId,
                                                  @WebParam(name = "workerNumber") String workerNumber,
                                                  @WebParam(name = "patient") Care[] cares,
                                                  @WebParam(name = "groupingStrategy") CareMessageGroupingStrategy groupingStrategy,
                                                  @WebParam(name = "mediaType") MediaType mediaType,
                                                  @WebParam(name = "startDate") Date startDate,
                                                  @WebParam(name = "endDate") Date endDate) {
        logger.info("Processing request...");
        return this.omiManager.createOMIService().sendBulkCaresMessage(messageId, workerNumber, cares, groupingStrategy,
                                                                       mediaType, startDate, endDate);
    }

    @WebMethod
    public MessageStatus sendMessage(@WebParam(name = "content") String content,
                                     @WebParam(name = "recipient") String recipient) {
        logger.info("Processing request...");
        return this.omiManager.createOMIService().sendMessage(content, recipient);
    }

    /**
     * @return the omiManager
     */
    @WebMethod(exclude = true)
    public OMIManager getOmiManager() {
        return omiManager;
    }

    /**
     * @param omiManager the omiManager to set
     */
    @WebMethod(exclude = true)
    public void setOmiManager(OMIManager omiManager) {
        logger.debug("Setting MessageServiceImpl.omiManager:");
        logger.debug(omiManager);
        this.omiManager = omiManager;
    }
}


text:
<?php
/**
 * Piwik - free/libre analytics platform
 *
 * @link http://piwik.org
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 */
namespace Piwik\Plugins\MobileMessaging\ReportRenderer;

use Piwik\Common;
use Piwik\Plugins\MultiSites\API;
use Piwik\ReportRenderer;
use Piwik\Site;
use Piwik\View;

/**
 *
 */
class Sms extends ReportRenderer
{
    const FLOAT_REGEXP = '/[-+]?[0-9]*[\.,]?[0-9]+/';
    const SMS_CONTENT_TYPE = 'text/plain';
    const SMS_FILE_EXTENSION = 'sms';

    private $rendering = "";

    public function setLocale($locale)
    {
        // nothing to do
    }

    public function sendToDisk($filename)
    {
        return ReportRenderer::writeFile($filename, self::SMS_FILE_EXTENSION, $this->rendering);
    }

    public function sendToBrowserDownload($filename)
    {
        ReportRenderer::sendToBrowser($filename, self::SMS_FILE_EXTENSION, self::SMS_CONTENT_TYPE, $this->rendering);
    }

    public function sendToBrowserInline($filename)
    {
        ReportRenderer::inlineToBrowser(self::SMS_CONTENT_TYPE, $this->rendering);
    }

    public function getRenderedReport()
    {
        return $this->rendering;
    }

    public function renderFrontPage($reportTitle, $prettyDate, $description, $reportMetadata, $segment)
    {
        // nothing to do
    }

    public function renderReport($processedReport)
    {
        $isGoalPluginEnabled = Common::isGoalPluginEnabled();
        $prettyDate = $processedReport['prettyDate'];
        $reportData = $processedReport['reportData'];

        $evolutionMetrics = array();
        $multiSitesAPIMetrics = API::getApiMetrics($enhanced = true);
        foreach ($multiSitesAPIMetrics as $metricSettings) {
            $evolutionMetrics[] = $metricSettings[API::METRIC_EVOLUTION_COL_NAME_KEY];
        }

        $floatRegex = self::FLOAT_REGEXP;
        // no decimal for all metrics to shorten SMS content (keeps the monetary sign for revenue metrics)
        $reportData->filter(
            'ColumnCallbackReplace',
            array(
                 array_merge(array_keys($multiSitesAPIMetrics), $evolutionMetrics),
                 function ($value) use ($floatRegex) {
                     return preg_replace_callback(
                         $floatRegex,
                         function ($matches) {
                             return round($matches[0]);
                         },
                         $value
                     );
                 }
            )
        );

        // evolution metrics formatting :
        //  - remove monetary, percentage and white spaces to shorten SMS content
        //    (this is also needed to be able to test $value != 0 and see if there is an evolution at all in SMSReport.twig)
        //  - adds a plus sign
        $reportData->filter(
            'ColumnCallbackReplace',
            array(
                 $evolutionMetrics,
                 function ($value) use ($floatRegex) {
                     $matched = preg_match($floatRegex, $value, $matches);
                     $formatted = $matched ? sprintf("%+d", $matches[0]) : $value;
                     return \Piwik\NumberFormatter::getInstance()->formatPercentEvolution($formatted);
                 }
            )
        );

        $dataRows = $reportData->getRows();
        $reportMetadata = $processedReport['reportMetadata'];
        $reportRowsMetadata = $reportMetadata->getRows();

        $siteHasECommerce = array();
        foreach ($reportRowsMetadata as $rowMetadata) {
            $idSite = $rowMetadata->getColumn('idsite');
            $siteHasECommerce[$idSite] = Site::isEcommerceEnabledFor($idSite);
        }

        $view = new View('@MobileMessaging/SMSReport');
        $view->assign("isGoalPluginEnabled", $isGoalPluginEnabled);
        $view->assign("reportRows", $dataRows);
        $view->assign("reportRowsMetadata", $reportRowsMetadata);
        $view->assign("prettyDate", $prettyDate);
        $view->assign("siteHasECommerce", $siteHasECommerce);
        $view->assign("displaySiteName", $processedReport['metadata']['action'] == 'getAll');

        // segment
        $segment = $processedReport['segment'];
        $displaySegment = ($segment != null);
        $view->assign("displaySegment", $displaySegment);
        if ($displaySegment) {
            $view->assign("segmentName", $segment['name']);
        }

        $this->rendering .= $view->render();
    }

    /**
     * Get report attachments, ex. graph images
     *
     * @param $report
     * @param $processedReports
     * @param $prettyDate
     * @return array
     */
    public function getAttachments($report, $processedReports, $prettyDate)
    {
        return array();
    }
}


text:
<?php

/*
 * This file is part of the Symfony framework.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Symfony\Bundle\AsseticBundle\Controller;

use Assetic\Asset\AssetCache;
use Assetic\Asset\AssetInterface;
use Assetic\Cache\CacheInterface;
use Assetic\Factory\LazyAssetManager;
use Assetic\ValueSupplierInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Profiler\Profiler;

/**
 * Serves assets.
 *
 * @author Kris Wallsmith <kris@symfony.com>
 */
class AsseticController
{
    protected $request;
    protected $am;
    protected $cache;
    protected $enableProfiler;
    protected $profiler;

    public function __construct(LazyAssetManager $am, CacheInterface $cache, $enableProfiler = false, Profiler $profiler = null)
    {
        $this->am = $am;
        $this->cache = $cache;
        $this->enableProfiler = (boolean) $enableProfiler;
        $this->profiler = $profiler;
    }

    public function setValueSupplier(ValueSupplierInterface $supplier)
    {
        trigger_error(sprintf('%s is deprecated. The values of asset variables are retrieved from the request after the route matching.', __METHOD__), E_USER_DEPRECATED);
    }

    public function render(Request $request, $name, $pos = null)
    {
        if (!$this->enableProfiler && null !== $this->profiler) {
            $this->profiler->disable();
        }

        if (!$this->am->has($name)) {
            throw new NotFoundHttpException(sprintf('The "%s" asset could not be found.', $name));
        }

        $asset = $this->am->get($name);
        if (null !== $pos && !$asset = $this->findAssetLeaf($asset, $pos)) {
            throw new NotFoundHttpException(sprintf('The "%s" asset does not include a leaf at position %d.', $name, $pos));
        }

        $response = $this->createResponse();
        $response->setExpires(new \DateTime());

        $this->configureAssetValues($asset, $request);

        // last-modified
        if (null !== $lastModified = $this->am->getLastModified($asset)) {
            $date = new \DateTime();
            $date->setTimestamp($lastModified);
            $response->setLastModified($date);
        }

        // etag
        if ($this->am->hasFormula($name)) {
            $formula = $this->am->getFormula($name);
            $formula['last_modified'] = $lastModified;
            $response->setETag(md5(serialize($formula)));
        }

        if ($response->isNotModified($request)) {
            return $response;
        }

        $etagCacheKeyFilter = new AssetCacheKeyFilter($response->getEtag());

        $response->setContent($this->cachifyAsset($asset)->dump($etagCacheKeyFilter));

        return $response;
    }

    protected function createResponse()
    {
        return new Response();
    }

    protected function cachifyAsset(AssetInterface $asset)
    {
        return new AssetCache($asset, $this->cache);
    }

    protected function configureAssetValues(AssetInterface $asset, Request $request)
    {
        if ($vars = $asset->getVars()) {
            $asset->setValues(array_intersect_key($request->attributes->all(), array_flip($vars)));
        }

        return $this;
    }

    private function findAssetLeaf(\Traversable $asset, $pos)
    {
        $i = 0;
        foreach ($asset as $leaf) {
            if ($pos == $i++) {
                return $leaf;
            }
        }
    }
}