text:
MAXCHILDREN=10
MAX_KMEANS=5
import math, random, sys
import time
import array

from .rect import Rect, union_all, NullRect

class RTree(object):
    def __init__(self):
        self.count = 0
        self.stats = {
            "overflow_f" : 0,
            "avg_overflow_t_f" : 0.0,
            "longest_overflow" : 0.0,
            "longest_kmeans" : 0.0,
            "sum_kmeans_iter_f" : 0,
            "count_kmeans_iter_f" : 0,
            "avg_kmeans_iter_f" : 0.0
            }

        # This round: not using objects directly -- they
        #   take up too much memory, and efficiency goes down the toilet
        #   (obviously) if things start to page.
        #  Less obviously: using object graph directly leads to really long GC
        #   pause times, too.
        # Instead, it uses pools of arrays:
        self.count = 0
        self.leaf_count = 0
        self.rect_pool = array.array('d')
        self.node_pool = array.array('L')
        self.leaf_pool = [] # leaf objects.

        self.cursor = _NodeCursor.create(self, NullRect)

    def _ensure_pool(self, idx):
        if len(self.rect_pool) < (4*idx):
            self.rect_pool.extend([0,0,0,0] * idx)
            self.node_pool.extend([0,0] * idx)

    def insert(self,o, orect):
        self.cursor.insert(o,orect)
        assert(self.cursor.index == 0)

    def query_rect(self, r):
        for x in self.cursor.query_rect(r): yield x
    def query_point(self, p):
        for x in self.cursor.query_point(p): yield x
    def walk(self,pred):
        return self.cursor.walk(pred)

class _NodeCursor(object):
    @classmethod
    def create(cls, rooto, rect):
        idx = rooto.count
        rooto.count += 1

        rooto._ensure_pool(idx + 1)
        #rooto.node_pool.extend([0,0])
        #rooto.rect_pool.extend([0,0,0,0])

        retv = _NodeCursor(rooto,idx,rect,0,0)

        retv._save_back()
        return retv

    @classmethod
    def create_with_children(cls, children, rooto):
        rect = union_all([c for c in children])
        nr = Rect(rect.x,rect.y,rect.xx,rect.yy)
        assert(not rect.swapped_x)
        nc = _NodeCursor.create(rooto,rect)
        nc._set_children(children)
        assert(not nc.is_leaf())
        return nc

    @classmethod
    def create_leaf(cls, rooto, leaf_obj, leaf_rect):
        rect = Rect(leaf_rect.x,leaf_rect.y,leaf_rect.xx,leaf_rect.yy)
        rect.swapped_x = True # Mark as leaf by setting the xswap flag.
        res = _NodeCursor.create(rooto, rect)
        idx = res.index
        res.first_child = rooto.leaf_count
        rooto.leaf_count += 1
        res.next_sibling = 0
        rooto.leaf_pool.append(leaf_obj)
        res._save_back()
        res._become(idx)
        assert(res.is_leaf())
        return res

    __slots__ = ("root","npool","rpool","index","rect","next_sibling","first_child")

    def __init__(self, rooto, index, rect, first_child, next_sibling):
        self.root = rooto
        self.rpool = rooto.rect_pool
        self.npool = rooto.node_pool

        self.index = index
        self.rect = rect
        self.next_sibling = next_sibling
        self.first_child = first_child

    def walk(self, predicate):
        if (predicate(self, self.leaf_obj())):
            yield self
            if not self.is_leaf():
                for c in self.children():
                    for cr in c.walk(predicate):
                        yield cr

    def query_rect(self, r):
        """ Return things that intersect with 'r'. """
        def p(o,x): return r.does_intersect(o.rect)
        for rr in self.walk(p):
            yield rr

    def query_point(self,point):
        """ Query by a point """
        def p(o,x): return o.rect.does_containpoint(point)

        for rr in self.walk(p):
            yield rr

    def lift(self):
        return _NodeCursor(self.root,
                           self.index,
                           self.rect,
                           self.first_child,
                           self.next_sibling)

    def _become(self, index):
        recti = index * 4
        nodei = index * 2
        rp = self.rpool
        x = rp[recti]
        y = rp[recti+1]
        xx = rp[recti+2]
        yy = rp[recti+3]

        if (x == 0.0 and y == 0.0 and xx == 0.0 and yy == 0.0):
            self.rect = NullRect
        else:
            self.rect = Rect(x,y,xx,yy)

        self.next_sibling = self.npool[nodei]
        self.first_child = self.npool[nodei + 1]
        self.index = index

    def is_leaf(self):
        return self.rect.swapped_x

    def has_children(self):
        return not self.is_leaf() and 0 != self.first_child

    def holds_leaves(self):
        if 0 == self.first_child: return True
        else:
            return self.has_children() and self.get_first_child().is_leaf()

    def get_first_child(self):
        fc = self.first_child
        c = _NodeCursor(self.root,0,NullRect,0,0)
        c._become(self.first_child)
        return c

    def leaf_obj(self):
        if self.is_leaf(): return self.root.leaf_pool[self.first_child]
        else: return None

    def _save_back(self):
        rp = self.rpool
        recti = self.index * 4
        nodei = self.index * 2

        if self.rect is not NullRect:
            self.rect.write_raw_coords(rp, recti)
        else:
            rp[recti] = 0
            rp[recti+1] = 0
            rp[recti+2] = 0
            rp[recti+3] = 0

        self.npool[nodei] = self.next_sibling
        self.npool[nodei + 1] = self.first_child

    def nchildren(self):
        i = self.index
        c = 0
        for x in self.children(): c += 1
        return c

    def insert(self, leafo, leafrect):
        index = self.index

        # tail recursion, made into loop:
        while True:
            if self.holds_leaves():
                self.rect = self.rect.union(leafrect)
                self._insert_child(_NodeCursor.create_leaf(self.root,leafo,leafrect))

                self._balance()

                # done: become the original again
                self._become(index)
                return
            else:
                # Not holding leaves, move down a level in the tree:

                # Micro-optimization:
                #  inlining union() calls -- logic is:
                # ignored,child = min([ ((c.rect.union(leafrect)).area() - c.rect.area(),c.index) for c in self.children() ])
                child = None
                minarea = -1.0
                for c in self.children():
                    x,y,xx,yy = c.rect.coords()
                    lx,ly,lxx,lyy = leafrect.coords()
                    nx = x if x < lx else lx
                    nxx = xx if xx > lxx else lxx
                    ny = y if y < ly else ly
                    nyy = yy if yy > lyy else lyy
                    a = (nxx - nx) * (nyy - ny)
                    if minarea < 0 or a < minarea:
                        minarea = a
                        child = c.index
                # End micro-optimization

                self.rect = self.rect.union(leafrect)
                self._save_back()
                self._become(child) # recurse.

    def _balance(self):
        if (self.nchildren() <= MAXCHILDREN):
            return

        t = time.clock()

        cur_score = -10

        s_children = [ c.lift() for c in self.children() ]

        memo = {}

        clusterings = [ k_means_cluster(self.root,k,s_children) for k in range(2,MAX_KMEANS) ]
        score,bestcluster = max( [ (silhouette_coeff(c,memo),c) for c in clusterings ])

        nodes = [ _NodeCursor.create_with_children(c,self.root) for c in bestcluster if len(c) > 0]

        self._set_children(nodes)

        dur = (time.clock() - t)
        c = float(self.root.stats["overflow_f"])
        oa = self.root.stats["avg_overflow_t_f"]
        self.root.stats["avg_overflow_t_f"] = (dur / (c + 1.0)) + (c * oa / (c + 1.0))
        self.root.stats["overflow_f"] += 1
        self.root.stats["longest_overflow"] = max(self.root.stats["longest_overflow"], dur)

    def _set_children(self, cs):
        self.first_child = 0

        if 0 == len(cs):
            return

        pred = None
        for c in cs:
            if pred is not None:
                pred.next_sibling = c.index
                pred._save_back()
            if 0 == self.first_child:
                self.first_child = c.index
            pred = c
        pred.next_sibling = 0
        pred._save_back()
        self._save_back()

    def _insert_child(self, c):
        c.next_sibling = self.first_child
        self.first_child = c.index
        c._save_back()
        self._save_back()

    def children(self):
        if (0 == self.first_child): return

        idx = self.index
        fc = self.first_child
        ns = self.next_sibling
        r = self.rect

        self._become(self.first_child)
        while True:
            yield self
            if 0 == self.next_sibling:
                break
            else: self._become(self.next_sibling)

        # Go back to becoming the same node we were.
        #self._become(idx)
        self.index = idx
        self.first_child = fc
        self.next_sibling = ns
        self.rect = r

def avg_diagonals(node, onodes, memo_tab):
    nidx = node.index
    sv = 0.0
    diag = 0.0
    for onode in onodes:
        k1 = (nidx,onode.index)
        k2 = (onode.index,nidx)
        if k1 in memo_tab:
            diag = memo_tab[k1]
        elif k2 in memo_tab:
            diag = memo_tab[k2]
        else:
            diag = node.rect.union(onode.rect).diagonal()
            memo_tab[k1] = diag

        sv += diag

    return sv / len(onodes)

def silhouette_w(node, cluster, next_closest_cluster, memo):
    ndist = avg_diagonals(node, cluster, memo)
    sdist = avg_diagonals(node, next_closest_cluster, memo)
    return (sdist - ndist) / max(sdist,ndist)

def silhouette_coeff(clustering, memo_tab):
    # special case for a clustering of 1.0
    if (len(clustering) == 1): return 1.0

    coeffs = []
    for cluster in clustering:
        others = [ c for c in clustering if c is not cluster ]
        others_cntr = [ center_of_gravity(c) for c in others ]
        ws = [ silhouette_w(node,cluster,others[closest(others_cntr,node)], memo_tab) for node in cluster ]
        cluster_coeff = sum(ws) / len(ws)
        coeffs.append(cluster_coeff)
    return sum(coeffs) / len(coeffs)

def center_of_gravity(nodes):
    totarea = 0.0
    xs,ys = 0,0
    for n in nodes:
        if n.rect is not NullRect:
            x,y,w,h = n.rect.extent()
            a = w*h
            xs = xs + (a * (x + (0.5 * w)))
            ys = ys + (a * (y + (0.5 * h)))
            totarea = totarea + a
    return (xs / totarea), (ys / totarea)

def closest(centroids, node):
    x,y = center_of_gravity([node])
    dist = -1
    ridx = -1

    for (i,(xx,yy)) in enumerate(centroids):
        dsq = ((xx-x) ** 2) + ((yy-y) ** 2)
        if -1 == dist or dsq < dist:
            dist = dsq
            ridx = i
    return ridx

def k_means_cluster(root, k, nodes):
    t = time.clock()
    if len(nodes) <= k: return [ [n] for n in nodes ]

    ns = list(nodes)
    root.stats["count_kmeans_iter_f"] += 1

    # Initialize: take n random nodes.
    random.shuffle(ns)

    cluster_starts = ns[:k]
    cluster_centers = [ center_of_gravity([n]) for n in ns[:k] ]

    # Loop until stable:
    while True:
        root.stats["sum_kmeans_iter_f"] += 1
        clusters = [ [] for c in cluster_centers ]

        for n in ns:
            idx = closest(cluster_centers, n)
            clusters[idx].append(n)

        #FIXME HACK TODO: is it okay for there to be empty clusters?
        clusters = [ c for c in clusters if len(c) > 0 ]

        for c in clusters:
            if (len(c) == 0):
                print("Errorrr....")
                print("Nodes: %d, centers: %s" % (len(ns),
                                                              repr(cluster_centers)))

            assert(len(c) > 0)

        rest = ns
        first = False

        new_cluster_centers = [ center_of_gravity(c) for c in clusters ]
        if new_cluster_centers == cluster_centers :
            root.stats["avg_kmeans_iter_f"] = float(root.stats["sum_kmeans_iter_f"] / root.stats["count_kmeans_iter_f"])
            root.stats["longest_kmeans"] = max(root.stats["longest_kmeans"], (time.clock() - t))
            return clusters
        else: cluster_centers = new_cluster_centers


text:
package org.scalaide.core.ui

import org.eclipse.jdt.core.IJavaProject
import org.eclipse.jdt.core.JavaCore
import org.eclipse.jdt.core.formatter.{ DefaultCodeFormatterConstants => Dcfc }
import org.eclipse.jdt.internal.core.JavaProject
import org.eclipse.jdt.internal.ui.JavaPlugin
import org.eclipse.jdt.ui.PreferenceConstants
import org.eclipse.jdt.ui.text.IJavaPartitions
import org.eclipse.jface.text.Document
import org.eclipse.jface.text.DocumentCommand
import org.eclipse.jface.text.TextUtilities
import org.eclipse.jface.text.source.ISourceViewer
import org.eclipse.ui.internal.editors.text.EditorsPlugin
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.junit.internal.runners.JUnit4ClassRunner
import org.junit.runner.RunWith
import org.scalaide.core.lexical.ScalaCodePartitioner
import org.scalaide.core.testsetup.SdtTestConstants
import org.scalaide.ui.internal.editor.PreferenceProvider
import org.scalaide.ui.internal.editor.ScalaAutoIndentStrategy
import org.scalaide.ui.internal.editor.ScalaIndenter

@RunWith(classOf[JUnit4ClassRunner])
@Ignore(SdtTestConstants.TestRequiresGuiSupport)
class TestScalaIndenter {

  /**
   * Needed because the only constructor for DocumentCommand is protected
   */
  class InstantiableDocumentCommands extends DocumentCommand {

  }

  class MockPreferenceProvider extends PreferenceProvider {
    def updateCache : Unit = {
      // Nothing to do - we rely on someone setting up this cache
    }
  }

  /**
   * This class overrides several functions in ScalaAutoIndentStrategy to reduce
   * the overhead of things that need to be initialised for testing
   */
  class TestScalaAutoIndentStrategy(
      partitioning : String,
      project : IJavaProject,
      viewer : ISourceViewer,
      preferenceProvider : MockPreferenceProvider
    )  extends ScalaAutoIndentStrategy(partitioning, project, viewer, preferenceProvider) {
    override def computeSmartMode : Boolean = {
      return true
    }
  }

  val CARET = "_|_"

  @Before
  def initialiseClass(): Unit = {
    // Initialisation fluff
    if (JavaPlugin.getDefault() == null) {
      new JavaPlugin()
    }
    if (EditorsPlugin.getDefault() == null) {
      new EditorsPlugin()
    }
    if (JavaCore.getJavaCore() == null) {
      new JavaCore()
    }
  }

  def runTest(textSoFar : String, insert : String, expectedResultWithCaret : String): Unit = {
    def nrOfCarets(str: String): Int = s"\\Q$CARET\\E".r.findAllIn(str).size

    val document = new Document(textSoFar.replace(CARET, ""))
    val partitioner = ScalaCodePartitioner.documentPartitioner()
    partitioner.connect(document)
    document.setDocumentPartitioner(IJavaPartitions.JAVA_PARTITIONING, partitioner)

    // Create the command with all needed information
    val command = new InstantiableDocumentCommands()
    command.text = insert
    command.length = 0
    command.offset = textSoFar.indexOf(CARET)
    command.doit = true
    command.shiftsCaret = true
    command.caretOffset = -1

    // Preferences for indentation
    val preferenceProvider = new MockPreferenceProvider

    // For succinctness we alias DefaultCodeFormatterConstants to Dcfc
    import org.eclipse.jdt.core.formatter.{ DefaultCodeFormatterConstants => Dcfc }
    preferenceProvider.put(PreferenceConstants.EDITOR_CLOSE_BRACES, "true")
    preferenceProvider.put(PreferenceConstants.EDITOR_SMART_TAB, "true")
    preferenceProvider.put(Dcfc.FORMATTER_INDENT_STATEMENTS_COMPARE_TO_BLOCK, "true")
    preferenceProvider.put(Dcfc.FORMATTER_BRACE_POSITION_FOR_BLOCK, Dcfc.END_OF_LINE)
    preferenceProvider.put(Dcfc.FORMATTER_INDENT_BODY_DECLARATIONS_COMPARE_TO_TYPE_HEADER, "true")
    preferenceProvider.put(Dcfc.FORMATTER_BRACE_POSITION_FOR_TYPE_DECLARATION, Dcfc.END_OF_LINE)
    preferenceProvider.put(Dcfc.FORMATTER_TAB_CHAR, "space")
    preferenceProvider.put(ScalaIndenter.TAB_SIZE, "2")
    preferenceProvider.put(ScalaIndenter.INDENT_SIZE, "2")
    preferenceProvider.put(ScalaIndenter.INDENT_WITH_TABS, "false")

    val project = new JavaProject()

    val indentStrategy = new TestScalaAutoIndentStrategy(IJavaPartitions.JAVA_PARTITIONING, project, null, preferenceProvider)
    indentStrategy.customizeDocumentCommand(document, command)

    // Allow for not moving the offset
    val newOffset =
      if (command.caretOffset == -1) {
        command.offset + command.text.length
      } else {
        command.caretOffset
      }

    val editedText = textSoFar.substring(0, command.offset) + command.text + textSoFar.substring(command.offset + command.length)
    val result = editedText.replaceAllLiterally(CARET, "")

    // Replace system specific new lines in the result with a generic '\n'
    val lineDelimiter = TextUtilities.getDefaultLineDelimiter(document)
    val resultWithCleanNewLines = result.replaceAll(lineDelimiter, "\n")

    val expectedResult = expectedResultWithCaret.replace(CARET, "")
    assertEquals(expectedResult.replace(CARET, ""), resultWithCleanNewLines)

    val delta = if (nrOfCarets(expectedResultWithCaret) > 1) CARET.length else 0
    val expectedOffset = expectedResultWithCaret.lastIndexOf(CARET) - delta
    assertEquals(expectedOffset, newOffset)
  }

  /**
   * Test:
   *   class x {<->
   *
   * Becomes
   *   class x {
   *     <->
   *   }
   */
  @Test
  def testClassIndent(): Unit = {

    val textSoFar =
      "class x {" + CARET

    val expectedResult =
      textSoFar + "\n" +
      "  " + CARET + "\n" +
      "}"

    runTest(textSoFar, "\n", expectedResult)
  }

  /**
   * Test:
   *   trait x {<->
   *
   * Becomes
   *   trait x {
   *     <->
   *   }
   */
  @Test
  def testTraitIndent(): Unit = {

    val textSoFar =
      "trait x {" + CARET

    val expectedResult =
      textSoFar + "\n" +
      "  " + CARET + "\n" +
      "}"

    runTest(textSoFar, "\n", expectedResult)
  }

  /**
   * Test:
   *   class x {
   *     def y = {<->
   *   }
   *
   * Becomes
   *   class x {
   *     def y = {
   *       <->
   *     }
   *   }
   */
  @Test
  def testDefIndent(): Unit = {
    val textSoFar =
      "class x {\n" +
      "  def y = {" + CARET + "\n" +
      "}"

    val expectedResult =
      "class x {\n" +
      "  def y = {" + CARET + "\n" +
      "    " + CARET + "\n" +
      "  }\n" +
      "}"

    runTest(textSoFar, "\n", expectedResult)
  }

  /**
   * Test:
   *   class x {
   *     def y : Int = {<->
   *   }
   *
   * Becomes
   *   class x {
   *     def y : Int = {
   *       <->
   *     }
   *   }
   */
  @Test
  def defWithType(): Unit = {
    val textSoFar =
      "class x {\n" +
      "  def y : Int = {" + CARET + "\n" +
      "}"

    val expectedResult =
      "class x {\n" +
      "  def y : Int = {" + CARET + "\n" +
      "    " + CARET + "\n" +
      "  }\n" +
      "}"

    runTest(textSoFar, "\n", expectedResult)
  }

  /**
   * Test:
   *   class x {
   *     val xs = List[x]<->
   *   }
   *
   * Becomes
   *   class x {
   *     val xs = List[x]
   *     <->
   *   }
   */
  @Test
  def testGenericsIndent(): Unit = {
    val textSoFar =
      "class x {\n" +
      "  val xs = List[x]" + CARET + "\n" +
      "}"

    val expectedResult =
      "class x {\n" +
      "  val xs = List[x]" + CARET + "\n" +
      "  " + CARET + "\n" +
      "}"

    runTest(textSoFar, "\n", expectedResult)
  }

  /**
   * Test:
   *   class x {
   *     val xs = List[<->
   *   }
   *
   * Becomes
   *   class x {
   *     val xs = List[
   *         <->
   *   }
   */
  @Test
  def genericsIndentOverMultipleLines(): Unit = {
    val textSoFar =
      "class x {\n" +
      "  val xs = List[" + CARET + "\n" +
      "}"
    val expectedResult =
      "class x {\n" +
      "  val xs = List[" + CARET + "\n" +
      "    " + CARET + "\n" +
      "}"

    runTest(textSoFar, "\n", expectedResult)
  }

  /**
   * Test:
   *   class x {
   *     y()<->
   *   }
   *
   * Becomes
   *   class x {
   *     y()
   *     <->
   *   }
   */
  @Test
  def afterFunctionCall(): Unit = {
    val textSoFar =
      "class x {\n" +
      "  y()" + CARET + "\n" +
      "}"

    val expectedResult =
      "class x {\n" +
      "  y()" + CARET + "\n" +
      "  " + CARET + "\n" +
      "}"

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDefNoRhs(): Unit = {
    val textSoFar = s"""|
                        |class x {
                        |  val x = $CARET
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {
                             |  val x = $CARET
                             |    $CARET
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDef(): Unit = {
    val textSoFar = s"""|
                        |class x {
                        |  val x = "abc"$CARET
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {
                             |  val x = "abc"$CARET
                             |  $CARET
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDefEmptySpace(): Unit = {
    val textSoFar = s"""|
                        |class x {
                        |  val x = "abc"
                        |  $CARET
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {
                             |  val x = "abc"
                             |  $CARET
                             |  $CARET
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDefCharLit(): Unit = {
    val textSoFar = s"""|
                        |class x {
                        |  val x = 'a'$CARET
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {
                             |  val x = 'a'$CARET
                             |  $CARET
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDefCharLitEscaped(): Unit = {
    val textSoFar = raw"""|
                        |class x {
                        |  val x = '\n'$CARET
                        |}""".stripMargin

    val expectedResult = raw"""|
                             |class x {
                             |  val x = '\n'$CARET
                             |  $CARET
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDefCharLitEscapedBackSlash(): Unit = {
    val textSoFar = raw"""|
                        |class x {
                        |  val x = '\\'$CARET
                        |}""".stripMargin

    val expectedResult = raw"""|
                             |class x {
                             |  val x = '\\'$CARET
                             |  $CARET
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDefRawString(): Unit = {
    val textSoFar = s"""|
                        |class x {
                        |  val x = \"\"\"abcdef\"\"\"$CARET
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {
                             |  val x = \"\"\"abcdef\"\"\"$CARET
                             |  $CARET
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDefMiddleCaret(): Unit = {
    val textSoFar = s"""|
                        |class x {
                        |  val x = $CARET"abc"
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {
                             |  val x = $CARET
                             |    $CARET"abc"
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterValDefWithEscape(): Unit = {
    val textSoFar = s"""|
                        |class x {"
                        |  val x = "a\"bc"$CARET
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {"
                             |  val x = "a\"bc"$CARET
                             |  $CARET
                             |}""".stripMargin

    runTest(textSoFar, "\n", expectedResult)
  }

  @Test
  def afterIfElse(): Unit = {
    val textSoFar = s"""|
                        |class x {"
                        |  if (true)
                        |    1
                        |    els$CARET
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {"
                             |  if (true)
                             |    1
                             |  else$CARET
                             |}""".stripMargin
    runTest(textSoFar, "e", expectedResult)
  }

  @Test
  def afterIfElseNoChange(): Unit = {
    val textSoFar = s"""|
                        |class x {"
                        |  if (true)
                        |    1
                        |  els$CARET
                        |}""".stripMargin

    val expectedResult = s"""|
                             |class x {"
                             |  if (true)
                             |    1
                             |  else$CARET
                             |}""".stripMargin
    runTest(textSoFar, "e", expectedResult)
  }
}

redpajama_set_name: RedPajamaGithub


text:
'use strict'

module.exports = function ignore(path, context) {
  // ignore node_modules by default
  var ignoreStrings = context.settings['import/ignore']
    ? [].concat(context.settings['import/ignore'])
    : ['node_modules']

  if (ignoreStrings.length === 0) return false

  for (var i = 0; i < ignoreStrings.length; i++) {
    var regex = new RegExp(ignoreStrings[i])
    if (regex.test(path)) return true
  }

  return false
}


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/note_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".NoteListActivity"
    tools:ignore="MergeRootFrame" />


text:
from __future__ import absolute_import

from collections import defaultdict
from itertools import chain
import logging
import os

from pip._vendor import pkg_resources
from pip._vendor import requests

from pip.compat import expanduser
from pip.download import (is_file_url, is_dir_url, is_vcs_url, url_to_path,
                          unpack_url)
from pip.exceptions import (InstallationError, BestVersionAlreadyInstalled,
                            DistributionNotFound, PreviousBuildDirError,
                            HashError, HashErrors, HashUnpinned,
                            DirectoryUrlHashUnsupported, VcsHashUnsupported)
from pip.req.req_install import InstallRequirement
from pip.utils import (
    display_path, dist_in_usersite, ensure_dir, normalize_path)
from pip.utils.hashes import MissingHashes
from pip.utils.logging import indent_log
from pip.vcs import vcs

logger = logging.getLogger(__name__)

class Requirements(object):

    def __init__(self):
        self._keys = []
        self._dict = {}

    def keys(self):
        return self._keys

    def values(self):
        return [self._dict[key] for key in self._keys]

    def __contains__(self, item):
        return item in self._keys

    def __setitem__(self, key, value):
        if key not in self._keys:
            self._keys.append(key)
        self._dict[key] = value

    def __getitem__(self, key):
        return self._dict[key]

    def __repr__(self):
        values = ['%s: %s' % (repr(k), repr(self[k])) for k in self.keys()]
        return 'Requirements({%s})' % ', '.join(values)

class DistAbstraction(object):
    """Abstracts out the wheel vs non-wheel prepare_files logic.

    The requirements for anything installable are as follows:
     - we must be able to determine the requirement name
       (or we can't correctly handle the non-upgrade case).
     - we must be able to generate a list of run-time dependencies
       without installing any additional packages (or we would
       have to either burn time by doing temporary isolated installs
       or alternatively violate pips 'don't start installing unless
       all requirements are available' rule - neither of which are
       desirable).
     - for packages with setup requirements, we must also be able
       to determine their requirements without installing additional
       packages (for the same reason as run-time dependencies)
     - we must be able to create a Distribution object exposing the
       above metadata.
    """

    def __init__(self, req_to_install):
        self.req_to_install = req_to_install

    def dist(self, finder):
        """Return a setuptools Dist object."""
        raise NotImplementedError(self.dist)

    def prep_for_dist(self):
        """Ensure that we can get a Dist for this requirement."""
        raise NotImplementedError(self.dist)

def make_abstract_dist(req_to_install):
    """Factory to make an abstract dist object.

    Preconditions: Either an editable req with a source_dir, or satisfied_by or
    a wheel link, or a non-editable req with a source_dir.

    :return: A concrete DistAbstraction.
    """
    if req_to_install.editable:
        return IsSDist(req_to_install)
    elif req_to_install.link and req_to_install.link.is_wheel:
        return IsWheel(req_to_install)
    else:
        return IsSDist(req_to_install)

class IsWheel(DistAbstraction):

    def dist(self, finder):
        return list(pkg_resources.find_distributions(
            self.req_to_install.source_dir))[0]

    def prep_for_dist(self):
        # FIXME:https://github.com/pypa/pip/issues/1112
        pass

class IsSDist(DistAbstraction):

    def dist(self, finder):
        dist = self.req_to_install.get_dist()
        # FIXME: shouldn't be globally added:
        if dist.has_metadata('dependency_links.txt'):
            finder.add_dependency_links(
                dist.get_metadata_lines('dependency_links.txt')
            )
        return dist

    def prep_for_dist(self):
        self.req_to_install.run_egg_info()
        self.req_to_install.assert_source_matches_version()

class Installed(DistAbstraction):

    def dist(self, finder):
        return self.req_to_install.satisfied_by

    def prep_for_dist(self):
        pass

class RequirementSet(object):

    def __init__(self, build_dir, src_dir, download_dir, upgrade=False,
                 ignore_installed=False, as_egg=False, target_dir=None,
                 ignore_dependencies=False, force_reinstall=False,
                 use_user_site=False, session=None, pycompile=True,
                 isolated=False, wheel_download_dir=None,
                 wheel_cache=None, require_hashes=False):
        """Create a RequirementSet.

        :param wheel_download_dir: Where still-packed .whl files should be
            written to. If None they are written to the download_dir parameter.
            Separate to download_dir to permit only keeping wheel archives for
            pip wheel.
        :param download_dir: Where still packed archives should be written to.
            If None they are not saved, and are deleted immediately after
            unpacking.
        :param wheel_cache: The pip wheel cache, for passing to
            InstallRequirement.
        """
        if session is None:
            raise TypeError(
                "RequirementSet() missing 1 required keyword argument: "
                "'session'"
            )

        self.build_dir = build_dir
        self.src_dir = src_dir
        # XXX: download_dir and wheel_download_dir overlap semantically and may
        # be combined if we're willing to have non-wheel archives present in
        # the wheelhouse output by 'pip wheel'.
        self.download_dir = download_dir
        self.upgrade = upgrade
        self.ignore_installed = ignore_installed
        self.force_reinstall = force_reinstall
        self.requirements = Requirements()
        # Mapping of alias: real_name
        self.requirement_aliases = {}
        self.unnamed_requirements = []
        self.ignore_dependencies = ignore_dependencies
        self.successfully_downloaded = []
        self.successfully_installed = []
        self.reqs_to_cleanup = []
        self.as_egg = as_egg
        self.use_user_site = use_user_site
        self.target_dir = target_dir  # set from --target option
        self.session = session
        self.pycompile = pycompile
        self.isolated = isolated
        if wheel_download_dir:
            wheel_download_dir = normalize_path(wheel_download_dir)
        self.wheel_download_dir = wheel_download_dir
        self._wheel_cache = wheel_cache
        self.require_hashes = require_hashes
        # Maps from install_req -> dependencies_of_install_req
        self._dependencies = defaultdict(list)

    def __str__(self):
        reqs = [req for req in self.requirements.values()
                if not req.comes_from]
        reqs.sort(key=lambda req: req.name.lower())
        return ' '.join([str(req.req) for req in reqs])

    def __repr__(self):
        reqs = [req for req in self.requirements.values()]
        reqs.sort(key=lambda req: req.name.lower())
        reqs_str = ', '.join([str(req.req) for req in reqs])
        return ('<%s object; %d requirement(s): %s>'
                % (self.__class__.__name__, len(reqs), reqs_str))

    def add_requirement(self, install_req, parent_req_name=None):
        """Add install_req as a requirement to install.

        :param parent_req_name: The name of the requirement that needed this
            added. The name is used because when multiple unnamed requirements
            resolve to the same name, we could otherwise end up with dependency
            links that point outside the Requirements set. parent_req must
            already be added. Note that None implies that this is a user
            supplied requirement, vs an inferred one.
        :return: Additional requirements to scan. That is either [] if
            the requirement is not applicable, or [install_req] if the
            requirement is applicable and has just been added.
        """
        name = install_req.name
        if not install_req.match_markers():
            logger.warning("Ignoring %s: markers %r don't match your "
                           "environment", install_req.name,
                           install_req.markers)
            return []

        install_req.as_egg = self.as_egg
        install_req.use_user_site = self.use_user_site
        install_req.target_dir = self.target_dir
        install_req.pycompile = self.pycompile
        if not name:
            # url or path requirement w/o an egg fragment
            self.unnamed_requirements.append(install_req)
            return [install_req]
        else:
            try:
                existing_req = self.get_requirement(name)
            except KeyError:
                existing_req = None
            if (parent_req_name is None and existing_req and not
                    existing_req.constraint and
                    existing_req.extras == install_req.extras and not
                    existing_req.req.specs == install_req.req.specs):
                raise InstallationError(
                    'Double requirement given: %s (already in %s, name=%r)'
                    % (install_req, existing_req, name))
            if not existing_req:
                # Add requirement
                self.requirements[name] = install_req
                # FIXME: what about other normalizations?  E.g., _ vs. -?
                if name.lower() != name:
                    self.requirement_aliases[name.lower()] = name
                result = [install_req]
            else:
                # Assume there's no need to scan, and that we've already
                # encountered this for scanning.
                result = []
                if not install_req.constraint and existing_req.constraint:
                    if (install_req.link and not (existing_req.link and
                       install_req.link.path == existing_req.link.path)):
                        self.reqs_to_cleanup.append(install_req)
                        raise InstallationError(
                            "Could not satisfy constraints for '%s': "
                            "installation from path or url cannot be "
                            "constrained to a version" % name)
                    # If we're now installing a constraint, mark the existing
                    # object for real installation.
                    existing_req.constraint = False
                    existing_req.extras = tuple(
                        sorted(set(existing_req.extras).union(
                               set(install_req.extras))))
                    logger.debug("Setting %s extras to: %s",
                                 existing_req, existing_req.extras)
                    # And now we need to scan this.
                    result = [existing_req]
                # Canonicalise to the already-added object for the backref
                # check below.
                install_req = existing_req
            if parent_req_name:
                parent_req = self.get_requirement(parent_req_name)
                self._dependencies[parent_req].append(install_req)
            return result

    def has_requirement(self, project_name):
        name = project_name.lower()
        if (name in self.requirements and
           not self.requirements[name].constraint or
           name in self.requirement_aliases and
           not self.requirements[self.requirement_aliases[name]].constraint):
            return True
        return False

    @property
    def has_requirements(self):
        return list(req for req in self.requirements.values() if not
                    req.constraint) or self.unnamed_requirements

    @property
    def is_download(self):
        if self.download_dir:
            self.download_dir = expanduser(self.download_dir)
            if os.path.exists(self.download_dir):
                return True
            else:
                logger.critical('Could not find download directory')
                raise InstallationError(
                    "Could not find or access download directory '%s'"
                    % display_path(self.download_dir))
        return False

    def get_requirement(self, project_name):
        for name in project_name, project_name.lower():
            if name in self.requirements:
                return self.requirements[name]
            if name in self.requirement_aliases:
                return self.requirements[self.requirement_aliases[name]]
        raise KeyError("No project with the name %r" % project_name)

    def uninstall(self, auto_confirm=False):
        for req in self.requirements.values():
            if req.constraint:
                continue
            req.uninstall(auto_confirm=auto_confirm)
            req.commit_uninstall()

    def prepare_files(self, finder):
        """
        Prepare process. Create temp directories, download and/or unpack files.
        """
        # make the wheelhouse
        if self.wheel_download_dir:
            ensure_dir(self.wheel_download_dir)

        # If any top-level requirement has a hash specified, enter
        # hash-checking mode, which requires hashes from all.
        root_reqs = self.unnamed_requirements + self.requirements.values()
        require_hashes = (self.require_hashes or
                          any(req.has_hash_options for req in root_reqs))
        if require_hashes and self.as_egg:
            raise InstallationError(
                '--egg is not allowed with --require-hashes mode, since it '
                'delegates dependency resolution to setuptools and could thus '
                'result in installation of unhashed packages.')

        # Actually prepare the files, and collect any exceptions. Most hash
        # exceptions cannot be checked ahead of time, because
        # req.populate_link() needs to be called before we can make decisions
        # based on link type.
        discovered_reqs = []
        hash_errors = HashErrors()
        for req in chain(root_reqs, discovered_reqs):
            try:
                discovered_reqs.extend(self._prepare_file(
                    finder,
                    req,
                    require_hashes=require_hashes,
                    ignore_dependencies=self.ignore_dependencies))
            except HashError as exc:
                exc.req = req
                hash_errors.append(exc)

        if hash_errors:
            raise hash_errors

    def _check_skip_installed(self, req_to_install, finder):
        """Check if req_to_install should be skipped.

        This will check if the req is installed, and whether we should upgrade
        or reinstall it, taking into account all the relevant user options.

        After calling this req_to_install will only have satisfied_by set to
        None if the req_to_install is to be upgraded/reinstalled etc. Any
        other value will be a dist recording the current thing installed that
        satisfies the requirement.

        Note that for vcs urls and the like we can't assess skipping in this
        routine - we simply identify that we need to pull the thing down,
        then later on it is pulled down and introspected to assess upgrade/
        reinstalls etc.

        :return: A text reason for why it was skipped, or None.
        """
        # Check whether to upgrade/reinstall this req or not.
        req_to_install.check_if_exists()
        if req_to_install.satisfied_by:
            skip_reason = 'satisfied (use --upgrade to upgrade)'
            if self.upgrade:
                best_installed = False
                # For link based requirements we have to pull the
                # tree down and inspect to assess the version #, so
                # its handled way down.
                if not (self.force_reinstall or req_to_install.link):
                    try:
                        finder.find_requirement(req_to_install, self.upgrade)
                    except BestVersionAlreadyInstalled:
                        skip_reason = 'up-to-date'
                        best_installed = True
                    except DistributionNotFound:
                        # No distribution found, so we squash the
                        # error - it will be raised later when we
                        # re-try later to do the install.
                        # Why don't we just raise here?
                        pass

                if not best_installed:
                    # don't uninstall conflict if user install and
                    # conflict is not user install
                    if not (self.use_user_site and not
                            dist_in_usersite(req_to_install.satisfied_by)):
                        req_to_install.conflicts_with = \
                            req_to_install.satisfied_by
                    req_to_install.satisfied_by = None
            return skip_reason
        else:
            return None

    def _prepare_file(self,
                      finder,
                      req_to_install,
                      require_hashes=False,
                      ignore_dependencies=False):
        """Prepare a single requirements file.

        :return: A list of additional InstallRequirements to also install.
        """
        # Tell user what we are doing for this requirement:
        # obtain (editable), skipping, processing (local url), collecting
        # (remote url or package name)
        if req_to_install.constraint or req_to_install.prepared:
            return []

        req_to_install.prepared = True

        # ###################### #
        # # print log messages # #
        # ###################### #
        if req_to_install.editable:
            logger.info('Obtaining %s', req_to_install)
        else:
            # satisfied_by is only evaluated by calling _check_skip_installed,
            # so it must be None here.
            assert req_to_install.satisfied_by is None
            if not self.ignore_installed:
                skip_reason = self._check_skip_installed(
                    req_to_install, finder)

            if req_to_install.satisfied_by:
                assert skip_reason is not None, (
                    '_check_skip_installed returned None but '
                    'req_to_install.satisfied_by is set to %r'
                    % (req_to_install.satisfied_by,))
                logger.info(
                    'Requirement already %s: %s', skip_reason,
                    req_to_install)
            else:
                if (req_to_install.link and
                        req_to_install.link.scheme == 'file'):
                    path = url_to_path(req_to_install.link.url)
                    logger.info('Processing %s', display_path(path))
                else:
                    logger.info('Collecting %s', req_to_install)

        with indent_log():
            # ################################ #
            # # vcs update or unpack archive # #
            # ################################ #
            if req_to_install.editable:
                if require_hashes:
                    raise InstallationError(
                        'The editable requirement %s cannot be installed when '
                        'requiring hashes, because there is no single file to '
                        'hash.' % req_to_install)
                req_to_install.ensure_has_source_dir(self.src_dir)
                req_to_install.update_editable(not self.is_download)
                abstract_dist = make_abstract_dist(req_to_install)
                abstract_dist.prep_for_dist()
                if self.is_download:
                    req_to_install.archive(self.download_dir)
            elif req_to_install.satisfied_by:
                if require_hashes:
                    logger.debug(
                        'Since it is already installed, we are trusting this '
                        'package without checking its hash. To ensure a '
                        'completely repeatable environment, install into an '
                        'empty virtualenv.')
                abstract_dist = Installed(req_to_install)
            else:
                # @@ if filesystem packages are not marked
                # editable in a req, a non deterministic error
                # occurs when the script attempts to unpack the
                # build directory
                req_to_install.ensure_has_source_dir(self.build_dir)
                # If a checkout exists, it's unwise to keep going.  version
                # inconsistencies are logged later, but do not fail the
                # installation.
                # FIXME: this won't upgrade when there's an existing
                # package unpacked in `req_to_install.source_dir`
                if os.path.exists(
                        os.path.join(req_to_install.source_dir, 'setup.py')):
                    raise PreviousBuildDirError(
                        "pip can't proceed with requirements '%s' due to a"
                        " pre-existing build directory (%s). This is "
                        "likely due to a previous installation that failed"
                        ". pip is being responsible and not assuming it "
                        "can delete this. Please delete it and try again."
                        % (req_to_install, req_to_install.source_dir)
                    )
                req_to_install.populate_link(
                    finder, self.upgrade, require_hashes)
                # We can't hit this spot and have populate_link return None.
                # req_to_install.satisfied_by is None here (because we're
                # guarded) and upgrade has no impact except when satisfied_by
                # is not None.
                # Then inside find_requirement existing_applicable -> False
                # If no new versions are found, DistributionNotFound is raised,
                # otherwise a result is guaranteed.
                assert req_to_install.link
                link = req_to_install.link

                # Now that we have the real link, we can tell what kind of
                # requirements we have and raise some more informative errors
                # than otherwise. (For example, we can raise VcsHashUnsupported
                # for a VCS URL rather than HashMissing.)
                if require_hashes:
                    # We could check these first 2 conditions inside
                    # unpack_url and save repetition of conditions, but then
                    # we would report less-useful error messages for
                    # unhashable requirements, complaining that there's no
                    # hash provided.
                    if is_vcs_url(link):
                        raise VcsHashUnsupported()
                    elif is_file_url(link) and is_dir_url(link):
                        raise DirectoryUrlHashUnsupported()
                    if (not req_to_install.original_link and
                            not req_to_install.is_pinned):
                        # Unpinned packages are asking for trouble when a new
                        # version is uploaded. This isn't a security check, but
                        # it saves users a surprising hash mismatch in the
                        # future.
                        #
                        # file:/// URLs aren't pinnable, so don't complain
                        # about them not being pinned.
                        raise HashUnpinned()
                hashes = req_to_install.hashes(
                    trust_internet=not require_hashes)
                if require_hashes and not hashes:
                    # Known-good hashes are missing for this requirement, so
                    # shim it with a facade object that will provoke hash
                    # computation and then raise a HashMissing exception
                    # showing the user what the hash should be.
                    hashes = MissingHashes()

                try:
                    download_dir = self.download_dir
                    # We always delete unpacked sdists after pip ran.
                    autodelete_unpacked = True
                    if req_to_install.link.is_wheel \
                            and self.wheel_download_dir:
                        # when doing 'pip wheel` we download wheels to a
                        # dedicated dir.
                        download_dir = self.wheel_download_dir
                    if req_to_install.link.is_wheel:
                        if download_dir:
                            # When downloading, we only unpack wheels to get
                            # metadata.
                            autodelete_unpacked = True
                        else:
                            # When installing a wheel, we use the unpacked
                            # wheel.
                            autodelete_unpacked = False
                    unpack_url(
                        req_to_install.link, req_to_install.source_dir,
                        download_dir, autodelete_unpacked,
                        session=self.session, hashes=hashes)
                except requests.HTTPError as exc:
                    logger.critical(
                        'Could not install requirement %s because '
                        'of error %s',
                        req_to_install,
                        exc,
                    )
                    raise InstallationError(
                        'Could not install requirement %s because '
                        'of HTTP error %s for URL %s' %
                        (req_to_install, exc, req_to_install.link)
                    )
                abstract_dist = make_abstract_dist(req_to_install)
                abstract_dist.prep_for_dist()
                if self.is_download:
                    # Make a .zip of the source_dir we already created.
                    if req_to_install.link.scheme in vcs.all_schemes:
                        req_to_install.archive(self.download_dir)
                # req_to_install.req is only avail after unpack for URL
                # pkgs repeat check_if_exists to uninstall-on-upgrade
                # (#14)
                if not self.ignore_installed:
                    req_to_install.check_if_exists()
                if req_to_install.satisfied_by:
                    if self.upgrade or self.ignore_installed:
                        # don't uninstall conflict if user install and
                        # conflict is not user install
                        if not (self.use_user_site and not
                                dist_in_usersite(
                                    req_to_install.satisfied_by)):
                            req_to_install.conflicts_with = \
                                req_to_install.satisfied_by
                        req_to_install.satisfied_by = None
                    else:
                        logger.info(
                            'Requirement already satisfied (use '
                            '--upgrade to upgrade): %s',
                            req_to_install,
                        )

            # ###################### #
            # # parse dependencies # #
            # ###################### #
            dist = abstract_dist.dist(finder)
            more_reqs = []

            def add_req(subreq):
                sub_install_req = InstallRequirement(
                    str(subreq),
                    req_to_install,
                    isolated=self.isolated,
                    wheel_cache=self._wheel_cache,
                )
                more_reqs.extend(self.add_requirement(
                    sub_install_req, req_to_install.name))

            # We add req_to_install before its dependencies, so that we
            # can refer to it when adding dependencies.
            if not self.has_requirement(req_to_install.name):
                # 'unnamed' requirements will get added here
                self.add_requirement(req_to_install, None)

            if not ignore_dependencies:
                if (req_to_install.extras):
                    logger.debug(
                        "Installing extra requirements: %r",
                        ','.join(req_to_install.extras),
                    )
                missing_requested = sorted(
                    set(req_to_install.extras) - set(dist.extras)
                )
                for missing in missing_requested:
                    logger.warning(
                        '%s does not provide the extra \'%s\'',
                        dist, missing
                    )

                available_requested = sorted(
                    set(dist.extras) & set(req_to_install.extras)
                )
                for subreq in dist.requires(available_requested):
                    add_req(subreq)

            # cleanup tmp src
            self.reqs_to_cleanup.append(req_to_install)

            if not req_to_install.editable and not req_to_install.satisfied_by:
                # XXX: --no-install leads this to report 'Successfully
                # downloaded' for only non-editable reqs, even though we took
                # action on them.
                self.successfully_downloaded.append(req_to_install)

        return more_reqs

    def cleanup_files(self):
        """Clean up files, remove builds."""
        logger.debug('Cleaning up...')
        with indent_log():
            for req in self.reqs_to_cleanup:
                req.remove_temporary_source()

    def _to_install(self):
        """Create the installation order.

        The installation order is topological - requirements are installed
        before the requiring thing. We break cycles at an arbitrary point,
        and make no other guarantees.
        """
        # The current implementation, which we may change at any point
        # installs the user specified things in the order given, except when
        # dependencies must come earlier to achieve topological order.
        order = []
        ordered_reqs = set()

        def schedule(req):
            if req.satisfied_by or req in ordered_reqs:
                return
            if req.constraint:
                return
            ordered_reqs.add(req)
            for dep in self._dependencies[req]:
                schedule(dep)
            order.append(req)
        for install_req in self.requirements.values():
            schedule(install_req)
        return order

    def install(self, install_options, global_options=(), *args, **kwargs):
        """
        Install everything in this set (after having downloaded and unpacked
        the packages)
        """
        to_install = self._to_install()

        if to_install:
            logger.info(
                'Installing collected packages: %s',
                ', '.join([req.name for req in to_install]),
            )

        with indent_log():
            for requirement in to_install:
                if requirement.conflicts_with:
                    logger.info(
                        'Found existing installation: %s',
                        requirement.conflicts_with,
                    )
                    with indent_log():
                        requirement.uninstall(auto_confirm=True)
                try:
                    requirement.install(
                        install_options,
                        global_options,
                        *args,
                        **kwargs
                    )
                except:
                    # if install did not succeed, rollback previous uninstall
                    if (requirement.conflicts_with and not
                            requirement.install_succeeded):
                        requirement.rollback_uninstall()
                    raise
                else:
                    if (requirement.conflicts_with and
                            requirement.install_succeeded):
                        requirement.commit_uninstall()
                requirement.remove_temporary_source()

        self.successfully_installed = to_install


text:
import { combineReducers } from 'redux';
import incomeReducer from './income';
import expenseReducer from './expenses';
import viewStateReducer from './view-state';

export default combineReducers({
    incomes: incomeReducer,
    expenses: expenseReducer,
    viewState: viewStateReducer
});


text:
	%if ($sessionObj->param("userMessage1") ne "") {

		<%$sessionObj->param("userMessage1")%>

	%$sessionObj->param("userMessage1", "");
	% }
	% if (@$hostGroupArray == 0) {

						<fieldset>
							<legend align="top">Host Groups</legend>
							There are no host groups to select
						</fieldset>

	%} else {

			<form action="index.pl" method="post">
			<input type="hidden" name="displayMode" value="edit">
			<input type="hidden" name="contentType" value="hostAssets">
			<input type="hidden" name="reportNameID" value="<%$reportNameID%>">
			<input type="hidden" name="contentID" value="<%$contentID%>">

						<fieldset>
							<legend align="top">Host Group</legend>
							<select name="hostGroupID" size="1" onchange="submit();">
								%foreach my $hostGroupName (@$hostGroupArray) {
									<option value="<%$hostGroupName%>" <%$hostGroupName eq $hostGroupID ? 'selected' : ' '%>><%$hostGroupName%></option>
								%}
							</select>
						</fieldset>

			</form>

	<form action="index.pl" method="post">
	<input type="hidden" name="action" value="updateHostAssets">
	<input type="hidden" name="hostGroupID" value="<%$hostGroupID%>">
	<input type="hidden" name="reportNameID" value="<%$reportNameID%>">
	<input type="hidden" name="contentID" value="<%$contentID%>">

						<fieldset>
							<legend align="top">Hosts</legend>
								<select name="selectHosts" size="1">
								% foreach my $contentStruct (@$hostArray) {
									%my $value="$contentStruct->{'hostName'}";
									<option value="<%$value%>" <%searchArray($selectHosts, $value) ? 'selected' : ' '%>><%$value%></option>
								%}
							</select>
						</fieldset>

						<fieldset>
							<legend align="top">CPU</legend>

									<input type="checkbox" name="cpu" value="model" <%searchArray($cpu, 'model') ? 'checked' : ' '%>>
									CPU Model

									<input type="checkbox" name="cpu" value="speed" <%searchArray($cpu, 'speed') ? 'checked' : ' '%>>
									CPU Speed

									<input type="checkbox" name="cpu" value="number" <%searchArray($cpu, 'number') ? 'checked' : ' '%>>
									CPU Number

						</fieldset>

						<fieldset>
							<legend align="top">Memory</legend>

									<input type="checkbox" name="memory" value="total" <%searchArray($memory, 'total') ? 'checked' : ' '%>>
									Total Memory

						</fieldset>

						<fieldset>
							<legend align="top">Operating System</legend>

									<input type="checkbox" name="os" value="name" <%searchArray($os, 'name') ? 'checked' : ' '%>>
									OS Name

									<input type="checkbox" name="os" value="version" <%searchArray($os, 'version') ? 'checked' : ' '%>>
									OS Version

									<input type="checkbox" name="os" value="kernel" <%searchArray($os, 'kernel') ? 'checked' : ' '%>>
									Kernel Version

									<input type="checkbox" name="os" value="patchList" <%searchArray($os, 'patchList') ? 'checked' : ' '%>>
									Patch List

						</fieldset>

                  <input class="liteButton" type="submit" name="Update" value="UPDATE">

                  <input class="liteButton" type="button" name="clear" value="Go Back" onclick="location='index.pl?reportNameID=<%$reportNameID%>';">

	</form>
	%}


text:
package org.cronhub.managesystem.commons.validation;

import com.opensymphony.xwork2.ActionSupport;
import it.sauronsoftware.cron4j.SchedulingPattern;
import org.apache.struts2.ServletActionContext;
import org.cronhub.managesystem.commons.logger.AppLogger;

import java.io.IOException;
import java.io.PrintWriter;
public class ValidationAction extends ActionSupport {
	public String validateCronExp(){
		String value = ServletActionContext.getRequest().getParameter("cron_exp");
		boolean pass = SchedulingPattern.validate(value);
		PrintWriter out = null;
		try {
			out = ServletActionContext.getResponse().getWriter();
			if(pass){
				out.print("success");
			}else{
				out.print("fail");
			}
			out.flush();
		} catch (IOException e) {
			AppLogger.errorLogger.error("error in get PrintWriter to page",e);
		}finally{
			if(null!=out){
			out.close();
			}
		}
		return NONE;
	}
}


text:
		Between:
		<input id="from" date ng-model="query.from" ng-change="refresh()"></input>

		And:
		<input id="to" date ng-model="query.to" ng-change="refresh()"></input>

		Containing Text:
		<input id="text" ng-model="query.text" ng-change="refresh()"></input>

		Split by Task:
		<input id="splitByTask" type="checkbox" ng-model="query.splitByTask" ng-change="refresh()"></input>

		Split by Day:
		<input id="splitByDay" type="checkbox" ng-model="query.splitByDay" ng-change="refresh()"></input>

<canvas time-graph="entryGroups"  width="400" height="400" style="float:right;"></canvas>

			Date
			Task
			Time

			{{entryGroup.dayNumber | formatDayNumber}}
			{{entryGroup.description}}
			{{entryGroup.duration | formatDuration}}

			{{entryGroups | sumGroupDurations | formatDuration}}

<button ng-click="refresh()">Refresh</button>
<button ng-click="getCsv()" ng-disable="!entryGroups" download="timePerTask.csv">'Download' CSV</button>


text:
(function(){
    'use strict';

    var module = angular.module('std.password.edit', []);

    module.controller('stdPasswordEditController', ['$scope',
        function ($scope) {
            var self = this;
            self.maxLength = $scope.field.type.property.maxLength ? $scope.field.type.property.maxLength : 10;

            self.validate = function() {
                $scope.invalidMessage = '';

                if ($scope.data.password !== $scope.data.confirmPassword) {
                    $scope.invalidMessage = " 'Password' does not match.";
                    $scope.invalid = true;
                }
                if (!$scope.data.password) {
                    $scope.invalidMessage += " 'Password' is required.";
                    $scope.invalid = true;
                }
                if ($scope.data.password && !$scope.data.confirmPassword) {
                    $scope.invalidMessage += " 'Confirm Password' is required.";
                    $scope.invalid = true;
                }
                if ($scope.data.password && $scope.data.password.length > self.maxLength) {
                    $scope.invalidMessage += " 'Password' exceeds maximum character length of " + self.maxLength + ".";
                    $scope.invalid = true;
                }
                if ($scope.data.confirmPassword && $scope.data.confirmPassword.length > self.maxLength) {
                    $scope.invalidMessage += " 'Confirm Password' exceeds maximum character length of " + self.maxLength + ".";
                    $scope.invalid = true;
                }
                if (!$scope.invalidMessage) {
                    $scope.invalid = false;
                }
            };

            self.init = function() {
                $scope.data = {
                    password: $scope.field.value.$,
                    confirmPassword: $scope.field.value.$
                };
                self.validate();
            };

            self.init();

            $scope.mouseEnter = function () {
                $scope.mouseOver = true;
                self.validate();
            };
            $scope.mouseLeave = function () {
                $scope.mouseOver = false;
                self.validate();
            };

            $scope.onChange = function() {
                $scope.field.value.$ = $scope.data.password;
                self.validate();
            };

            $scope.onConfirmChange = function() {
                self.validate();
            };

            $scope.readOnlyPasswordPlaceHolder = undefined;
            $scope.passwordPlaceHolder = undefined;
            $scope.mouseOver = false;
            $scope.invalid = false;
            $scope.invalidMessage = undefined;

            $scope.$watch('field.editor.isEditing', function (isEditing) {
                $scope.readOnlyPasswordPlaceHolder = $scope.data.password ? 'Password Exists' : 'No Password Yet';
                $scope.passwordPlaceHolder = $scope.data.confirmPassword ? 'Password Exists, Change Password' : 'No Password Yet, Set New Password';
            });

            $scope.$watch('field.value.$', function () {
                if (!$scope.field.editor.isEditing)
                    self.init();
            });
        }]);

    module.directive('stdPasswordEdit',
        ['$templateCache', 'stdDisplay',
            function($templateCache, display) {
                return {
                    restrict: 'E',
                    scope: {
                        field: '=',
                        label: '@'
                    },
                    controller: 'stdPasswordEditController',
                    template: $templateCache.get('src/templates/edit/std-password-edit.html'),
                    link: function(scope, element) {
                        display.setVisibility(element, scope.field.type.canDisplay);
                    }
                };
            }
        ]);
})();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta name="collection" content="api">

<TITLE>
java.lang (Java 2 Platform SE 5.0)
</TITLE>

<META NAME="keywords" CONTENT="java.lang package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../stylesheet.css" TITLE="Style">

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Package java.lang

Provides classes that are fundamental to the design of the Java
programming language.

See:

          Description

Interface Summary

Appendable
An object to which <tt>char</tt> sequences and values can be appended.

CharSequence
A <tt>CharSequence</tt> is a readable sequence of char values.

Cloneable
A class implements the Cloneable interface to
 indicate to the Object.clone() method that it
 is legal for that method to make a
 field-for-field copy of instances of that class.

Comparable<T>
This interface imposes a total ordering on the objects of each class that
 implements it.

Iterable<T>
Implementing this interface allows an object to be the target of
  the "foreach" statement.

Readable
A <tt>Readable</tt> is a source of characters.

Runnable
The Runnable interface should be implemented by any
 class whose instances are intended to be executed by a thread.

Thread.UncaughtExceptionHandler
Interface for handlers invoked when a <tt>Thread</tt> abruptly
 terminates due to an uncaught exception.

Class Summary

Boolean
The Boolean class wraps a value of the primitive type
 boolean in an object.

Byte
The Byte class wraps a value of primitive type
 byte in an object.

Character
The Character class wraps a value of the primitive
 type char in an object.

Character.Subset
Instances of this class represent particular subsets of the Unicode
 character set.

Character.UnicodeBlock
A family of character subsets representing the character blocks in the
 Unicode specification.

Class<T>
Instances of the class Class represent classes and
 interfaces in a running Java application.

ClassLoader
A class loader is an object that is responsible for loading classes.

Compiler
The Compiler class is provided to support
 Java-to-native-code compilers and related services.

Double
The Double class wraps a value of the primitive type
 double in an object.

Enum<E extends Enum<E>>
This is the common base class of all Java language enumeration types.

Float
The Float class wraps a value of primitive type
 float in an object.

InheritableThreadLocal<T>
This class extends <tt>ThreadLocal</tt> to provide inheritance of values
 from parent thread to child thread: when a child thread is created, the
 child receives initial values for all inheritable thread-local variables
 for which the parent has values.

Integer
The Integer class wraps a value of the primitive type
 int in an object.

Long
The Long class wraps a value of the primitive type
 long in an object.

Math
The class Math contains methods for performing basic
 numeric operations such as the elementary exponential, logarithm,
 square root, and trigonometric functions.

Number
The abstract class Number is the superclass of classes
 BigDecimal, BigInteger,
 Byte, Double, Float,
 Integer, Long, and Short.

Object
Class Object is the root of the class hierarchy.

Package
Package objects contain version information
 about the implementation and specification of a Java package.

Process
The ProcessBuilder.start() and
 Runtime.exec
 methods create a native process and
 return an instance of a subclass of Process that can
 be used to control the process and obtain information about it.

ProcessBuilder
This class is used to create operating system processes.

Runtime
Every Java application has a single instance of class
 Runtime that allows the application to interface with
 the environment in which the application is running.

RuntimePermission
This class is for runtime permissions.

SecurityManager
The security manager is a class that allows
 applications to implement a security policy.

Short
The Short class wraps a value of primitive type
 short in an object.

StackTraceElement
An element in a stack trace, as returned by Throwable.getStackTrace().

StrictMath
The class StrictMath contains methods for performing basic
 numeric operations such as the elementary exponential, logarithm,
 square root, and trigonometric functions.

String
The String class represents character strings.

StringBuffer
A thread-safe, mutable sequence of characters.

StringBuilder
A mutable sequence of characters.

System
The System class contains several useful class fields
 and methods.

Thread
A thread is a thread of execution in a program.

ThreadGroup
A thread group represents a set of threads.

ThreadLocal<T>
This class provides thread-local variables.

Throwable
The Throwable class is the superclass of all errors and
 exceptions in the Java language.

Void
The Void class is an uninstantiable placeholder class to hold a
 reference to the Class object representing the Java keyword
 void.

Enum Summary

Thread.State
A thread state.

Exception Summary

ArithmeticException
Thrown when an exceptional arithmetic condition has occurred.

ArrayIndexOutOfBoundsException
Thrown to indicate that an array has been accessed with an
 illegal index.

ArrayStoreException
Thrown to indicate that an attempt has been made to store the
 wrong type of object into an array of objects.

ClassCastException
Thrown to indicate that the code has attempted to cast an object
 to a subclass of which it is not an instance.

ClassNotFoundException
Thrown when an application tries to load in a class through its
 string name using:

 The forName method in class Class.

CloneNotSupportedException
Thrown to indicate that the clone method in class
 Object has been called to clone an object, but that
 the object's class does not implement the Cloneable
 interface.

EnumConstantNotPresentException
Thrown when an application tries to access an enum constant by name
 and the enum type contains no constant with the specified name.

Exception
The class Exception and its subclasses are a form of
 Throwable that indicates conditions that a reasonable
 application might want to catch.

IllegalAccessException
An IllegalAccessException is thrown when an application tries
 to reflectively create an instance (other than an array),
 set or get a field, or invoke a method, but the currently
 executing method does not have access to the definition of
 the specified class, field, method or constructor.

IllegalArgumentException
Thrown to indicate that a method has been passed an illegal or
 inappropriate argument.

IllegalMonitorStateException
Thrown to indicate that a thread has attempted to wait on an
 object's monitor or to notify other threads waiting on an object's
 monitor without owning the specified monitor.

IllegalStateException
Signals that a method has been invoked at an illegal or
 inappropriate time.

IllegalThreadStateException
Thrown to indicate that a thread is not in an appropriate state
 for the requested operation.

IndexOutOfBoundsException
Thrown to indicate that an index of some sort (such as to an array, to a
 string, or to a vector) is out of range.

InstantiationException
Thrown when an application tries to create an instance of a class
 using the newInstance method in class
 Class, but the specified class object cannot be
 instantiated because it is an interface or is an abstract class.

InterruptedException
Thrown when a thread is waiting, sleeping, or otherwise paused for
 a long time and another thread interrupts it using the
 interrupt  method in class Thread.

NegativeArraySizeException
Thrown if an application tries to create an array with negative size.

NoSuchFieldException
Signals that the class doesn't have a field of a specified name.

NoSuchMethodException
Thrown when a particular method cannot be found.

NullPointerException
Thrown when an application attempts to use null in a
 case where an object is required.

NumberFormatException
Thrown to indicate that the application has attempted to convert
 a string to one of the numeric types, but that the string does not
 have the appropriate format.

RuntimeException
RuntimeException is the superclass of those
 exceptions that can be thrown during the normal operation of the
 Java Virtual Machine.

SecurityException
Thrown by the security manager to indicate a security violation.

StringIndexOutOfBoundsException
Thrown by String methods to indicate that an index
 is either negative or greater than the size of the string.

TypeNotPresentException
Thrown when an application tries to access a type using a string
 representing the type's name, but no definition for the type with
 the specified name can be found.

UnsupportedOperationException
Thrown to indicate that the requested operation is not supported.

Error Summary

AbstractMethodError
Thrown when an application tries to call an abstract method.

AssertionError
Thrown to indicate that an assertion has failed.

ClassCircularityError
Thrown when a circularity has been detected while initializing a class.

ClassFormatError
Thrown when the Java Virtual Machine attempts to read a class
 file and determines that the file is malformed or otherwise cannot
 be interpreted as a class file.

Error
An Error is a subclass of Throwable
 that indicates serious problems that a reasonable application
 should not try to catch.

ExceptionInInitializerError
Signals that an unexpected exception has occurred in a static initializer.

IllegalAccessError
Thrown if an application attempts to access or modify a field, or
 to call a method that it does not have access to.

IncompatibleClassChangeError
Thrown when an incompatible class change has occurred to some class
 definition.

InstantiationError
Thrown when an application tries to use the Java new
 construct to instantiate an abstract class or an interface.

InternalError
Thrown to indicate some unexpected internal error has occurred in
 the Java Virtual Machine.

LinkageError
Subclasses of LinkageError indicate that a class has
 some dependency on another class; however, the latter class has
 incompatibly changed after the compilation of the former class.

NoClassDefFoundError
Thrown if the Java Virtual Machine or a ClassLoader instance
 tries to load in the definition of a class (as part of a normal method call
 or as part of creating a new instance using the new expression)
 and no definition of the class could be found.

NoSuchFieldError
Thrown if an application tries to access or modify a specified
 field of an object, and that object no longer has that field.

NoSuchMethodError
Thrown if an application tries to call a specified method of a
 class (either static or instance), and that class no longer has a
 definition of that method.

OutOfMemoryError
Thrown when the Java Virtual Machine cannot allocate an object
 because it is out of memory, and no more memory could be made
 available by the garbage collector.

StackOverflowError
Thrown when a stack overflow occurs because an application
 recurses too deeply.

ThreadDeath
An instance of ThreadDeath is thrown in the victim
 thread when the stop method with zero arguments in
 class Thread is called.

UnknownError
Thrown when an unknown but serious exception has occurred in the
 Java Virtual Machine.

UnsatisfiedLinkError
Thrown if the Java Virtual Machine cannot find an appropriate
 native-language definition of a method declared native.

UnsupportedClassVersionError
Thrown when the Java Virtual Machine attempts to read a class
 file and determines that the major and minor version numbers
 in the file are not supported.

VerifyError
Thrown when the "verifier" detects that a class file,
 though well formed, contains some sort of internal inconsistency
 or security problem.

VirtualMachineError
Thrown to indicate that the Java Virtual Machine is broken or has
 run out of resources necessary for it to continue operating.

Annotation Types Summary

Deprecated
A program element annotated @Deprecated is one that programmers
 are discouraged from using, typically because it is dangerous,
 or because a better alternative exists.

Override
Indicates that a method declaration is intended to override a
 method declaration in a superclass.

SuppressWarnings
Indicates that the named compiler warnings should be suppressed in the
 annotated element (and in all program elements contained in the annotated
 element).

Package java.lang Description

Provides classes that are fundamental to the design of the Java
programming language. The most important classes are Object,
which is the root of the class hierarchy, and Class, instances of
which represent classes at run time.

Frequently it is necessary to represent a value of primitive type as
if it were an object. The wrapper classes Boolean,
Character, Integer, Long, Float, and
Double serve this purpose. An object of type Double,
for example, contains a field whose type is double, representing that
value in such a way that a reference to it can be stored in a variable
of reference type. These classes also provide a number of methods for
converting among primitive values, as well as supporting such
standard methods as equals and hashCode.  The Void class is a
non-instantiable class that holds a reference to a Class object
represening the primitive type void.

The class Math provides commonly used mathematical functions such
as sine, cosine, and square root. The classes String and
StringBuffer similarly provide commonly used operations on
character strings.

Classes ClassLoader, Process, Runtime,
SecurityManager, and System provide "system operations"
that manage the dynamic loading of classes, creation of external processes,
host environment inquiries such as the time of day, and enforcement of
security policies.

Class Throwable encompasses objects that may be thrown by the
throw statement (§14.16). Subclasses of Throwable represent errors
and exceptions.

Package Specification

Character Encodings

The specification of the java.nio.charset.Charset class describes the naming conventions for character
encodings as well as the set of standard encodings that must be supported by
every implementation of the Java platform.

Since:

JDK1.0

      Overview
    Package
      Class
      Use
      Tree
      Deprecated
      Index
      Help

JavaTM 2 Platform
Standard Ed. 5.0

 PREV PACKAGE
 NEXT PACKAGE

  FRAMES
 NO FRAMES

  All Classes

Submit a bug or feature
For further API reference and developer documentation, see Java 2 SDK SE Developer Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 2004, 2010 Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.


text:
package org.usfirst.frc.team3335.robot.commands;

import org.usfirst.frc.team3335.robot.Robot;

import edu.wpi.first.wpilibj.command.Command;

public class IntakeBalls extends Command {

	private final boolean finished;
	private final double speed;

	public IntakeBalls(boolean isFinished, double speed) {
		requires(Robot.intake);
		finished=isFinished;
		this.speed = speed;
	}

	@Override
    protected void initialize() {
        Robot.intake.set(speed);
    }

	@Override
	protected void end() {
		Robot.intake.set(0);
	}

	@Override
	protected boolean isFinished() {
		// TODO Auto-generated method stub
		return finished;
	}

}


text:
const should = require('should');
const supertest = require('supertest');
const config = require('../../../core/shared/config');
const testUtils = require('../../utils');
const localUtils = require('./utils');

describe('Roles API', function () {
    let request;

    before(async function () {
        await localUtils.startGhost();
        request = supertest.agent(config.get('url'));
        await localUtils.doAuth(request, 'posts');
    });

    it('Can request all roles', async function () {
        const res = await request.get(localUtils.API.getApiQuery('roles/'))
            .set('Origin', config.get('url'))
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .expect(200);

        should.not.exist(res.headers['x-cache-invalidate']);
        const response = res.body;
        should.exist(response);
        should.exist(response.roles);
        localUtils.API.checkResponse(response, 'roles');
        response.roles.should.have.length(8);
        localUtils.API.checkResponse(response.roles[0], 'role');
        localUtils.API.checkResponse(response.roles[1], 'role');
        localUtils.API.checkResponse(response.roles[2], 'role');
        localUtils.API.checkResponse(response.roles[3], 'role');
        localUtils.API.checkResponse(response.roles[4], 'role');
        localUtils.API.checkResponse(response.roles[5], 'role');
        localUtils.API.checkResponse(response.roles[6], 'role');
        localUtils.API.checkResponse(response.roles[7], 'role');
    });

    it('Can request roles which i am able to assign to other users', async function () {
        const res = await request.get(localUtils.API.getApiQuery('roles/?permissions=assign'))
            .set('Origin', config.get('url'))
            .expect('Content-Type', /json/)
            .expect('Cache-Control', testUtils.cacheRules.private)
            .expect(200);

        should.not.exist(res.headers['x-cache-invalidate']);
        const response = res.body;
        should.exist(response.roles);
        localUtils.API.checkResponse(response, 'roles');
        response.roles.should.have.length(4);
        localUtils.API.checkResponse(response.roles[0], 'role');
        localUtils.API.checkResponse(response.roles[1], 'role');
        localUtils.API.checkResponse(response.roles[2], 'role');
        localUtils.API.checkResponse(response.roles[3], 'role');
        response.roles[0].name.should.equal('Administrator');
        response.roles[1].name.should.equal('Editor');
        response.roles[2].name.should.equal('Author');
        response.roles[3].name.should.equal('Contributor');
    });
});


text:
<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta charset="utf-8">
	<title>SAPUI5 Data Binding Tutorial</title>
	<script
		id="sap-ui-bootstrap"
		src="../../../../../../../../../resources/sap-ui-core.js"
		data-sap-ui-theme="sap_belize"
		data-sap-ui-libs="sap.m"
		data-sap-ui-compatVersion="edge"
		data-sap-ui-preload="async"
		data-sap-ui-resourceroots='{ "sap.ui.demo.db": "./" }'
		>
	</script>
	<script>
		// ------------------------------------------------------------------------
		// Attach an anonymous function to the SAPUI5 'init' event
		sap.ui.getCore().attachInit(function () {
			var oModel = new sap.ui.model.json.JSONModel({
				firstName: "Harry",
				lastName: "Hawk",
				enabled: true,
				address: {
					street: "Dietmar-Hopp-Allee 16",
					city: "Walldorf",
					zip: "69190",
					country: "Germany"
				},
				"salesToDate" : 12345.6789,
				"currencyCode" : "EUR"
			});

			// Assign the model object to the SAPUI5 core
			sap.ui.getCore().setModel(oModel);

			var oResourceBundle = new sap.ui.model.resource.ResourceModel({
				bundleName: "sap.ui.demo.db.i18n.i18n"
			});

			sap.ui.getCore().setModel(oResourceBundle, "i18n");

			// Display the XML view called "App"
			new sap.ui.core.mvc.XMLView({viewName: "sap.ui.demo.db.view.App"}).
				placeAt("content");
		});
	</script>
</head>
<body class="sapUiBody" id="content">
</body>
</html>