text:
package org.apache.spark.deploy.yarn

import java.io.File
import java.net.URL
import java.nio.charset.StandardCharsets
import java.util.{HashMap => JHashMap}

import scala.collection.mutable
import scala.concurrent.duration._
import scala.language.postfixOps

import com.google.common.io.{ByteStreams, Files}
import org.apache.hadoop.yarn.conf.YarnConfiguration
import org.scalatest.Matchers
import org.scalatest.concurrent.Eventually._

import org.apache.spark._
import org.apache.spark.deploy.SparkHadoopUtil
import org.apache.spark.internal.Logging
import org.apache.spark.launcher._
import org.apache.spark.scheduler.{SparkListener, SparkListenerApplicationStart,
  SparkListenerExecutorAdded}
import org.apache.spark.scheduler.cluster.ExecutorInfo
import org.apache.spark.tags.ExtendedYarnTest
import org.apache.spark.util.Utils

/**
 * Integration tests for YARN; these tests use a mini Yarn cluster to run Spark-on-YARN
 * applications, and require the Spark assembly to be built before they can be successfully
 * run.
 */
@ExtendedYarnTest
class YarnClusterSuite extends BaseYarnClusterSuite {

  override def newYarnConfig(): YarnConfiguration = new YarnConfiguration()

  private val TEST_PYFILE = """
    |import mod1, mod2
    |import sys
    |from operator import add
    |
    |from pyspark import SparkConf , SparkContext
    |if __name__ == "__main__":
    |    if len(sys.argv) != 2:
    |        print >> sys.stderr, "Usage: test.py [result file]"
    |        exit(-1)
    |    sc = SparkContext(conf=SparkConf())
    |    status = open(sys.argv[1],'w')
    |    result = "failure"
    |    rdd = sc.parallelize(range(10)).map(lambda x: x * mod1.func() * mod2.func())
    |    cnt = rdd.count()
    |    if cnt == 10:
    |        result = "success"
    |    status.write(result)
    |    status.close()
    |    sc.stop()
    """.stripMargin

  private val TEST_PYMODULE = """
    |def func():
    |    return 42
    """.stripMargin

  test("run Spark in yarn-client mode") {
    testBasicYarnApp(true)
  }

  test("run Spark in yarn-cluster mode") {
    testBasicYarnApp(false)
  }

  test("run Spark in yarn-client mode with different configurations") {
    testBasicYarnApp(true,
      Map(
        "spark.driver.memory" -> "512m",
        "spark.executor.cores" -> "1",
        "spark.executor.memory" -> "512m",
        "spark.executor.instances" -> "2"
      ))
  }

  test("run Spark in yarn-cluster mode with different configurations") {
    testBasicYarnApp(false,
      Map(
        "spark.driver.memory" -> "512m",
        "spark.driver.cores" -> "1",
        "spark.executor.cores" -> "1",
        "spark.executor.memory" -> "512m",
        "spark.executor.instances" -> "2"
      ))
  }

  test("run Spark in yarn-cluster mode with using SparkHadoopUtil.conf") {
    testYarnAppUseSparkHadoopUtilConf()
  }

  test("run Spark in yarn-client mode with additional jar") {
    testWithAddJar(true)
  }

  test("run Spark in yarn-cluster mode with additional jar") {
    testWithAddJar(false)
  }

  test("run Spark in yarn-cluster mode unsuccessfully") {
    // Don't provide arguments so the driver will fail.
    val finalState = runSpark(false, mainClassName(YarnClusterDriver.getClass))
    finalState should be (SparkAppHandle.State.FAILED)
  }

  test("run Spark in yarn-cluster mode failure after sc initialized") {
    val finalState = runSpark(false, mainClassName(YarnClusterDriverWithFailure.getClass))
    finalState should be (SparkAppHandle.State.FAILED)
  }

  test("run Python application in yarn-client mode") {
    testPySpark(true)
  }

  test("run Python application in yarn-cluster mode") {
    testPySpark(false)
  }

  test("user class path first in client mode") {
    testUseClassPathFirst(true)
  }

  test("user class path first in cluster mode") {
    testUseClassPathFirst(false)
  }

  test("monitor app using launcher library") {
    val env = new JHashMap[String, String]()
    env.put("YARN_CONF_DIR", hadoopConfDir.getAbsolutePath())

    val propsFile = createConfFile()
    val handle = new SparkLauncher(env)
      .setSparkHome(sys.props("spark.test.home"))
      .setConf("spark.ui.enabled", "false")
      .setPropertiesFile(propsFile)
      .setMaster("yarn")
      .setDeployMode("client")
      .setAppResource(SparkLauncher.NO_RESOURCE)
      .setMainClass(mainClassName(YarnLauncherTestApp.getClass))
      .startApplication()

    try {
      eventually(timeout(30 seconds), interval(100 millis)) {
        handle.getState() should be (SparkAppHandle.State.RUNNING)
      }

      handle.getAppId() should not be (null)
      handle.getAppId() should startWith ("application_")
      handle.stop()

      eventually(timeout(30 seconds), interval(100 millis)) {
        handle.getState() should be (SparkAppHandle.State.KILLED)
      }
    } finally {
      handle.kill()
    }
  }

  private def testBasicYarnApp(clientMode: Boolean, conf: Map[String, String] = Map()): Unit = {
    val result = File.createTempFile("result", null, tempDir)
    val finalState = runSpark(clientMode, mainClassName(YarnClusterDriver.getClass),
      appArgs = Seq(result.getAbsolutePath()),
      extraConf = conf)
    checkResult(finalState, result)
  }

  private def testYarnAppUseSparkHadoopUtilConf(): Unit = {
    val result = File.createTempFile("result", null, tempDir)
    val finalState = runSpark(false,
      mainClassName(YarnClusterDriverUseSparkHadoopUtilConf.getClass),
      appArgs = Seq("key=value", result.getAbsolutePath()),
      extraConf = Map("spark.hadoop.key" -> "value"))
    checkResult(finalState, result)
  }

  private def testWithAddJar(clientMode: Boolean): Unit = {
    val originalJar = TestUtils.createJarWithFiles(Map("test.resource" -> "ORIGINAL"), tempDir)
    val driverResult = File.createTempFile("driver", null, tempDir)
    val executorResult = File.createTempFile("executor", null, tempDir)
    val finalState = runSpark(clientMode, mainClassName(YarnClasspathTest.getClass),
      appArgs = Seq(driverResult.getAbsolutePath(), executorResult.getAbsolutePath()),
      extraClassPath = Seq(originalJar.getPath()),
      extraJars = Seq("local:" + originalJar.getPath()))
    checkResult(finalState, driverResult, "ORIGINAL")
    checkResult(finalState, executorResult, "ORIGINAL")
  }

  private def testPySpark(clientMode: Boolean): Unit = {
    val primaryPyFile = new File(tempDir, "test.py")
    Files.write(TEST_PYFILE, primaryPyFile, StandardCharsets.UTF_8)

    // When running tests, let's not assume the user has built the assembly module, which also
    // creates the pyspark archive. Instead, let's use PYSPARK_ARCHIVES_PATH to point at the
    // needed locations.
    val sparkHome = sys.props("spark.test.home")
    val pythonPath = Seq(
        s"$sparkHome/python/lib/py4j-0.10.3-src.zip",
        s"$sparkHome/python")
    val extraEnv = Map(
      "PYSPARK_ARCHIVES_PATH" -> pythonPath.map("local:" + _).mkString(File.pathSeparator),
      "PYTHONPATH" -> pythonPath.mkString(File.pathSeparator))

    val moduleDir =
      if (clientMode) {
        // In client-mode, .py files added with --py-files are not visible in the driver.
        // This is something that the launcher library would have to handle.
        tempDir
      } else {
        val subdir = new File(tempDir, "pyModules")
        subdir.mkdir()
        subdir
      }
    val pyModule = new File(moduleDir, "mod1.py")
    Files.write(TEST_PYMODULE, pyModule, StandardCharsets.UTF_8)

    val mod2Archive = TestUtils.createJarWithFiles(Map("mod2.py" -> TEST_PYMODULE), moduleDir)
    val pyFiles = Seq(pyModule.getAbsolutePath(), mod2Archive.getPath()).mkString(",")
    val result = File.createTempFile("result", null, tempDir)

    val finalState = runSpark(clientMode, primaryPyFile.getAbsolutePath(),
      sparkArgs = Seq("--py-files" -> pyFiles),
      appArgs = Seq(result.getAbsolutePath()),
      extraEnv = extraEnv)
    checkResult(finalState, result)
  }

  private def testUseClassPathFirst(clientMode: Boolean): Unit = {
    // Create a jar file that contains a different version of "test.resource".
    val originalJar = TestUtils.createJarWithFiles(Map("test.resource" -> "ORIGINAL"), tempDir)
    val userJar = TestUtils.createJarWithFiles(Map("test.resource" -> "OVERRIDDEN"), tempDir)
    val driverResult = File.createTempFile("driver", null, tempDir)
    val executorResult = File.createTempFile("executor", null, tempDir)
    val finalState = runSpark(clientMode, mainClassName(YarnClasspathTest.getClass),
      appArgs = Seq(driverResult.getAbsolutePath(), executorResult.getAbsolutePath()),
      extraClassPath = Seq(originalJar.getPath()),
      extraJars = Seq("local:" + userJar.getPath()),
      extraConf = Map(
        "spark.driver.userClassPathFirst" -> "true",
        "spark.executor.userClassPathFirst" -> "true"))
    checkResult(finalState, driverResult, "OVERRIDDEN")
    checkResult(finalState, executorResult, "OVERRIDDEN")
  }

}

private[spark] class SaveExecutorInfo extends SparkListener {
  val addedExecutorInfos = mutable.Map[String, ExecutorInfo]()
  var driverLogs: Option[collection.Map[String, String]] = None

  override def onExecutorAdded(executor: SparkListenerExecutorAdded) {
    addedExecutorInfos(executor.executorId) = executor.executorInfo
  }

  override def onApplicationStart(appStart: SparkListenerApplicationStart): Unit = {
    driverLogs = appStart.driverLogs
  }
}

private object YarnClusterDriverWithFailure extends Logging with Matchers {
  def main(args: Array[String]): Unit = {
    val sc = new SparkContext(new SparkConf()
      .set("spark.extraListeners", classOf[SaveExecutorInfo].getName)
      .setAppName("yarn test with failure"))

    throw new Exception("exception after sc initialized")
  }
}

private object YarnClusterDriverUseSparkHadoopUtilConf extends Logging with Matchers {
  def main(args: Array[String]): Unit = {
    if (args.length != 2) {
      // scalastyle:off println
      System.err.println(
        s"""
        |Invalid command line: ${args.mkString(" ")}
        |
        |Usage: YarnClusterDriverUseSparkHadoopUtilConf [hadoopConfKey=value] [result file]
        """.stripMargin)
      // scalastyle:on println
      System.exit(1)
    }

    val sc = new SparkContext(new SparkConf()
      .set("spark.extraListeners", classOf[SaveExecutorInfo].getName)
      .setAppName("yarn test using SparkHadoopUtil's conf"))

    val kv = args(0).split("=")
    val status = new File(args(1))
    var result = "failure"
    try {
      SparkHadoopUtil.get.conf.get(kv(0)) should be (kv(1))
      result = "success"
    } finally {
      Files.write(result, status, StandardCharsets.UTF_8)
      sc.stop()
    }
  }
}

private object YarnClusterDriver extends Logging with Matchers {

  val WAIT_TIMEOUT_MILLIS = 10000

  def main(args: Array[String]): Unit = {
    if (args.length != 1) {
      // scalastyle:off println
      System.err.println(
        s"""
        |Invalid command line: ${args.mkString(" ")}
        |
        |Usage: YarnClusterDriver [result file]
        """.stripMargin)
      // scalastyle:on println
      System.exit(1)
    }

    val sc = new SparkContext(new SparkConf()
      .set("spark.extraListeners", classOf[SaveExecutorInfo].getName)
      .setAppName("yarn \"test app\" 'with quotes' and \\back\\slashes and $dollarSigns"))
    val conf = sc.getConf
    val status = new File(args(0))
    var result = "failure"
    try {
      val data = sc.parallelize(1 to 4, 4).collect().toSet
      sc.listenerBus.waitUntilEmpty(WAIT_TIMEOUT_MILLIS)
      data should be (Set(1, 2, 3, 4))
      result = "success"

      // Verify that the config archive is correctly placed in the classpath of all containers.
      val confFile = "/" + Client.SPARK_CONF_FILE
      assert(getClass().getResource(confFile) != null)
      val configFromExecutors = sc.parallelize(1 to 4, 4)
        .map { _ => Option(getClass().getResource(confFile)).map(_.toString).orNull }
        .collect()
      assert(configFromExecutors.find(_ == null) === None)
    } finally {
      Files.write(result, status, StandardCharsets.UTF_8)
      sc.stop()
    }

    // verify log urls are present
    val listeners = sc.listenerBus.findListenersByClass[SaveExecutorInfo]
    assert(listeners.size === 1)
    val listener = listeners(0)
    val executorInfos = listener.addedExecutorInfos.values
    assert(executorInfos.nonEmpty)
    executorInfos.foreach { info =>
      assert(info.logUrlMap.nonEmpty)
    }

    // If we are running in yarn-cluster mode, verify that driver logs links and present and are
    // in the expected format.
    if (conf.get("spark.submit.deployMode") == "cluster") {
      assert(listener.driverLogs.nonEmpty)
      val driverLogs = listener.driverLogs.get
      assert(driverLogs.size === 2)
      assert(driverLogs.contains("stderr"))
      assert(driverLogs.contains("stdout"))
      val urlStr = driverLogs("stderr")
      // Ensure that this is a valid URL, else this will throw an exception
      new URL(urlStr)
      val containerId = YarnSparkHadoopUtil.get.getContainerId
      val user = Utils.getCurrentUserName()
      assert(urlStr.endsWith(s"/node/containerlogs/$containerId/$user/stderr?start=-4096"))
    }
  }

}

private object YarnClasspathTest extends Logging {
  def error(m: String, ex: Throwable = null): Unit = {
    logError(m, ex)
    // scalastyle:off println
    System.out.println(m)
    if (ex != null) {
      ex.printStackTrace(System.out)
    }
    // scalastyle:on println
  }

  def main(args: Array[String]): Unit = {
    if (args.length != 2) {
      error(
        s"""
        |Invalid command line: ${args.mkString(" ")}
        |
        |Usage: YarnClasspathTest [driver result file] [executor result file]
        """.stripMargin)
      // scalastyle:on println
    }

    readResource(args(0))
    val sc = new SparkContext(new SparkConf())
    try {
      sc.parallelize(Seq(1)).foreach { x => readResource(args(1)) }
    } finally {
      sc.stop()
    }
  }

  private def readResource(resultPath: String): Unit = {
    var result = "failure"
    try {
      val ccl = Thread.currentThread().getContextClassLoader()
      val resource = ccl.getResourceAsStream("test.resource")
      val bytes = ByteStreams.toByteArray(resource)
      result = new String(bytes, 0, bytes.length, StandardCharsets.UTF_8)
    } catch {
      case t: Throwable =>
        error(s"loading test.resource to $resultPath", t)
    } finally {
      Files.write(result, new File(resultPath), StandardCharsets.UTF_8)
    }
  }

}

private object YarnLauncherTestApp {

  def main(args: Array[String]): Unit = {
    // Do not stop the application; the test will stop it using the launcher lib. Just run a task
    // that will prevent the process from exiting.
    val sc = new SparkContext(new SparkConf())
    sc.parallelize(Seq(1)).foreach { i =>
      this.synchronized {
        wait()
      }
    }
  }

}


text:
@interface Pair : NSObject

@property (nonatomic, strong) id first;
@property (nonatomic, strong) id second;

@end

redpajama_set_name: RedPajamaGithub


text:
module Admin::ApplicationHelper
  def roles
    hash = {}
    Role.available_roles.each do |role|
      hash[role.titleize] = role
    end
    hash
  end
end


text:
namespace IntUITive.Selenium.Tests.HtmlTestHelpers
{
    using System;
    using System.IO;
    using System.Text.RegularExpressions;

    public class TemporaryHelperFile : IDisposable
    {
        private readonly string _tempHtmlFile;

        public TemporaryHelperFile()
        {
            var tempFileName = Path.GetTempFileName();
            _tempHtmlFile = tempFileName + ".html";
            File.Move(tempFileName, _tempHtmlFile);
        }

        public string TempHtmlFile
        {
            get { return _tempHtmlFile; }
        }

        public void Dispose()
        {
            DeleteFile();
        }

        public string AsUri()
        {
            return new Uri(_tempHtmlFile).AbsoluteUri;
        }

        public void DeleteFile()
        {
            if (File.Exists(_tempHtmlFile))
            {
                File.Delete(_tempHtmlFile);
            }
        }

        public TemporaryHelperFile FromHtml(string htmlSource)
        {
            var hasDoctypeTag = Regex.IsMatch(htmlSource, @"\<!DOCTYPE", RegexOptions.IgnoreCase);
            var hasHtmlTag = Regex.IsMatch(htmlSource, @"\<html", RegexOptions.IgnoreCase);
            var hasHeadTag = Regex.IsMatch(htmlSource, @"\<head", RegexOptions.IgnoreCase);
            var hasBodyTag = Regex.IsMatch(htmlSource, @"\<body", RegexOptions.IgnoreCase);

            using (var sw = new StreamWriter(_tempHtmlFile))
            {
                var htmlBody = hasBodyTag ? htmlSource : string.Format("{0}</body", htmlSource);
                var htmlContents = hasHeadTag
                    ? htmlBody
                    : string.Format("<meta charset=\"utf-8\" /><title>temporary test page</title>{0}",
                        htmlBody);
                var htmlElement = hasHtmlTag ? htmlContents : string.Format("{0}", htmlContents);
                var html = hasDoctypeTag ? htmlElement : string.Format("<!DOCTYPE html>{0}", htmlElement);

                sw.WriteLine(html);
                sw.Close();
            }

            return this;
        }
    }
}


text:
<?php

/**
 * La clase encapsula la logica de negocio asociada a las preferencias del sistema.
 *
 *
 * @package     pragtico
 * @subpackage  app.controllers
 */
class PreferenciasController extends AppController {

    var $paginate = array(
        'order' => array(
            'Preferencia.nombre' => 'asc'
        )
    );

/**
 * valores.
 * Muestra via desglose los valores que puede asumir la preferencia.
 */
	function valores($id) {
		$this->data = $this->Preferencia->read(null, $id);
	}

}
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/goods_sub_shape" android:state_pressed="false"/>

    <item android:drawable="@drawable/goods_add_shape" android:state_pressed="true"/>

</selector>


text:
HammerWeather
=============


text:
#include "config.h"
#include "core/css/CSSLineBoxContainValue.h"

#include "core/dom/WebCoreMemoryInstrumentation.h"
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>

namespace WebCore {

CSSLineBoxContainValue::CSSLineBoxContainValue(unsigned value)
    : CSSValue(LineBoxContainClass)
    , m_value(value)
{
}

String CSSLineBoxContainValue::customCssText() const
{
    StringBuilder text;

    if (m_value & LineBoxContainBlock)
        text.appendLiteral("block");
    if (m_value & LineBoxContainInline) {
        if (!text.isEmpty())
            text.append(' ');
        text.appendLiteral("inline");
    }
    if (m_value & LineBoxContainFont) {
        if (!text.isEmpty())
            text.append(' ');
        text.appendLiteral("font");
    }
    if (m_value & LineBoxContainGlyphs) {
        if (!text.isEmpty())
            text.append(' ');
        text.appendLiteral("glyphs");
    }
    if (m_value & LineBoxContainReplaced) {
        if (!text.isEmpty())
            text.append(' ');
        text.appendLiteral("replaced");
    }
    if (m_value & LineBoxContainInlineBox) {
        if (!text.isEmpty())
            text.append(' ');
        text.appendLiteral("inline-box");
    }

    return text.toString();
}

void CSSLineBoxContainValue::reportDescendantMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
{
    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
}

}


text:
package org.jboss.vfs.protocol;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import junit.framework.TestSuite;
import org.jboss.test.vfs.AbstractVFSTest;
import org.jboss.vfs.VirtualFile;
import org.junit.Assert;
import org.junit.Test;

/**
 * Provides test cases for WFLY16322, which was broken in
 * JDK-8273655
 * content-types.properties files are missing some common types
 * and released in 17.0.3, 11.0.16, 13.0.12 and 15.0.8. The JDK issue implements
 * a content type for Java Archives, which breaks the expectation that
 * getContent() returns the VirtualFile (behavior for when the content type is
 * {@code null}.
 */
public class VirtualFileURLConnectionTest extends AbstractVFSTest {
    public VirtualFileURLConnectionTest(String name) {
        super(name);
    }

    public static junit.framework.Test suite() {
        return new TestSuite(VirtualFileURLConnectionTest.class);
    }

    @Test
    public void testFixWFLY16322ContentTypeJarShouldReturnVirtualFile() throws MalformedURLException, IOException {
        VirtualFile jar = getVirtualFile("/vfs/test/dup.jar");

        URL url = getResource("/vfs/test/dup.jar");
        VirtualFileURLConnection con = new VirtualFileURLConnection(url) {
            public String getContentType() {
                return VirtualFileURLConnection.JAR_CONTENT_TYPE;
            }
        };

        Object content = con.getContent();
        Assert.assertTrue(content instanceof VirtualFile);
    }

    @Test
    public void testFixWFLY16322NullValueShouldReturnVirtualFile() throws MalformedURLException, IOException {
        VirtualFile jar = getVirtualFile("/vfs/test/dup.jar");

        URL url = getResource("/vfs/test/dup.jar");
        VirtualFileURLConnection con = new VirtualFileURLConnection(url) {
            public String getContentType() {
                return null;
            }
        };

        Object content = con.getContent();
        Assert.assertTrue(content instanceof VirtualFile);
    }

    @Test
    public void testFixWFLY16322ContentTypeJsonShouldReturnFileInputStream() throws MalformedURLException, IOException {
        VirtualFile jar = getVirtualFile("/vfs/test/dup.jar");

        URL url = getResource("/vfs/test/dup.jar");
        VirtualFileURLConnection con = new VirtualFileURLConnection(url) {
            public String getContentType() {
                return "application/json";
            }
        };

        Object content = con.getContent();
        Assert.assertTrue(content instanceof FileInputStream);
    }
}


text:
package org.jbpm.casemgmt.impl.command;

import org.drools.core.ClassObjectFilter;
import org.drools.core.command.impl.RegistryContext;
import org.jbpm.casemgmt.api.CaseCommentNotFoundException;
import org.jbpm.casemgmt.api.model.instance.CaseFileInstance;
import org.jbpm.casemgmt.api.model.instance.CommentInstance;
import org.jbpm.casemgmt.impl.event.CaseEventSupport;
import org.jbpm.casemgmt.impl.model.instance.CaseFileInstanceImpl;
import org.jbpm.casemgmt.impl.model.instance.CommentInstanceImpl;
import org.kie.api.runtime.KieSession;
import org.kie.api.runtime.rule.FactHandle;
import org.kie.api.runtime.Context;

import java.util.Collection;

/**
 * Adds or removes comment to/from case
 */
public class CaseCommentCommand extends CaseCommand<Void> {

    private static final long serialVersionUID = 6345222909719335923L;

    private String author;
    private String comment;
    private boolean add;
    private boolean update;
    private boolean remove;

    private String commentId;

    private String updatedText;

    public CaseCommentCommand(String author, String comment) {
        this.author = author;
        this.comment = comment;
        this.add = true;
    }

    public CaseCommentCommand(String commentId) {
        this.commentId = commentId;
        this.remove = true;
    }

    public CaseCommentCommand(String commentId, String author, String updatedText) {
        this.commentId = commentId;
        this.author = author;
        this.updatedText = updatedText;
        this.update = true;

    }

    @Override
    public Void execute(Context context) {
        KieSession ksession = ((RegistryContext) context).lookup( KieSession.class );

        Collection<? extends Object> caseFiles = ksession.getObjects(new ClassObjectFilter(CaseFileInstance.class));
        if (caseFiles.size() != 1) {
            throw new IllegalStateException("Not able to find distinct case file - found case files " + caseFiles.size());
        }
        CaseFileInstance caseFile = (CaseFileInstance) caseFiles.iterator().next();
        FactHandle factHandle = ksession.getFactHandle(caseFile);

        CaseEventSupport caseEventSupport = getCaseEventSupport(context);

        if (add) {
            CommentInstance commentInstance = new CommentInstanceImpl(author, comment);
            caseEventSupport.fireBeforeCaseCommentAdded(caseFile.getCaseId(), commentInstance);
            ((CaseFileInstanceImpl)caseFile).addComment(commentInstance);
            caseEventSupport.fireAfterCaseCommentAdded(caseFile.getCaseId(), commentInstance);
        } else if (update) {
            CommentInstance toUpdate = ((CaseFileInstanceImpl)caseFile).getComments().stream()
                    .filter(c -> c.getId().equals(commentId))
                    .findFirst()
                    .orElseThrow(() -> new CaseCommentNotFoundException("Cannot find comment with id " + commentId));
            if (!this.author.equals(toUpdate.getAuthor())) {
                throw new IllegalStateException("Only original author can update comment");
            }
            caseEventSupport.fireBeforeCaseCommentUpdated(caseFile.getCaseId(), toUpdate);
            ((CommentInstanceImpl)toUpdate).setComment(updatedText);
            caseEventSupport.fireBeforeCaseCommentUpdated(caseFile.getCaseId(), toUpdate);
        } else if (remove) {
            CommentInstance toRemove = ((CaseFileInstanceImpl)caseFile).getComments().stream()
                    .filter(c -> c.getId().equals(commentId))
                    .findFirst()
                    .orElseThrow(() -> new CaseCommentNotFoundException("Cannot find comment with id " + commentId));
            caseEventSupport.fireBeforeCaseCommentRemoved(caseFile.getCaseId(), toRemove);
            ((CaseFileInstanceImpl)caseFile).removeComment(toRemove);
            caseEventSupport.fireBeforeCaseCommentRemoved(caseFile.getCaseId(), toRemove);
        }
        ksession.update(factHandle, caseFile);
        return null;
    }

}


text:
package com.coco.heart.redis;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.coco.heart.entry.PingEntry;

/**
 * @author wanglin/netboy
 * @version 创建时间:2016年3月31日 下午5:29:05
 * @func
 */
public interface RedisClientInterface {
    void start();

    void set(String key, String value);

    void set(String key, String value, TimeUnit timeUnit, Long expiredTime);

    Object get(String key);

    void del(String key);

    void expire(String key, TimeUnit timeUnit, long timeout);

    boolean exists(String key);

    void setBlackHostsMap(Map<String, PingEntry> blackHostMap);

    long increment(String key, Long value);

    void close();
}


text:
<?php

/**
 * PHPWord_Section_ListItem
 *
 * @category   PHPWord
 * @package    PHPWord_Section
 * @copyright  Copyright (c) 2011 PHPWord
 */
class PHPWord_Section_ListItem {

	/**
	 * ListItem Style
	 *
	 * @var PHPWord_Style_ListItem
	 */
	private $_style;

	/**
	 * Textrun
	 *
	 * @var PHPWord_Section_Text
	 */
	private $_textObject;

	/**
	 * ListItem Depth
	 *
	 * @var int
	 */
	private $_depth;

	/**
	 * Create a new ListItem
	 *
	 * @param string $text
	 * @param int $depth
	 * @param mixed $styleText
	 * @param mixed $styleList
	 */
	public function __construct($text, $depth = 0, $styleFont = null, $styleList = null, $styleParagraph = null) {
		$this->_style = new PHPWord_Style_ListItem();
		$this->_textObject = new PHPWord_Section_Text($text, $styleFont, $styleParagraph);
		$this->_depth = $depth;

		if(!is_null($styleList) && is_array($styleList)) {
			foreach($styleList as $key => $value) {
				if(substr($key, 0, 1) != '_') {
					$key = '_'.$key;
				}
				$this->_style->setStyleValue($key, $value);
			}
		}
	}

	/**
	 * Get ListItem style
	 */
	public function getStyle() {
		return $this->_style;
	}

	/**
	 * Get ListItem TextRun
	 */
	public function getTextObject() {
		return $this->_textObject;
	}

	/**
	 * Get ListItem depth
	 */
	public function getDepth() {
		return $this->_depth;
	}
}
?>


text:
import React          from 'react';
import ReactDOM       from 'react-dom';

import {Provider}     from 'react-redux';
import {createStore, applyMiddleware}  from 'redux';
import thunk          from 'redux-thunk';

import {Route, Router, browserHistory, IndexRoute} from 'react-router';

import './index.css';

import reducer        from './reducer';
import action         from './action';

import Application    from './components/Application';
import Callback       from './components/Callback';
import Favorites      from './components/Favorites';
import Home           from './components/Home';
import Popular        from './Popular';
import PhotoDetails   from './components/PhotoDetails';

const initialState =  {
  photos: {},
  popularItems: [],
  myLikes: {title: "My Likes", content: []}
};

const store = createStore(reducer, initialState, applyMiddleware(thunk));

store.dispatch(action.getInitialState());

const NotFound = () => {
  return
404!
;
}
ReactDOM.render(
  <Provider store={store}>
    <Router history={browserHistory}>
      <Route path="/" component={Application}>
        <IndexRoute component={Home}/>
        <Route path="/popular" component={Popular} />
        <Route path="/favorites" component={Favorites} />
        <Route path="/photo/:photoId" component={PhotoDetails}/>

      </Route>
      <Route path="callback" component={Callback} />
    </Router>
  </Provider>,
  document.getElementById('root')
);


text:
'use strict';

import * as App from './App.js';
import * as Ordbase from '../lib/Ordbase.js';
import * as TranslatePlugin from '../lib/Ordbase-translate-plugin.js';

import { force } from '../lib/Util.js';

import { View_SelectTranslation } from '../views/select-translation.js';

import { Component_Header }               from '../components/header.js';
import { Component_TranslationCard }      from '../components/card-translation.js';
import { Component_TranslationGenerator } from '../components/generator-translation.js';
import { Component_ContainerPicker }      from '../components/picker-container.js';

import { load_selectClient }    from './load-selectClient.js';

//
// @function load_selectTranslation
//  @note @todo
//
export function load_selectTranslation (clientKey) {

    //
    // -1. Set up Ordbase
    //
    TranslatePlugin.OnLanguageChange(() => { load_selectTranslation(clientKey); });
    TranslatePlugin.async_loadContainer('Ordbase', 'SelectTranslation');

    //
    // 0. Init components
    //
    const view             = new View_SelectTranslation;
    const header           = new Component_Header;
    const generator        = new Component_TranslationGenerator;
    const picker           = new Component_ContainerPicker;
    const cardPrototype    = new Component_TranslationCard;
    const languageKeyArray = new Array();

    //
    // 1. Async calls
    //
    // Populate languageArray
    async_language_getClientLanguageKeyArray({
        clientKey: clientKey,
        success: _languageKeyArray => {
            languageKeyArray.push.apply(languageKeyArray, _languageKeyArray);
        }
    });

    // Populate picker and set up default item
    async_container_getClientContainerKeyArray({
        clientKey: clientKey,
        success: containerKeyArray => {

            // Populate generator with translation cards
            async_translation_getGroupMetaArray({
                clientKey: clientKey,
                containerKey: containerKeyArray[0],
                success: groupMetaArray => {
                    groupMetaArray.forEach(groupMeta => {
                        let card = makeTranslationCard({ cardPrototype: cardPrototype,  groupMeta: groupMeta, languageKeyArray: languageKeyArray })
                        generator.addCard(card);
                    });
                }
            });

            containerKeyArray.forEach(containerKey => {

                picker.makeItem({
                    key: containerKey,
                    text: containerKey,

                    // On picker-item click, reload all translation cards
                    onclick: e => {

                        async_translation_getGroupMetaArray({
                            clientKey: clientKey,
                            containerKey: picker.getContainerKey(),
                            success: groupMetaArray => {
                                generator.clearItems();
                                groupMetaArray.forEach(groupMeta => {
                                    let card = makeTranslationCard({ cardPrototype: cardPrototype, groupMeta: groupMeta, languageKeyArray: languageKeyArray });
                                    generator.addCard(card);
                                })
                                generator.focus();
                            },
                        });

                        //
                        // @cleanup Repetitive 3 lines - JSolsvik 10.08.17
                        //
                        TranslatePlugin.translate('selectTranslation', text => header.setTheme({ textBig: text, selectable: true }));
                        header.setIcons({ button1: App.ICON_TRASH, button2: App.ICON_ARROW_LEFT, });
                        header.setEventHandlers({ button2_onclick: e => { load_selectClient() }});
                    },
                });
            });

            picker.setDefaultItem();
            picker.focus();
        }
    });

    //
    // 2. Hook up Translation card event handlers
    //
    cardPrototype.setEventHandlers({
        onopen: (card, e) => {

            // Generate fieldsets
            async_translation_getGroup({
                clientKey:     clientKey,
                containerKey:  picker.getContainerKey(),
                translationKey: card.getTranslationKey(),
                success: group => {

                    languageKeyArray.forEach(languageKey => {

                        let item = group.items.find(item => {
                            return item.languageKey === languageKey;
                        })

                        if (item !== undefined)
                            card.makeFieldset({languageKey: item.languageKey, text:  item.text, isComplete: item.isComplete})
                        else
                            card.makeFieldset({languageKey: languageKey, text:  'default*', isComplete: false })
                    });

                    card.display();
                }
            })

            TranslatePlugin.translate('editTranslation', text => header.setTheme({ textBig: text, editable: true }));
            card.open({ languageCount: languageKeyArray.length });
        },

        onclose: () => {
            TranslatePlugin.translate('selectTranslation', text => header.setTheme({ textBig: text, selectable: true }));
        },

        ondelete:(card, e) => {
            // Delete translation
            async_translation_delete({
                clientKey:      clientKey,
                containerKey:   picker.getContainerKey(),
                translationKey: card.getTranslationKey(),
                success: () => {
                    card.delete();
                    generator.getCardArray().forEach(_card => _card.setOpenable());

                    //
                    // @cleanup Repetitive 3 lines - JSolsvik 10.08.17
                    //
                    TranslatePlugin.translate('selectTranslation', text => header.setTheme({ textBig: text, selectable: true }));
                    header.setIcons({ button1: App.ICON_TRASH, button2: App.ICON_ARROW_LEFT, });
                    header.setEventHandlers({ button2_onclick: e => { load_selectClient() }});
                }
            });
        },
        onsubmit: (card, e) => {

            let translationArray = new Array();
            let formData = card.getFormData();

            formData.fieldsetArray.forEach(fieldset => {

                if (fieldset.text === 'default*')
                    fieldset.text = 'default';

                translationArray.push({
                    clientKey    : clientKey,
                    languageKey  : fieldset.languageKey,
                    containerKey : picker.getContainerKey(),
                    key          : formData.translationKey,
                    text         : fieldset.text,
                    isComplete   : fieldset.isComplete,
                });
            });

            async_translation_updateArray({ translationArray: translationArray,

                success: () => {
                    //
                    // @note Here I am updating ALL cards withing a container, even though
                    //       only 1 card has been updated. It would be better to JUST updated that card.
                    //       The reason I dont do that yet, was that it was faster to just copy paste existing code snippet. - JSolsvik 02.08.17
                    //
                    generator.clearItems();

                    async_translation_getGroupMetaArray({
                        clientKey: clientKey,
                        containerKey: picker.getContainerKey(),
                        success: groupMetaArray => {
                            groupMetaArray.forEach(groupMeta => {
                                let card = makeTranslationCard({ cardPrototype: cardPrototype,  groupMeta: groupMeta, languageKeyArray: languageKeyArray })
                                generator.addCard(card);
                            });
                            generator.focus();
                            generator.deactivateInput();
                        }
                    });
                    // Refresh the Ordbase container to get updated data
                    TranslatePlugin.async_loadContainer('Ordbase', 'SelectTranslation');
                    TranslatePlugin.translate('selectTranslation', text => header.setTheme({ textBig: text, selectable: true }));
                    header.setIcons({ button1: App.ICON_TRASH, button2: App.ICON_ARROW_LEFT, });
                    header.setEventHandlers({ button2_onclick: e => { load_selectClient() }});
                }
            });

        },
    });

    //
    // 2. Setup header
    //

    TranslatePlugin.translate('selectTranslation', text => header.setTheme({textSmall: 'Ordbase', textBig: text, selectable: true }));
    header.setIcons({ button1: App.ICON_TRASH, button2: App.ICON_ARROW_LEFT });
    header.setEventHandlers({

        // 2.1 Delete translation
        button1_onclick:  e => {

            let cardArray = generator.getCardArray();

            if (cardArray.length > 0) {
                if (!cardArray[0].isDeleteable()) {
                    cardArray.forEach(card => {
                        card.close();
                        card.setDeleteable();
                    });

                    TranslatePlugin.translate('deleteTranslation', text => header.setTheme({ textBig: text, deleteable: true }));
                    header.setIcons({ button1: App.ICON_NONE,  button2: App.ICON_TIMES, });
                    header.setEventHandlers({
                        button2_onclick: e => {
                            cardArray.forEach(card => card.setOpenable());

                            //
                            // @cleanup Repetitive 3 lines - JSolsvik 10.08.17
                            //
                            TranslatePlugin.translate('selectTranslation', text => header.setTheme({ textBig: text, selectable: true }));
                            header.setIcons({ button1: App.ICON_TRASH, button2: App.ICON_ARROW_LEFT, });
                            header.setEventHandlers({ button2_onclick: e => { load_selectClient() }});
                            generator.focus();
                        }
                    });
                    generator.focus();
                }
            } else {
                TranslatePlugin.translate('errorNothingToDelete', text => App.flashError(text));
                picker.focus();
            }
        },
        // 2.2 Back to select client view
        button2_onclick:  e => load_selectClient(),
    });

    //
    // 3. Setup Component_TranslationGenerator
    //
    generator.OnGenerate( e => {

        let translationArray = new Array();

        languageKeyArray.forEach(languageKey => {

            translationArray.push({
                clientKey : clientKey,
                languageKey : languageKey,
                containerKey : picker.getContainerKey(),
                key : generator.getInputValue(),
                text : 'default',
                isComplete : false,
            });
        });

        async_translation_createArray({
            translationArray: translationArray,
            success: (groupMeta) => {
                let card = makeTranslationCard({cardPrototype: cardPrototype, groupMeta: groupMeta, languageKeyArray: languageKeyArray})
                generator.addCard(card);
            }
        });
    });

    //
    // 5. Insert components into view, and add view to DOM
    //
    view.setTranslationGenerator(generator);
    view.setContainerPicker(picker);
    App.setHeader(header);
    App.setView(view);
}

//
// @function makeTranslationCard
//
function makeTranslationCard({ cardPrototype = force('cardPrototype'),
                               groupMeta = force('groupMeta'),
                               languageKeyArray = force('languageKeyArray'), }) {

    if (languageKeyArray.length === 0) {
        App.flashError('No languages registered yet....');
        throw Error('panic: no languages registered yet...');
    }

    let card = new Component_TranslationCard;

    card.setTranslationKey(groupMeta.key);
    TranslatePlugin.translate('updateTranslation', text =>  card.setSubmitButtontext(text));
    TranslatePlugin.translate('checkboxText',      text => card.setCheckboxText(text));

    languageKeyArray.forEach(languageKey => {
        let item = groupMeta.items.find(item => item.languageKey == languageKey);

        if (item !== undefined) {
            card.makeLanguagekeyComplete(item.languageKey, item.isComplete);
        }
        else {
            card.makeLanguagekeyComplete(languageKey, false);
        }
    });

    card.setEventHandlers(cardPrototype.getEventHandlers());
    return card;
}

//
// @function async_language_getClientLanguageKeyArray
//
function async_language_getClientLanguageKeyArray({ clientKey = force('clientKey'),
                                                    success   = force('success') }){

    Route.language_getClientLanguageArray({clientKey: clientKey}).then(clientLanguageArray => {
        success(clientLanguageArray.map(clientLanguage => { return  clientLanguage.languageKey; }));
    })
    .catch(err => console.error(err));
}

//
// @function async_translation_getGroup
//
function async_translation_getGroup({ success       = force('success'),
                                         clientKey     = force('clientKey'),
                                         containerKey  = force('containerKey'),
                                         translationKey = force('translationKey'), }) {

    Route.translation_getGroup({clientKey: clientKey,
                                containerKey: containerKey,
                                translationKey: translationKey}).then((groupArray) => {
      if (groupArray.length > 0) {
            let group = groupArray[0];
            success(group);
      } else {
          App.flashError('Pick a container to enable editing!');
      }

    }).catch(err => console.error(err));
}

//
// @function async_container_getClientContainerKeyArray
//
function async_container_getClientContainerKeyArray ({  success  = force('success'),
                                                     clientKey   = force('clientKey') }) {

    Route.container_getClientContainerArray({clientKey: clientKey}).then(clientContainerArray => {
        if (clientContainerArray.length > 0)
            success(clientContainerArray.map(clientContainer => { return clientContainer.containerKey }));
        else {
            App.flashError('There are no containers in this client...');
        }
    })
    .catch(err => console.error(err));
}

//
// @function async_translation_getGroupMetaArray
//
function async_translation_getGroupMetaArray({ success      = force('success'),
                                               clientKey    = force('clientKey'),
                                               containerKey = force('containerKey') }) {

    Route.translation_getGroupMeta({clientKey:    clientKey,
                                    containerKey: containerKey}).then(groupMetaArray => {
        success(groupMetaArray);
    })
    .catch(err => console.error(err));
}

//
// @function async_translation_getGroupMeta
//
function async_translation_getGroupMeta({ success      = force('success'),
                                             clientKey   = force('clientKey'),
                                             containerKey = force('containerKey'),
                                             translationKey = force('translationKey')}) {

    Route.translation_getGroupMeta(arguments[0]).then(groupMetaArray => {
        let groupMeta = groupMetaArray[0];
        success(groupMeta)
    })
    .catch(err => console.error(err));
}

//
// @function async_translation_createArray
//
function async_translation_createArray({ success         = force('success'),
                                            translationArray = force('translationArray')}) {

    Route.translation_createArray({ translationArray: translationArray }).then(res => {

        if(res.status != App.HTTP_CREATED) {
            App.flashError(`${res.status}: Was not able to create new translations...`);
            throw new Error('translation_createArray(): ', res.status);
        }

        return Route.translation_getGroupMeta({ clientKey: translationArray[0].clientKey,
                                                containerKey: translationArray[0].containerKey,
                                                translationKey: translationArray[0].key });
    })
    .then(groupMetaArray => {
        let groupMeta = groupMetaArray[0];
        success(groupMeta);
    })
    .catch(err => console.error(err));
}

//
// @function async_translation_delete
//

function    async_translation_updateArray({ success= force('success'), translationArray = force('translationArray') }) {

    Route.translation_updateArray({ translationArray: translationArray,
                                    clientKey: translationArray[0].clientKey,
                                    containerKey: translationArray[0].containerKey,
                                    translationKey: translationArray[0].key })
    .then(res => {
        console.log('translation_updateArray():', res.status);

        if (App.HTTP_UPDATED) {
            success();
        } else {
            App.flashError('Code ${res.status}: Something went wrong while updating the translations..');
        }
    })
    .catch(err => console.error(err));
}

//
// @function async_translation_delete
//
function async_translation_delete({  success        = force('success'),
                                        clientKey      = force('clientKey'),
                                        containerKey   = force('containerKey'),
                                        translationKey = force('translationKey'), }) {

    Route.translation_deleteGroup({clientKey: clientKey,
                                   containerKey: containerKey,
                                   translationKey: translationKey})
    .then(res => {

        console.log('translation_deleteGroup():', res.status);

        if (res.status == App.HTTP_OK) {
            success();
        }
        else {
            App.flashError(`${res.status}: Was not able to delete card...`);
        }
    }).catch(err => console.error(err));
}


text:
import React from 'react';

interface IErrorBoundaryProps {
  readonly children: JSX.Element | JSX.Element[];
}

interface IErrorBoundaryState {
  readonly error: any;
  readonly errorInfo: any;
}

class ErrorBoundary extends React.Component<IErrorBoundaryProps, IErrorBoundaryState> {
  readonly state: IErrorBoundaryState = { error: undefined, errorInfo: undefined };

  componentDidCatch(error:any , errorInfo: any) {
    this.setState({
      error,
      errorInfo,
    });
  }

  render() {
    const { error, errorInfo } = this.state;
    if (errorInfo) {
      const errorDetails =
        process.env.NODE_ENV === 'development' ? (

            {error && error.toString()}

            {errorInfo.componentStack}

        ) : undefined;
      return (

An unexpected error has occurred.

          {errorDetails}

      );
    }
    return this.props.children;
  }
}

export default ErrorBoundary;


text: import "empty-lines";


text:
import ElementTypes = require("./elementTypes");
import Traversal = require("./traversal");
import Types = require("./types");
import Util = require("./util");

class Position {

    private _node: Node;
    public offset: number;
    public origOffset: number;
    public posId: number;
    public tracking: number;
    public targetX: any;

    constructor(node: Node, offset: number) {
        if (node == document.documentElement)
            throw new Error("node is root element");
        this.node = node;
        this.offset = offset;
        this.origOffset = offset;
        this.tracking = 0;
        this.posId = null;
        this.targetX = null;
    }

    get node(): Node {
        return this._node;
    }

    set node(newNode: Node) {
        if (this.tracking > 0)
            this.actuallyStopTracking();

        this._node = newNode;

        if (this.tracking > 0)
            this.actuallyStartTracking();
    }

    private actuallyStartTracking(): void {
        let node = this.node;
        if (node._trackedPositions == null)
            node._trackedPositions = new Array<Position>();
        node._trackedPositions.push(this);
    }

    private actuallyStopTracking(): void {
        let trackedPositions = this.node._trackedPositions;
        if (trackedPositions == null)
            throw new Error("actuallyStopTracking: no registered positions for this node "+
                            "("+this.node.nodeName+")");
        for (let i = 0; i < trackedPositions.length; i++) {
            if (trackedPositions[i] == this) {
                trackedPositions.splice(i,1);
                return;
            }
        }
        throw new Error("removeTrackedPosition: position is not registered ("+
                        trackedPositions.length+" others)");
    }

    public track() {
        if (this.tracking == 0)
            this.actuallyStartTracking();
        this.tracking++;
    }

    public untrack() {
        this.tracking--;
        if (this.tracking == 0)
            this.actuallyStopTracking();
    }

    public toString(): string {
        let result: string;
        if (this.node instanceof Text) {
            let extra = "";
            if (this.offset > this.node.nodeValue.length) {
                for (let i = this.node.nodeValue.length; i < this.offset; i++)
                    extra += "!";
            }
            let id = "";
            result = id+JSON.stringify(this.node.nodeValue.slice(0,this.offset)+extra+"|"+
                                       this.node.nodeValue.slice(this.offset));
        }
        else {
            result = "("+Util.nodeString(this.node)+","+this.offset+")";
        }
        if (this.posId != null)
            result = "["+this.posId+"]"+result;
        return result;
    }

    private static positionSpecial(pos: Position, forwards: boolean, backwards: boolean): Position {
        let node = pos.node;
        let offset = pos.offset;

        let prev = node.childNodes[offset-1];
        let next = node.childNodes[offset];

        // Moving left from the start of a caption - go to the end of the table
        if ((node._type == ElementTypes.HTML_CAPTION) && backwards && (prev == null))
            return new Position(node.parentNode,node.parentNode.childNodes.length);

        // Moving right from the end of a caption - go after the table
        if ((node._type == ElementTypes.HTML_CAPTION) && forwards && (next == null))
            return new Position(node.parentNode.parentNode,Traversal.nodeOffset(node.parentNode)+1);

        // Moving left from just after a table - go to the end of the caption (if there is one)
        if ((prev != null) && (prev._type == ElementTypes.HTML_TABLE) && backwards) {
            let firstChild = Traversal.firstChildElement(prev);
            if ((firstChild._type == ElementTypes.HTML_CAPTION))
                return new Position(firstChild,firstChild.childNodes.length);
        }

        // Moving right from just before a table - bypass the the caption (if there is one)
        if ((next != null) && (next._type == ElementTypes.HTML_TABLE) && forwards) {
            let firstChild = Traversal.firstChildElement(next);
            if (firstChild._type == ElementTypes.HTML_CAPTION)
                return new Position(next,Traversal.nodeOffset(firstChild)+1);
        }

        // Moving right from the end of a table - go to the start of the caption (if there is one)
        if ((node._type == ElementTypes.HTML_TABLE) && (next == null) && forwards) {
            let firstChild = Traversal.firstChildElement(node);
            if (firstChild._type == ElementTypes.HTML_CAPTION)
                return new Position(firstChild,0);
        }

        // Moving left just after a caption node - skip the caption
        if ((prev != null) && (prev._type == ElementTypes.HTML_CAPTION) && backwards)
            return new Position(node,offset-1);

        return null;
    }

    public assertValid(description?: string): void {
        let pos = this;
        if (description == null)
            description = "Position";

        for (let ancestor = pos.node; ancestor != document.body; ancestor = ancestor.parentNode) {
            if (ancestor == null)
                throw new Error(description+" node "+pos.node.nodeName+" is not in tree");
        }

        let max: number;
        if (pos.node instanceof Element)
            max = pos.node.childNodes.length;
        else if (pos.node instanceof Text)
            max = pos.node.nodeValue.length;
        else
            throw new Error(description+" has invalid node type "+pos.node.nodeType);

        if ((pos.offset < 0) || (pos.offset > max)) {
            throw new Error(description+" (in "+pos.node.nodeName+") has invalid offset "+
                            pos.offset+" (max allowed is "+max+")");
        }
    }

    public prev(): Position {
        let pos = this;
        if (pos.node instanceof Element) {
            let r = Position.positionSpecial(pos,false,true);
            if (r != null)
                return r;
            if (pos.offset == 0) {
                return upAndBack(pos);
            }
            else {
                let child = pos.node.childNodes[pos.offset-1];
                return new Position(child,Traversal.maxChildOffset(child));
            }
        }
        else if (pos.node instanceof Text) {
            if (pos.offset > 0)
                return new Position(pos.node,pos.offset-1);
            else
                return upAndBack(pos);
        }
        else {
            return null;
        }

        function upAndBack(pos: Position): Position {
            if (pos.node == pos.node.ownerDocument.body)
                return null;
            else
                return new Position(pos.node.parentNode,Traversal.nodeOffset(pos.node));
        }
    }

    public next(): Position {
        let pos = this;
        if (pos.node instanceof Element) {
            let r = Position.positionSpecial(pos,true,false);
            if (r != null)
                return r;
            if (pos.offset == pos.node.childNodes.length)
                return upAndForwards(pos);
            else
                return new Position(pos.node.childNodes[pos.offset],0);
        }
        else if (pos.node instanceof Text) {
            if (pos.offset < pos.node.nodeValue.length)
                return new Position(pos.node,pos.offset+1);
            else
                return upAndForwards(pos);
        }
        else {
            return null;
        }

        function upAndForwards(pos: Position): Position {
            if (pos.node == pos.node.ownerDocument.body)
                return null;
            else
                return new Position(pos.node.parentNode,Traversal.nodeOffset(pos.node)+1);
        }
    }

    public static trackWhileExecuting<T>(positions: Position[], fun: () => T): T {
        for (let i = 0; i < positions.length; i++)
            positions[i].track();
        try {
            return fun();
        }
        finally {
            for (let i = 0; i < positions.length; i++)
                positions[i].untrack();
        }
    }

    public closestActualNode(preferElement?: boolean): Node {
        let pos = this;
        let node = pos.node;
        let offset = pos.offset;
        if (!(node instanceof Element) || (node.firstChild == null))
            return node;
        else if (offset == 0)
            return node.firstChild;
        else if (offset >= node.childNodes.length)
            return node.lastChild;

        let prev = node.childNodes[offset-1];
        let next = node.childNodes[offset];
        if (preferElement &&
            !(next instanceof Element) &&
            (prev instanceof Element)) {
            return prev;
        }
        else {
            return next;
        }
    }

    public static okForInsertion(pos: Position): boolean {
        return Position.okForMovement(pos,true);
    }

    private static nodeCausesLineBreak(node: Node): boolean {
        return ((node._type == ElementTypes.HTML_BR) || !Types.isInlineNode(node));
    }

    private static spacesUntilNextContent(node: Node): number {
        let spaces = 0;
        while (true) {
            if (node.firstChild) {
                node = node.firstChild;
            }
            else if (node.nextSibling) {
                node = node.nextSibling;
            }
            else {
                while ((node.parentNode != null) && (node.parentNode.nextSibling == null)) {
                    node = node.parentNode;
                    if (Position.nodeCausesLineBreak(node))
                        return null;
                }
                if (node.parentNode == null)
                    node = null;
                else
                    node = node.parentNode.nextSibling;
            }

            if ((node == null) || Position.nodeCausesLineBreak(node))
                return null;
            if (Types.isOpaqueNode(node))
                return spaces;
            if (node instanceof Text) {
                if (Traversal.isWhitespaceTextNode(node)) {
                    spaces += node.nodeValue.length;
                }
                else {
                    let matches = node.nodeValue.match(/^\s+/);
                    if (matches == null)
                        return spaces;
                    spaces += matches[0].length;
                    return spaces;
                }
            }
        }
    }

    public static okForMovement(pos: Position, insertion?: boolean): boolean {
        let node = pos.node;
        let offset = pos.offset;
        let type = node._type;

        if (Types.isOpaqueNode(node))
            return false;

        for (let ancestor = node; ancestor != null; ancestor = ancestor.parentNode) {
            let ancestorType = node._type;
            if (ancestorType == ElementTypes.HTML_FIGCAPTION)
                break;
            else if (ancestorType == ElementTypes.HTML_FIGURE)
                return false;
        }

        if (node instanceof Text) {
            let value = node.nodeValue;

            // If there are multiple adjacent text nodes, consider them as one (adjusting the
            // offset appropriately)

            let firstNode: Node = node;
            let lastNode: Node = node;

            while ((firstNode.previousSibling != null) &&
                   (firstNode.previousSibling instanceof Text)) {
                firstNode = firstNode.previousSibling;
                value = firstNode.nodeValue + value;
                offset += firstNode.nodeValue.length;
            }

            while ((lastNode.nextSibling != null) &&
                   (lastNode.nextSibling instanceof Text)) {
                lastNode = lastNode.nextSibling;
                value += lastNode.nodeValue;
            }

            let prevChar = value.charAt(offset-1);
            let nextChar = value.charAt(offset);
            let havePrevChar = ((prevChar != null) && !Util.isWhitespaceString(prevChar));
            let haveNextChar = ((nextChar != null) && !Util.isWhitespaceString(nextChar));
            if (havePrevChar && haveNextChar) {
                let prevCode = value.charCodeAt(offset-1);
                let nextCode = value.charCodeAt(offset);
                if ((prevCode >= 0xD800) && (prevCode <= 0xDBFF) &&
                    (nextCode >= 0xDC00) && (nextCode <= 0xDFFF)) {
                    return false; // In middle of surrogate pair
                }
                return true;
            }

            if (Util.isWhitespaceString(value)) {
                if (offset == 0) {
                    if ((node == firstNode) &&
                        (firstNode.previousSibling == null) && (lastNode.nextSibling == null))
                        return true;
                    if ((node.nextSibling != null) && (node.nextSibling._type == ElementTypes.HTML_BR))
                        return true;
                    if ((node.firstChild == null) &&
                        (node.previousSibling == null) &&
                        (node.nextSibling == null)) {
                        return true;
                    }
                    if (insertion && (node.previousSibling != null) &&
                        Types.isInlineNode(node.previousSibling) &&
                        !Types.isOpaqueNode(node.previousSibling) &&
                        (node.previousSibling._type != ElementTypes.HTML_BR))
                        return true;
                }
                return false;
            }

            if (insertion)
                return true;

            let precedingText = value.substring(0,offset);
            if (Util.isWhitespaceString(precedingText)) {
                return (haveNextChar &&
                        ((node.previousSibling == null) ||
                         (node.previousSibling._type == ElementTypes.HTML_BR) ||
                         Types.isNoteNode(node.previousSibling) ||
                         (Types.isParagraphNode(node.previousSibling)) ||
                         (Traversal.getNodeText(node.previousSibling).match(/\s$/) != null) ||
                         Types.isItemNumber(node.previousSibling) ||
                         ((precedingText.length > 0))));
            }

            let followingText = value.substring(offset);
            if (Util.isWhitespaceString(followingText)) {
                return (havePrevChar &&
                        ((node.nextSibling == null) ||
                         Types.isNoteNode(node.nextSibling) ||
                         (followingText.length > 0) ||
                         (Position.spacesUntilNextContent(node) != 0)));
            }

            return (havePrevChar || haveNextChar);
        }
        else if (node instanceof Element) {
            if (node.firstChild == null) {
                switch (type) {
                case ElementTypes.HTML_LI:
                case ElementTypes.HTML_TH:
                case ElementTypes.HTML_TD:
                    return true;
                default:
                    if (Types.PARAGRAPH_ELEMENTS[type])
                        return true;
                    else
                        break;
                }
            }

            let prevNode = node.childNodes[offset-1];
            let nextNode = node.childNodes[offset];
            let prevType = (prevNode != null) ? prevNode._type : 0;
            let nextType = (nextNode != null) ? nextNode._type : 0;

            let prevIsNote = (prevNode != null) && Types.isNoteNode(prevNode);
            let nextIsNote = (nextNode != null) && Types.isNoteNode(nextNode);
            if (((nextNode == null) || !Types.nodeHasContent(nextNode)) && prevIsNote)
                return true;
            if (((prevNode == null) || !Types.nodeHasContent(prevNode)) && nextIsNote)
                return true;
            if (prevIsNote && nextIsNote)
                return true;

            if ((prevNode == null) && (nextNode == null) &&
                (Types.CONTAINERS_ALLOWING_CHILDREN[type] ||
                (Types.isInlineNode(node) && !Types.isOpaqueNode(node) && (type != ElementTypes.HTML_BR))))
                return true;

            if ((prevNode != null) && Types.isSpecialBlockNode(prevNode))
                return true;
            if ((nextNode != null) && Types.isSpecialBlockNode(nextNode))
                return true;

            if ((nextNode != null) && Types.isItemNumber(nextNode))
                return false;
            if ((prevNode != null) && Types.isItemNumber(prevNode))
                return ((nextNode == null) || Traversal.isWhitespaceTextNode(nextNode));

            if ((nextNode != null) && (nextType == ElementTypes.HTML_BR))
                return ((prevType == 0) || (prevType != ElementTypes.HTML_TEXT));

            if ((prevNode != null) && (Types.isOpaqueNode(prevNode) || (prevType == ElementTypes.HTML_TABLE))) {

                switch (nextType) {
                case 0:
                case ElementTypes.HTML_TEXT:
                case ElementTypes.HTML_TABLE:
                    return true;
                default:
                    return Types.isOpaqueNode(nextNode);
                }
            }
            if ((nextNode != null) && (Types.isOpaqueNode(nextNode) || (nextType == ElementTypes.HTML_TABLE))) {
                switch (prevType) {
                case 0:
                case ElementTypes.HTML_TEXT:
                case ElementTypes.HTML_TABLE:
                    return true;
                default:
                    return Types.isOpaqueNode(prevNode);
                }
            }
        }

        return false;
    }

    public prevMatch(fun: (pos: Position) => boolean): Position {
        let pos: Position = this;
        do {
            pos = pos.prev();
        } while ((pos != null) && !fun(pos));
        return pos;
    }

    public nextMatch(fun: (pos: Position) => boolean): Position {
        let pos: Position = this;
        do {
            pos = pos.next();
        } while ((pos != null) && !fun(pos));
        return pos;
    }

    private static findEquivalentValidPosition(pos: Position, fun: (pos: Position) => boolean): Position {
        let node = pos.node;
        let offset = pos.offset;
        if (node instanceof Element) {
            let before = node.childNodes[offset-1];
            let after = node.childNodes[offset];
            if ((before != null) && (before instanceof Text)) {
                let candidate = new Position(before,before.nodeValue.length);
                if (fun(candidate))
                    return candidate;
            }
            if ((after != null) && (after instanceof Text)) {
                let candidate = new Position(after,0);
                if (fun(candidate))
                    return candidate;
            }
        }

        if ((pos.node instanceof Text) &&
            Util.isWhitespaceString(pos.node.nodeValue.slice(pos.offset))) {
            let str = pos.node.nodeValue;
            let whitespace = str.match(/\s+$/);
            if (whitespace) {
                let adjusted = new Position(pos.node,
                                            str.length - whitespace[0].length + 1);
                return adjusted;
            }
        }
        return pos;
    }

    public static closestMatchForwards(pos: Position, fun: (pos: Position) => boolean): Position {
        if (pos == null)
            return null;

        if (!fun(pos))
            pos = Position.findEquivalentValidPosition(pos,fun);

        if (fun(pos))
            return pos;

        let next = pos.nextMatch(fun);
        if (next != null)
            return next;

        let prev = pos.prevMatch(fun);
        if (prev != null)
            return prev;

        return new Position(document.body,document.body.childNodes.length);
    }

    public static closestMatchBackwards(pos: Position, fun: (pos: Position) => boolean): Position {
        if (pos == null)
            return null;

        if (!fun(pos))
            pos = Position.findEquivalentValidPosition(pos,fun);

        if (fun(pos))
            return pos;

        let prev = pos.prevMatch(fun);
        if (prev != null)
            return prev;

        let next = pos.nextMatch(fun);
        if (next != null)
            return next;

        return new Position(document.body,0);
    }

    public noteAncestor(): HTMLElement {
        let pos = this;
        let node = pos.closestActualNode();
        for (; node != null; node = node.parentNode) {
            if ((node instanceof HTMLElement) && Types.isNoteNode(node))
                return node;
        }
        return null;
    }

    public captionAncestor(): Element {
        let pos = this;
        let node = pos.closestActualNode();
        for (; node != null; node = node.parentNode) {
            if ((node instanceof Element) &&
                ((node._type == ElementTypes.HTML_FIGCAPTION) || (node._type == ElementTypes.HTML_CAPTION)))
                return node;
        }
        return null;
    }

    public figureOrTableAncestor(): Element {
        let pos = this;
        let node = pos.closestActualNode();
        for (; node != null; node = node.parentNode) {
            if ((node instanceof Element) &&
                ((node._type == ElementTypes.HTML_FIGURE) || (node._type == ElementTypes.HTML_TABLE)))
                return node;
        }
        return null;
    }

    public static equal(a: Position, b: Position): boolean {
        if ((a == null) && (b == null))
            return true;
        if ((a != null) && (b != null) &&
            (a.node == b.node) && (a.offset == b.offset))
            return true;
        return false;
    }

    public preferTextPosition(): Position {
        let pos = this;
        let node = pos.node;
        let offset = pos.offset;
        if (node instanceof Element) {
            let before = node.childNodes[offset-1];
            let after = node.childNodes[offset];
            if ((before != null) && (before instanceof Text))
                return new Position(before,before.nodeValue.length);
            if ((after != null) && (after instanceof Text))
                return new Position(after,0);
        }
        return pos;
    }

    public preferElementPosition(): Position {
        let pos = this;
        if (pos.node instanceof Text) {
            if (pos.node.parentNode == null)
                throw new Error("Position "+pos+" has no parent node");
            if (pos.offset == 0)
                return new Position(pos.node.parentNode,Traversal.nodeOffset(pos.node));
            if (pos.offset == pos.node.nodeValue.length)
                return new Position(pos.node.parentNode,Traversal.nodeOffset(pos.node)+1);
        }
        return pos;
    }

    public compare(second: Position): number {
        let first = this;
        if ((first.node == second.node) && (first.offset == second.offset))
            return 0;

        let doc = first.node.ownerDocument;
        if ((first.node.parentNode == null) && (first.node != doc.documentElement))
            throw new Error("First node has been removed from document");
        if ((second.node.parentNode == null) && (second.node != doc.documentElement))
            throw new Error("Second node has been removed from document");

        if (first.node == second.node)
            return first.offset - second.offset;

        let firstParent: Node = null;
        let firstChild: Node = null;
        let secondParent: Node = null;
        let secondChild: Node = null;

        if (second.node instanceof Element) {
            secondParent = second.node;
            secondChild = second.node.childNodes[second.offset];
        }
        else {
            secondParent = second.node.parentNode;
            secondChild = second.node;
        }

        if (first.node instanceof Element) {
            firstParent = first.node;
            firstChild = first.node.childNodes[first.offset];
        }
        else {
            firstParent = first.node.parentNode;
            firstChild = first.node;
            if (firstChild == secondChild)
                return 1;
        }

        let firstC = firstChild;
        let firstP = firstParent;
        while (firstP != null) {

            let secondC = secondChild;
            let secondP = secondParent;
            while (secondP != null) {

                if (firstP == secondC)
                    return 1;

                if (firstP == secondP) {
                    // if secondC is last child, firstC must be secondC or come before it
                    if (secondC == null)
                        return -1;
                    for (let n = firstC; n != null; n = n.nextSibling) {
                        if (n == secondC)
                            return -1;
                    }
                    return 1;
                }

                secondC = secondP;
                secondP = secondP.parentNode;
            }

            firstC = firstP;
            firstP = firstP.parentNode;
        }
        throw new Error("Could not find common ancestor");
    }

}

export = Position;


text:
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010 FUJIWARA, Yusuke
//
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//
//        http://www.apache.org/licenses/LICENSE-2.0
//
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
//
#endregion -- License Terms --

using System;
using NUnit.Framework;
using System.IO;

namespace MsgPack.Rpc.Server.Dispatch.SvcFileInterop
{
	[TestFixture()]
	public class InitialStateTest
	{
		[Test()]
		public void TestParse_LessorThanImmeditely_TransitToStartTagFoundState()
		{
			var target = new InitialState();
			var next = target.Parse( new StringReader( "<" ) );
			Assert.That( next, Is.TypeOf<StartTagFoundState>() );
		}

		[Test()]
		public void TestParse_TrailingWhitespace_ProceedsByOneAndFinallyTransitToStartTagFoundState()
		{
			SvcDirectiveParserState target = new InitialState();
			var reader = new StringReader( " \u3000\t<" );
			for ( int i = 0; i < 4; i++ )
			{
				Assert.That( target.IsFinished, Is.False );
				Assert.That( target, Is.TypeOf<InitialState>() );
				target = target.Parse( reader );
			}

			Assert.That( target, Is.TypeOf<StartTagFoundState>() );
		}

		[Test()]
		[ExpectedException( typeof( FormatException ) )]
		public void TestParse_NonWhitespace()
		{
			var target = new InitialState();
			var next = target.Parse( new StringReader( "a" ) );
		}
	}
}


text:
FactoryGirl.define do
  factory :contact do
    address_book
    first_name { Faker::Name.first_name }
    last_name { Faker::Name.last_name }
    display_name { "#{first_name} #{last_name}" }
    email_address { Faker::Internet.email }
  end
end


text:
-- DROP TABLE action;

CREATE TABLE action
(
  id bigint NOT NULL,
  type_id integer NOT NULL, -- Type of action: Move,Alter,Take,Give. Corresponding integer matching is being handled from application. ...
  task_id bigint NOT NULL, -- Link to task table. To which task this action is attached
  sequence integer NOT NULL, -- The sequence number representing the order in whic the actions are in relation to each other in a specific task.
  object_id bigint NOT NULL, -- Link to objects table. The target object of the action.
  location_object_id bigint, -- Link to objects table. The destination or alternate object related to the action.
  instrument_id bigint DEFAULT 0, -- Link to objects table. Optional instrument object related to some action types.
  manner_id bigint DEFAULT 0, -- Link to manners table. Describes the manne in which to object is being applied to location
  cue_id bigint DEFAULT 0, -- Link to cues table. Defines whether there is a cue attached to specific action
  duration bigint, -- duration in milliseconds
  CONSTRAINT actions_pk PRIMARY KEY (id)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE action
  OWNER TO test;
COMMENT ON TABLE action
  IS 'All actions attached to tasks being attaced to worklfow process models';
COMMENT ON COLUMN action.type_id IS 'Type of action: Move,Alter,Take,Give. Corresponding integer matching is being handled from application.

1 - Move
2 - Take
3 - Alter
4 - Give';
COMMENT ON COLUMN action.task_id IS 'Link to task table. To which task this action is attached';
COMMENT ON COLUMN action.sequence IS 'The sequence number representing the order in whic the actions are in relation to each other in a specific task. ';
COMMENT ON COLUMN action.object_id IS 'Link to objects table. The target object of the action. ';
COMMENT ON COLUMN action.location_object_id IS 'Link to objects table. The destination or alternate object related to the action. ';
COMMENT ON COLUMN action.instrument_id IS 'Link to objects table. Optional instrument object related to some action types. ';
COMMENT ON COLUMN action.manner_id IS 'Link to manners table. Describes the manne in which to object is being applied to location';
COMMENT ON COLUMN action.cue_id IS 'Link to cues table. Defines whether there is a cue attached to specific action';
COMMENT ON COLUMN action.duration IS 'duration in milliseconds';


text:
namespace csapex
{
class CSAPEX_CORE_EXPORT Settings
{
public:
    static const std::string settings_file;
    static const std::string config_extension;
    static const std::string template_extension;
    static const std::string message_extension;
    static const std::string message_extension_compressed;
    static const std::string message_extension_binary;
    static const std::string default_config;
    static const std::string config_selector;

    static const std::string namespace_separator;

    static std::string defaultConfigFile();
    static std::string defaultConfigPath();

public:
    Settings();
    virtual ~Settings();

    bool isDirty() const;

    bool isQuiet() const;
    void setQuiet(bool quiet);

    virtual bool knows(const std::string& name) const = 0;

    virtual void add(csapex::param::Parameter::Ptr p, bool persistent) = 0;
    virtual csapex::param::ParameterPtr get(const std::string& name) const = 0;
    virtual csapex::param::ParameterPtr getNoThrow(const std::string& name) const = 0;

    void addTemporary(csapex::param::Parameter::Ptr p);
    void addPersistent(csapex::param::Parameter::Ptr p);

    virtual void savePersistent() = 0;
    virtual void loadPersistent() = 0;

    virtual void saveTemporary(YAML::Node& node) = 0;
    virtual void loadTemporary(YAML::Node& node) = 0;

    template <typename T>
    T get(const std::string& name) const
    {
        auto param = getNoThrow(name);
        if (!param) {
            throw std::runtime_error(std::string("settings.get: unknown parameter '") + name + "'");
        }

        return param->as<T>();
    }

    template <typename T>
    T get(const std::string& name, const T default_value) const
    {
        auto param = getNoThrow(name);
        if (!param) {
            return default_value;
        }

        return param->as<T>();
    }

    template <typename T>
    T getPersistent(const std::string& name, T def)
    {
        auto param = getNoThrow(name);
        if (!param) {
            param::ValueParameter::Ptr p(new param::ValueParameter(name, csapex::param::ParameterDescription()));
            p->set(def);
            addPersistent(p);
            return def;
        }

        return param->as<T>();
    }

    template <typename T>
    T getTemporary(const std::string& name, T def)
    {
        auto param = getNoThrow(name);
        if (!param) {
            param::ValueParameter::Ptr p(new param::ValueParameter(name, csapex::param::ParameterDescription()));
            p->set(def);
            addTemporary(p);
            return def;
        }

        return param->as<T>();
    }

    template <typename T>
    void set(const std::string& name, const T& val)
    {
        auto param = getNoThrow(name);
        if (!param) {
            param::ValueParameter::Ptr p(new param::ValueParameter(name, csapex::param::ParameterDescription()));
            p->set(val);
            addTemporary(p);
            param = p;

        } else {
            param->set<T>(val);
        }

        settingsChanged(param.get());
    }

    template <typename T>
    void setPersistent(const std::string& name, const T& val)
    {
        auto param = getNoThrow(name);
        if (!param) {
            param::ValueParameter::Ptr p(new param::ValueParameter(name, csapex::param::ParameterDescription()));
            p->set(val);
            addPersistent(p);
            param = p;

        } else {
            param->set<T>(val);
        }

        settingsChanged(param.get());
    }

protected:
    void setNotDirty();
    void settingsChanged(const param::Parameter* parameter);

    virtual void triggerSettingsChanged();

public:
    csapex::slim_signal::Signal<void(const std::string&)> setting_changed;
    csapex::slim_signal::Signal<void()> settings_changed;

protected:
    bool dirty_;
    bool quiet_;

    std::vector<std::string> changes_;
};

}  // namespace csapex

#endif  // SETTINGS_H


text:
local assertEq=test.assertEq
local unpack = unpack or table.unpack

test.open('wordsnl.txt')
local init_data = buffer:get_text()
local keys = {'j', 'l', 'v', 'l', 'l', 'l', 'x'}

test.key(unpack(keys))
local fini_data = buffer:get_text()

assertEq(test.run_in_vim(init_data, keys), fini_data)


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>whoami — prints the name of the current Fluidinfo user — fish 4.33 documentation</title>

    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />

    <link rel="top" title="fish 4.33 documentation" href="index.html" />
    <link rel="next" title="quit — quits fish" href="quit.html" />
    <link rel="prev" title="su — sets the Fluidinfo user" href="su.html" />

Navigation

          index

          next |

          previous |

fish 4.33 documentation »

whoami — prints the name of the current Fluidinfo user¶

Prints the name of the current authenticated user.

FORM

whoami

Previous topic

su — sets the Fluidinfo user

Next topic

quit — quits fish

This Page

Show Source

Quick search

    <form class="search" action="search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

fish 4.33 documentation »

        © Copyright 2011-2012, Nicholas J. Radcliffe.
      Created using Sphinx 1.1.2.


text:
package com.asp.placequiz.database;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public final class DbOperations {
    /**
     * Using the database provided finds the email's unique user ID.
     * @param db The database to use. <b>Must be open!</b>
     * @param email The email of the user to use as a search key.
     * @return The user ID for the given email or -1 if none found in the database.
     */
    public static long getUserId(SQLiteDatabase db, String email) {
        if (db.isOpen()) {
            String[] projection = {
                    MapQuizContract.UserEntry._ID,
                    MapQuizContract.UserEntry.COLUMN_NAME_USER_EMAIL_HASH
            };
            String selection = MapQuizContract.UserEntry.COLUMN_NAME_USER_EMAIL_HASH +
                    " = '" + email.hashCode() + "'";
            Cursor c = db.query(
                    MapQuizContract.UserEntry.TABLE_NAME,  // Table name
                    projection,                            // Columns to select
                    selection,                             // Where statement
                    null,
                    null,                                  // no grouping ignore
                    null,                                  // no grouping ignore
                    null);                                 // no ordering ignore
            try {
                int columnIndex = c.getColumnIndex(MapQuizContract.UserEntry._ID);
                if (columnIndex == -1)
                    throw new IllegalStateException("Unable to find the user ID column!");
                c.moveToFirst();
                if (c.getCount() > 0) {
                    long userId = c.getLong(columnIndex);
                    return userId;
                }
            } finally {
                c.close();
            }
        }
        return -1;
    }
}


text:
var React = require('react');
var StylePropable = require('./mixins/style-propable');
var Transitions = require('./styles/transitions');
var EnhancedSwitch = require('./enhanced-switch');
var RadioButtonOff = require('./svg-icons/toggle-radio-button-off');
var RadioButtonOn = require('./svg-icons/toggle-radio-button-on');

var RadioButton = React.createClass({displayName: "RadioButton",

  mixins: [StylePropable],

  contextTypes: {
    muiTheme: React.PropTypes.object
  },

  propTypes: {
    iconStyle: React.PropTypes.object,
    onCheck: React.PropTypes.func
  },

  getTheme: function() {
    return this.context.muiTheme.component.radioButton;
  },

  getStyles: function() {
    var styles = {
      icon: {
          height: this.getTheme().size,
          width: this.getTheme().size
      },
      target: {
          transition: Transitions.easeOut(),
          position: 'absolute',
          opacity: 1,
          transform: 'scale(1)',
          fill: this.getTheme().borderColor
      },
      fill: {
          position: 'absolute',
          opacity: 1,
          transform: 'scale(0)',
          transformOrigin: '50% 50%',
          transition: Transitions.easeOut(),
          fill: this.getTheme().checkedColor
      },
      targetWhenChecked: {
        opacity: 0,
        transform: 'scale(0)'
      },
      fillWhenChecked: {
        opacity: 1,
        transform: 'scale(1)'
      },
      targetWhenDisabled: {
        fill: this.getTheme().disabledColor
      },
      fillWhenDisabled: {
        fill: this.getTheme().disabledColor
      },
    };
    return styles;
  },

  render: function() {
    var $__0=

      this.props,onCheck=$__0.onCheck,other=(function(source, exclusion) {var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) {throw new TypeError();}for (var key in source) {if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) {rest[key] = source[key];}}return rest;})($__0,{onCheck:1});

    var styles = this.getStyles();
    var onStyles =
      this.mergeAndPrefix(
        styles.target,
        this.props.checked && styles.targetWhenChecked,
        this.props.iconStyle,
        this.props.disabled && styles.targetWhenDisabled);
    var offStyles =
      this.mergeAndPrefix(
        styles.fill,
        this.props.checked && styles.fillWhenChecked,
        this.props.iconStyle,
        this.props.disabled && styles.fillWhenDisabled);

    var radioButtonElement = (
      React.createElement("div", null,
          React.createElement(RadioButtonOff, {style: onStyles}),
          React.createElement(RadioButtonOn, {style: offStyles})
      )
    );

    var rippleColor = this.props.checked ? this.getTheme().checkedColor : this.getTheme().borderColor;

    var enhancedSwitchProps = {
      ref: "enhancedSwitch",
      inputType: "radio",
      switched: this.props.checked,
      switchElement: radioButtonElement,
      rippleColor: rippleColor,
      iconStyle: styles.icon,
      onSwitch: this._handleCheck,
      onParentShouldUpdate: this._handleStateChange,
      labelPosition: (this.props.labelPosition) ? this.props.labelPosition : "right"
    };

    return (
      React.createElement(EnhancedSwitch, React.__spread({},
        other,
        enhancedSwitchProps))
    );
  },

  // Only called when selected, not when unselected.
  _handleCheck: function(e) {
    if (this.props.onCheck) this.props.onCheck(e, this.props.value);
  },

  _handleStateChange: function(newSwitched) {
  },

  isChecked: function() {
    return this.refs.enhancedSwitch.isSwitched();
  },

  // Use RadioButtonGroup.setSelectedValue(newSelectionValue) to set a
  // RadioButton's checked value.
  setChecked: function(newCheckedValue) {
    this.refs.enhancedSwitch.setSwitched(newCheckedValue);
  },

  getValue: function() {
    return this.refs.enhancedSwitch.getValue();
  }

});

module.exports = RadioButton;


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

//Assets
import './css/Footer.css';

class Footer extends Component {
    static propTypes = {
        copyright: PropTypes.string,
    };
    render() {
        const { copyright = '© React 2017' } = this.props;
        return (

        );
    }
}

export default Footer;


text:
from __future__ import unicode_literals
import frappe
from frappe import _

from frappe.model.document import Document

class Workflow(Document):

	def validate(self):
		self.set_active()
		self.create_custom_field_for_workflow_state()
		self.update_default_workflow_status()

	def on_update(self):
		frappe.clear_cache(doctype=self.document_type)

	def create_custom_field_for_workflow_state(self):
		frappe.clear_cache(doctype=self.document_type)
		meta = frappe.get_meta(self.document_type)
		if not meta.get_field(self.workflow_state_field):
			# create custom field
			frappe.get_doc({
				"doctype":"Custom Field",
				"dt": self.document_type,
				"__islocal": 1,
				"fieldname": self.workflow_state_field,
				"label": self.workflow_state_field.replace("_", " ").title(),
				"hidden": 1,
				"fieldtype": "Link",
				"options": "Workflow State",
			}).save()

			frappe.msgprint(_("Created Custom Field {0} in {1}").format(self.workflow_state_field,
				self.document_type))

	def update_default_workflow_status(self):
		docstatus_map = {}
		states = self.get("workflow_document_states")
		for d in states:
			if not d.doc_status in docstatus_map:
				frappe.db.sql("""update `tab%s` set `%s` = %s where \
					ifnull(`%s`, '')='' and docstatus=%s""" % (self.document_type, self.workflow_state_field,
						'%s', self.workflow_state_field, "%s"), (d.state, d.doc_status))
				docstatus_map[d.doc_status] = d.state

	def set_active(self):
		if int(self.is_active or 0):
			# clear all other
			frappe.db.sql("""update tabWorkflow set is_active=0
				where document_type=%s""",
				self.document_type)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Gen. fung. (Minneapolis) (1909)

#### Original name
Porina schizospora Vain.

### Remarks
null


text:
package org.ofbiz.birt.report.context;

import java.net.URL;

import javax.servlet.http.HttpServletRequest;

import org.eclipse.birt.report.context.ViewerAttributeBean;
import org.eclipse.birt.report.exception.ViewerException;
import org.eclipse.birt.report.resource.ResourceConstants;
import org.eclipse.birt.report.utility.DataUtil;
import org.eclipse.birt.report.utility.ParameterAccessor;
import org.ofbiz.base.location.FlexibleLocation;
import org.ofbiz.base.util.UtilValidate;

public class BirtViewerAttributeBean extends ViewerAttributeBean {

    public final static String module = BirtViewerAttributeBean.class.getName();

    public BirtViewerAttributeBean(HttpServletRequest request) {
        super(request);
    }

    @Override
    protected void __init(HttpServletRequest request) throws Exception {
        String reportParam = DataUtil.trimString( ParameterAccessor.getParameter( request, ParameterAccessor.PARAM_REPORT ));
        if (reportParam.startsWith("component://")) {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            if (loader == null) {
                loader = BirtViewerAttributeBean.class.getClassLoader();
            }
            URL reportFileUrl = null;
            reportFileUrl = FlexibleLocation.resolveLocation(reportParam, loader);
            if (reportFileUrl == null) {
                throw new IllegalArgumentException("Could not resolve location to URL: " + reportParam);
            }
            this.reportDesignName = reportFileUrl.getPath();
        } else {
            this.reportDesignName = ParameterAccessor.getReport( request, null );
        }

        if (UtilValidate.isNotEmpty(this.reportDesignName)) {
            this.reportDesignHandle = getDesignHandle( request );
            if ( this.reportDesignHandle == null )
                throw new ViewerException(
                        ResourceConstants.GENERAL_EXCEPTION_NO_REPORT_DESIGN );
            // Initialize report parameters.
            __initParameters( request );
        }
    }
}


text:
package net.geocentral.geometria.evaluator.operator;

import net.geocentral.geometria.evaluator.token.GUnaryOperator;
import net.geocentral.geometria.evaluator.token.GValueToken;

import org.apache.log4j.Logger;

public class GNegate implements GUnaryOperator {

    private static Logger logger = Logger.getLogger("net.geocentral.geometria");

    public double evaluate(GValueToken token) {
        logger.info(token);
        return -token.getValue();
    }

    public int getPrecedence() {
        return 30;
    }

    public String toString() {
        return "neg";
    }
}


text:
var ts = require('typescript');

module.exports = {
  process: function(src, path) {
    return ts.transpile(src, {
      target: ts.ScriptTarget.ES5,
      module: ts.ModuleKind.CommonJS
    })
  }
};


text:
package io.indexr.hive;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.ql.io.CombineHiveInputFormat;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.InputSplit;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.RecordReader;
import org.apache.hadoop.mapred.Reporter;

import java.io.IOException;

public class IndexRInputFormat extends FileInputFormat<Void, ArrayWritable> implements CombineHiveInputFormat.AvoidSplitCombination {
    @Override
    protected boolean isSplitable(FileSystem fs, Path filename) {
        //  Never splite.
        return false;
    }

    @Override
    public boolean shouldSkipCombine(Path path, Configuration conf) throws IOException {
        // Never combine.
        return true;
    }

    @Override
    public RecordReader getRecordReader(InputSplit inputSplit, JobConf jobConf, Reporter reporter) throws IOException {
        return new IndexRRecordReader(inputSplit, jobConf);
    }
}


text:
package fr.acxio.tools.agia.convert;

/**
 * <p>
 * Conversion related exception.
 * </p>
 *
 * @author pcollardez
 *
 */
public class ConversionException extends Exception {

    private static final long serialVersionUID = 9188247825367599489L;

    public ConversionException() {
    }

    public ConversionException(String sArg0) {
        super(sArg0);
    }

    public ConversionException(Throwable sArg0) {
        super(sArg0);
    }

    public ConversionException(String sArg0, Throwable sArg1) {
        super(sArg0, sArg1);
    }

}


text:
"use strict";
/**
 * Created by DuanG on 2016/8/26.
 */
var app_1 = require('../routes/app');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser');
var path = require('path');
var timeoutParser = require('./timeout-parser');
var errParser = require('./error-parser');
var cors = require('cors');
var server_config_1 = require('../configs/server-config');
var cookieParser = require('cookie-parser');
exports.parserInit = function () {
    app_1.app.use(favicon(path.resolve('favicon.ico')));
    app_1.app.use(bodyParser.json());
    app_1.app.use(bodyParser.urlencoded({ extended: false }));
    app_1.app.use(cookieParser());
    if (server_config_1.SERVER_CONFIG.env === server_config_1.DEV) {
        app_1.app.use(logger(server_config_1.DEV));
        var whitelist = ['http://127.0.0.1:3008', 'http://127.0.0.1:3006'];
        var corsOptionsDelegate = function (req, callback) {
            var corsOptions;
            if (whitelist.indexOf(req.header('Origin')) !== -1) {
                corsOptions = { origin: true, credentials: true }; // reflect (enable) the requested origin in the CORS response
            }
            else {
                corsOptions = { origin: false }; // disable CORS for this request
            }
            callback(null, corsOptions); // callback expects two parameters: error and options
        };
        /*var corsOptions = {
            origin: 'http://127.0.0.1:3008',
            optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
        };*/
        app_1.app.use(cors(corsOptionsDelegate)); //white List
    }
    else if (server_config_1.SERVER_CONFIG.env === server_config_1.PROD) {
        app_1.app.use(logger('prod'));
    }
    timeoutParser.init();
    errParser.init();
    exports.parserInit = function () {
        throw new Error("parsers/index.ts: parsers have been initialized.");
    };
};