text:
package org.apache.sis.internal.jaxb.metadata;

import javax.xml.bind.annotation.XmlElementRef;
import org.opengis.metadata.maintenance.MaintenanceInformation;
import org.apache.sis.metadata.iso.maintenance.DefaultMaintenanceInformation;
import org.apache.sis.internal.jaxb.gco.PropertyType;

/**
 * JAXB adapter mapping implementing class to the GeoAPI interface. See
 * package documentation for more information about JAXB and interface.
 *
 * @author  Cédric Briançon (Geomatys)
 * @author  Martin Desruisseaux (Geomatys)
 * @version 0.3
 * @since   0.3
 * @module
 */
public final class MD_MaintenanceInformation extends
        PropertyType<MD_MaintenanceInformation, MaintenanceInformation>
{
    /**
     * Empty constructor for JAXB only.
     */
    public MD_MaintenanceInformation() {
    }

    /**
     * Returns the GeoAPI interface which is bound by this adapter.
     * This method is indirectly invoked by the private constructor
     * below, so it shall not depend on the state of this object.
     *
     * @return {@code MaintenanceInformation.class}
     */
    @Override
    protected Class<MaintenanceInformation> getBoundType() {
        return MaintenanceInformation.class;
    }

    /**
     * Constructor for the {@link #wrap} method only.
     */
    private MD_MaintenanceInformation(final MaintenanceInformation metadata) {
        super(metadata);
    }

    /**
     * Invoked by {@link PropertyType} at marshalling time for wrapping the given metadata value
     * in a {@code <gmd:MD_MaintenanceInformation>} XML element.
     *
     * @param  metadata  the metadata element to marshall.
     * @return a {@code PropertyType} wrapping the given the metadata element.
     */
    @Override
    protected MD_MaintenanceInformation wrap(final MaintenanceInformation metadata) {
        return new MD_MaintenanceInformation(metadata);
    }

    /**
     * Invoked by JAXB at marshalling time for getting the actual metadata to write
     * inside the {@code <gmd:MD_MaintenanceInformation>} XML element.
     * This is the value or a copy of the value given in argument to the {@code wrap} method.
     *
     * @return the metadata to be marshalled.
     */
    @XmlElementRef
    public DefaultMaintenanceInformation getElement() {
        return DefaultMaintenanceInformation.castOrCopy(metadata);
    }

    /**
     * Invoked by JAXB at unmarshalling time for storing the result temporarily.
     *
     * @param  metadata  the unmarshalled metadata.
     */
    public void setElement(final DefaultMaintenanceInformation metadata) {
        this.metadata = metadata;
    }
}

redpajama_set_name: RedPajamaGithub


text:
""" CodeMommy WebPython """

import CodeMommy.core.Http
import CodeMommy.core.About
import CodeMommy.core.Route
import CodeMommy.core.Server
import CodeMommy.core.Output

class Http(CodeMommy.core.Http.Http): pass

class About(CodeMommy.core.About.About): pass

class Route(CodeMommy.core.Route.Route): pass

class Server(CodeMommy.core.Server.Server): pass

class Output(CodeMommy.core.Output.Output): pass


text:
/** Run a wdl task.

In the example below, we want to run the Add task in a dx:applet.

task Add {
    Int a
    Int b

    command {
        echo $((a + b))
    }
    output {
        Int sum = read_int(stdout())
    }
}

  */
package dx.exec

import java.lang.management._
import java.nio.file.{Files, Path, Paths}

import dx.AppInternalException
import dx.api.{DxApi, DxJob, InstanceTypeDB}
import dx.compiler.WdlRuntimeAttrs
import dx.exec
import dx.core.io.{DxPathConfig, DxdaManifest, DxfuseManifest}
import dx.core.languages.wdl._
import dx.core.getVersion
import spray.json._
import wdlTools.eval.{Eval, WdlValueBindings, WdlValues}
import wdlTools.exec.DockerUtils
import wdlTools.syntax.SourceLocation
import wdlTools.types.{WdlTypes, TypedAbstractSyntax => TAT}
import wdlTools.util.{
  FileSource,
  FileSourceResolver,
  FileUtils,
  RealFileSource,
  SysUtils,
  TraceLevel
}

case class TaskRunner(task: TAT.Task,
                      document: TAT.Document,
                      typeAliases: Map[String, WdlTypes.T],
                      instanceTypeDB: InstanceTypeDB,
                      dxPathConfig: DxPathConfig,
                      fileResolver: FileSourceResolver,
                      wdlVarLinksConverter: WdlVarLinksConverter,
                      jobInputOutput: JobInputOutput,
                      defaultRuntimeAttrs: Option[WdlRuntimeAttrs],
                      delayWorkspaceDestruction: Option[Boolean],
                      dxApi: DxApi,
                      evaluator: Eval) {
  private val dockerUtils = DockerUtils(fileResolver)

  // serialize the task inputs to json, and then write to a file.
  def writeEnvToDisk(localizedInputs: Map[String, (WdlTypes.T, WdlValues.V)],
                     fileSourceToPath: Map[FileSource, Path]): Unit = {
    val locInputsM: Map[String, JsValue] = localizedInputs.map {
      case (name, (t, v)) =>
        val wdlTypeRepr = TypeSerialization(typeAliases).toString(t)
        val value = WdlValueSerialization(typeAliases).toJSON(t, v)
        (name, JsArray(JsString(wdlTypeRepr), value))
    }
    val dxUrlM: Map[String, JsValue] = fileSourceToPath.map {
      case (fileSource: RealFileSource, path) => fileSource.value -> JsString(path.toString)
      case (other, _) =>
        throw new RuntimeException(s"Can only serialize a RealFileSource, not ${other}")
    }

    // marshal into json, and then to a string
    val json = JsObject("localizedInputs" -> JsObject(locInputsM), "dxUrl2path" -> JsObject(dxUrlM))
    FileUtils.writeFileContent(dxPathConfig.runnerTaskEnv, json.prettyPrint)
  }

  def readEnvFromDisk(): (Map[String, (WdlTypes.T, WdlValues.V)], Map[FileSource, Path]) = {
    val buf = FileUtils.readFileContent(dxPathConfig.runnerTaskEnv)
    val json: JsValue = buf.parseJson
    val (localPathToJs, dxUriToJs) = json match {
      case JsObject(m) =>
        (m.get("localizedInputs"), m.get("dxUrl2path")) match {
          case (Some(JsObject(env_m)), Some(JsObject(path_m))) =>
            (env_m, path_m)
          case (_, _) =>
            throw new Exception("Malformed environment serialized to disk")
        }
      case _ => throw new Exception("Malformed environment serialized to disk")
    }
    val localizedInputs = localPathToJs.map {
      case (key, JsArray(Vector(JsString(wdlTypeRepr), jsVal))) =>
        val t = TypeSerialization(typeAliases).fromString(wdlTypeRepr)
        val value = WdlValueSerialization(typeAliases).fromJSON(jsVal)
        key -> (t, value)
      case (_, other) =>
        throw new Exception(s"Bad deserialization value ${other}")
    }
    val fileSourceToPath = dxUriToJs.map {
      case (uri, JsString(path)) => fileResolver.resolve(uri) -> Paths.get(path)
      case other                 => throw new Exception(s"Invalid map item ${other}")
    }
    (localizedInputs, fileSourceToPath)
  }

  private def printDirStruct(): Unit = {
    dxApi.logger.traceLimited("Directory structure:", minLevel = TraceLevel.VVerbose)
    val (_, stdout, _) = SysUtils.execCommand("ls -lR", None)
    dxApi.logger.traceLimited(stdout + "\n", 10000, minLevel = TraceLevel.VVerbose)
  }

  // Figure out if a docker image is specified. If so, return it as a string.
  private def dockerImageEval(env: Map[String, WdlValues.V]): Option[String] = {
    val attributes: Map[String, TAT.Expr] = task.runtime match {
      case None                             => Map.empty
      case Some(TAT.RuntimeSection(kvs, _)) => kvs
    }
    val dImg: Option[WdlValues.V] = attributes.get("docker") match {
      case None =>
        defaultRuntimeAttrs match {
          case None      => None
          case Some(dra) => dra.m.get("docker")
        }
      case Some(expr) =>
        val value = evaluator.applyExprAndCoerce(expr, WdlTypes.T_String, WdlValueBindings(env))
        Some(value)
    }
    dImg match {
      case None                        => None
      case Some(WdlValues.V_String(s)) => Some(s)
      case Some(other) =>
        throw new AppInternalException(s"docker is not a string expression ${other}")
    }
  }

  private def dockerImage(env: Map[String, WdlValues.V], loc: SourceLocation): Option[String] = {
    dockerImageEval(env) match {
      case Some(nameOrUrl) => Some(dockerUtils.getImage(nameOrUrl, loc))
      case other           => other
    }
  }

  // Figure how much memory is available for this container/image
  //
  // We may need to check the cgroup itself. Not sure how portable that is.
  //val totalAvailableMemoryBytes = Utils.readFileContent("/sys/fs/cgroup/memory/memory.limit_in_bytes").toInt
  //
  private def availableMemory(): Long = {
    val mbean = ManagementFactory.getOperatingSystemMXBean
      .asInstanceOf[com.sun.management.OperatingSystemMXBean]
    mbean.getTotalPhysicalMemorySize
  }

  // Write the core bash script into a file. In some cases, we
  // need to run some shell setup statements before and after this
  // script.
  private def writeBashScript(command: String): Unit = {
    // This is based on Cromwell code from
    // [BackgroundAsyncJobExecutionActor.scala].  Generate a bash
    // script that captures standard output, and standard
    // error. We need to be careful to pipe stdout/stderr to the
    // parent stdout/stderr, and not lose the result code of the
    // shell command. Notes on bash magic symbols used here:
    //
    //  Symbol  Explanation
    //    >     redirect stdout
    //    2>    redirect stderr
    //    <     redirect stdin
    //
    val script =
      if (command.isEmpty) {
        s"""|#!/bin/bash
            |echo 0 > ${dxPathConfig.rcPath}
            |""".stripMargin.trim + "\n"
      } else {
        // It would have been easier to have one long
        // section bracketed with triple quotes (`"""`). However,
        // some characters are dropped from [command] this way, for
        // example pipe ('|').
        val part1 =
          s"""|#!/bin/bash
              |(
              |    cd ${dxPathConfig.homeDir.toString}
              |""".stripMargin
        val part2 =
          s"""|) \\
              |  > >( tee ${dxPathConfig.stdout} ) \\
              |  2> >( tee ${dxPathConfig.stderr} >&2 )
              |
              |echo $$? > ${dxPathConfig.rcPath}
              |
              |# make sure the files are on stable storage
              |# before leaving. This helps with stdin and stdout
              |# characters that may be in the fifo queues.
              |sync
              |""".stripMargin
        Vector(part1, command, part2).mkString("\n")
      }
    dxApi.logger.traceLimited(s"writing bash script to ${dxPathConfig.script}")
    FileUtils.writeFileContent(dxPathConfig.script, script)
    dxPathConfig.script.toFile.setExecutable(true)
  }

  private def writeDockerSubmitBashScript(imgName: String, dxfuseRunning: Boolean): Unit = {
    // The user wants to use a docker container with the
    // image [imgName].
    //
    // Map the home directory into the container, so that
    // we can reach the result files, and upload them to
    // the platform.
    //

    // Limit the docker container to leave some memory for the rest of the
    // ongoing system services, for example, dxfuse.
    //
    // This doesn't work with our current docker installation, unfortunately.
    // I am leaving the code here, so we could fix this in the future.
    val totalAvailableMemoryBytes = availableMemory()
    val memCap =
      if (dxfuseRunning)
        totalAvailableMemoryBytes - exec.DXFUSE_MAX_MEMORY_CONSUMPTION
      else
        totalAvailableMemoryBytes

    val dockerRunScript =
      s"""|#!/bin/bash -x
          |
          |# make sure there is no preexisting Docker CID file
          |rm -f ${dxPathConfig.dockerCid}
          |
          |# Run the container under a priviliged user, so it will have
          |# permissions to read/write files in the home directory. This
          |# is required in cases where the container uses a different
          |# user.
          |extraFlags="--user $$(id -u):$$(id -g) --hostname $$(hostname)"
          |
          |# run as in the original configuration
          |docker run \\
          |  --memory=${memCap} \\
          |  --cidfile ${dxPathConfig.dockerCid} \\
          |  $${extraFlags} \\
          |  --entrypoint /bin/bash \\
          |  -v ${dxPathConfig.homeDir}:${dxPathConfig.homeDir} \\
          |  ${imgName} ${dxPathConfig.script.toString}
          |
          |# get the return code (working even if the container was detached)
          |rc=$$(docker wait `cat ${dxPathConfig.dockerCid.toString}`)
          |
          |# remove the container after waiting
          |docker rm `cat ${dxPathConfig.dockerCid.toString}`
          |
          |# return exit code
          |exit $$rc
          |""".stripMargin

    //  -v ${dxPathConfig.dxfuseMountpoint}:${dxPathConfig.dxfuseMountpoint}

    dxApi.logger.traceLimited(s"writing docker run script to ${dxPathConfig.dockerSubmitScript}")
    FileUtils.writeFileContent(dxPathConfig.dockerSubmitScript, dockerRunScript)
    dxPathConfig.dockerSubmitScript.toFile.setExecutable(true)
  }

  private def inputsDbg(inputs: Map[TAT.InputDefinition, WdlValues.V]): String = {
    inputs
      .map {
        case (inp, value) =>
          s"${inp.name} -> (${inp.wdlType}, ${value})"
      }
      .mkString("\n")
  }

  private def stripTypesFromEnv(
      env: Map[String, (WdlTypes.T, WdlValues.V)]
  ): Map[String, WdlValues.V] = {
    env.map { case (name, (_, v)) => name -> v }
  }

  private def evalInputsAndDeclarations(
      inputsWithTypes: Map[String, (WdlTypes.T, WdlValues.V)]
  ): Map[String, (WdlTypes.T, WdlValues.V)] = {
    // evaluate the declarations using the inputs
    val env: Map[String, (WdlTypes.T, WdlValues.V)] =
      task.declarations.foldLeft(inputsWithTypes) {
        case (env, TAT.Declaration(name, wdlType, Some(expr), _)) =>
          val wdlValue =
            evaluator.applyExprAndCoerce(expr, wdlType, WdlValueBindings(stripTypesFromEnv(env)))
          env + (name -> (wdlType, wdlValue))
        case (_, TAT.Declaration(name, _, None, _)) =>
          throw new Exception(s"Declaration ${name} has no expression")
      }
    env
  }

  // Calculate the input variables for the task, download the input files,
  // and build a shell script to run the command.
  def prolog(
      taskInputs: Map[TAT.InputDefinition, WdlValues.V]
  ): (Map[String, (WdlTypes.T, WdlValues.V)], Map[FileSource, Path]) = {
    if (dxApi.logger.isVerbose) {
      dxApi.logger.traceLimited(s"Prolog debugLevel=${dxApi.logger.traceLevel}")
      dxApi.logger.traceLimited(s"dxWDL version: ${getVersion}")
      if (dxApi.logger.traceLevel >= TraceLevel.VVerbose) {
        printDirStruct()
      }
      dxApi.logger.traceLimited(s"Task source code:")
      dxApi.logger.traceLimited(document.source.readString, 10000)
      dxApi.logger.traceLimited(s"inputs: ${inputsDbg(taskInputs)}")
    }

    val parameterMeta: Map[String, TAT.MetaValue] = task.parameterMeta match {
      case None                          => Map.empty
      case Some(TAT.MetaSection(kvs, _)) => kvs
    }

    // Download/stream all input files.
    //
    // Note: this may be overly conservative,
    // because some of the files may not actually be accessed.
    val (localizedInputs, fileSourceToPath, dxdaManifest, dxfuseManifest) =
      jobInputOutput.localizeFiles(parameterMeta, taskInputs, dxPathConfig.inputFilesDir)

    // build a manifest for dxda, if there are files to download
    val DxdaManifest(manifestJs) = dxdaManifest
    if (manifestJs.asJsObject.fields.nonEmpty) {
      FileUtils.writeFileContent(dxPathConfig.dxdaManifest, manifestJs.prettyPrint)
    }

    // build a manifest for dxfuse
    val DxfuseManifest(manifest2Js) = dxfuseManifest
    if (manifest2Js != JsNull) {
      FileUtils.writeFileContent(dxPathConfig.dxfuseManifest, manifest2Js.prettyPrint)
    }

    val inputsWithTypes: Map[String, (WdlTypes.T, WdlValues.V)] =
      localizedInputs.map {
        case (inpDfn, value) =>
          inpDfn.name -> (inpDfn.wdlType, value)
      }

    dxApi.logger.traceLimited(s"Epilog: complete, inputsWithTypes = ${localizedInputs}")
    (inputsWithTypes, fileSourceToPath)
  }

  // HERE we download all the inputs, or mount them with dxfuse

  // instantiate the bash command
  def instantiateCommand(
      localizedInputs: Map[String, (WdlTypes.T, WdlValues.V)]
  ): Map[String, (WdlTypes.T, WdlValues.V)] = {
    dxApi.logger.traceLimited(s"InstantiateCommand, env = ${localizedInputs}")

    val env = evalInputsAndDeclarations(localizedInputs)
    val docker = dockerImage(stripTypesFromEnv(env), task.command.loc)

    // instantiate the command
    val command = evaluator.applyCommand(task.command, WdlValueBindings(stripTypesFromEnv(env)))

    // Write shell script to a file. It will be executed by the dx-applet shell code.
    writeBashScript(command)
    docker match {
      case Some(img) =>
        // write a script that launches the actual command inside a docker image.
        writeDockerSubmitBashScript(img, Files.exists(dxPathConfig.dxfuseManifest))
      case None => ()
    }

    // Record the localized inputs, we need them in the ilog
    env
  }

  // HERE we run docker and/or the bash script

  def epilog(localizedInputs: Map[String, (WdlTypes.T, WdlValues.V)],
             fileSourceToPath: Map[FileSource, Path]): Map[String, JsValue] = {
    dxApi.logger.traceLimited(s"Epilog debugLevel=${dxApi.logger.traceLevel}")
    if (dxApi.logger.traceLevel >= TraceLevel.VVerbose) {
      printDirStruct()
    }

    // Evaluate the output declarations. Add outputs evaluated to the environment,
    // so they can be referenced by expressions in the next lines.
    val outputsLocal: Map[String, (WdlTypes.T, WdlValues.V)] =
      task.outputs
        .foldLeft(Map.empty[String, (WdlTypes.T, WdlValues.V)]) {
          case (env, outDef: TAT.OutputDefinition) =>
            val inputsNoTypes = stripTypesFromEnv(localizedInputs)
            val envNoTypes = stripTypesFromEnv(env)
            val value = evaluator.applyExprAndCoerce(outDef.expr,
                                                     outDef.wdlType,
                                                     WdlValueBindings(envNoTypes ++ inputsNoTypes))
            env + (outDef.name -> (outDef.wdlType, value))
        }

    val outputs: Map[String, (WdlTypes.T, WdlValues.V)] =
      // Upload output files to the platform.
      jobInputOutput.delocalizeFiles(outputsLocal, fileSourceToPath)

    // convert the WDL values to JSON
    val outputFields: Map[String, JsValue] = outputs
      .map {
        case (outputVarName, (wdlType, wdlValue)) =>
          val wvl = wdlVarLinksConverter.importFromWDL(wdlType, wdlValue)
          wdlVarLinksConverter.genFields(wvl, outputVarName)
      }
      .toVector
      .flatten
      .toMap
    outputFields
  }

  // Evaluate the runtime expressions, and figure out which instance type
  // this task requires.
  //
  // Do not download the files, if there are any. We may be
  // calculating the instance type in the workflow runner, outside
  // the task.
  def calcInstanceType(taskInputs: Map[TAT.InputDefinition, WdlValues.V]): String = {
    dxApi.logger.traceLimited("calcInstanceType", minLevel = TraceLevel.VVerbose)
    dxApi.logger.traceLimited(s"inputs: ${inputsDbg(taskInputs)}", minLevel = TraceLevel.VVerbose)

    val inputsWithTypes: Map[String, (WdlTypes.T, WdlValues.V)] =
      taskInputs.map {
        case (inpDfn, value) =>
          inpDfn.name -> (inpDfn.wdlType, value)
      }
    val env = evalInputsAndDeclarations(inputsWithTypes)
    val runtimeAttrs: Map[String, TAT.Expr] = task.runtime match {
      case None                             => Map.empty
      case Some(TAT.RuntimeSection(kvs, _)) => kvs
    }

    def evalAttr(attrName: String): Option[WdlValues.V] = {
      runtimeAttrs.get(attrName) match {
        case None =>
          // try the defaults
          defaultRuntimeAttrs match {
            case None      => None
            case Some(dra) => dra.m.get(attrName)
          }
        case Some(expr) =>
          Some(
              evaluator
                .applyExprAndCoerce(expr,
                                    WdlTypes.T_String,
                                    WdlValueBindings(stripTypesFromEnv(env)))
          )
      }
    }

    val dxInstanceType = evalAttr("dx_instance_type")
    val memory = evalAttr("memory")
    val diskSpace = evalAttr("disks")
    val cores = evalAttr("cpu")
    val gpu = evalAttr("gpu")
    val iTypeRaw = InstanceTypes.parse(dxInstanceType, memory, diskSpace, cores, gpu)
    val iType = instanceTypeDB.apply(iTypeRaw)
    dxApi.logger.traceLimited(
        s"""|calcInstanceType memory=${memory} disk=${diskSpace}
            |cores=${cores} instancetype=${iType}""".stripMargin
          .replaceAll("\n", " ")
    )
    iType
  }

  /** Check if we are already on the correct instance type. This allows for avoiding unnecessary
    * relaunch operations.
    */
  def checkInstanceType(inputs: Map[TAT.InputDefinition, WdlValues.V]): Boolean = {
    // evaluate the runtime attributes
    // determine the instance type
    dxApi.logger.traceLimited(s"inputs: ${inputsDbg(inputs)}")

    val requiredInstanceType: String = calcInstanceType(inputs)
    dxApi.logger.traceLimited(s"required instance type: ${requiredInstanceType}")

    // Figure out which instance we are on right now
    val dxJob = dxApi.currentJob
    val descFieldReq = Map("fields" -> JsObject("instanceType" -> JsBoolean(true)))
    val retval = dxApi.jobDescribe(dxJob.id, descFieldReq)
    val crntInstanceType: String = retval.fields.get("instanceType") match {
      case Some(JsString(x)) => x
      case _                 => throw new Exception(s"wrong type for instanceType ${retval}")
    }
    dxApi.logger.traceLimited(s"current instance type: ${crntInstanceType}")

    val isSufficient = instanceTypeDB.lteqByResources(requiredInstanceType, crntInstanceType)
    dxApi.logger.traceLimited(s"isSufficient? ${isSufficient}")
    isSufficient
  }

  /** The runtime attributes need to be calculated at runtime. Evaluate them,
    *  determine the instance type [xxxx], and relaunch the job on [xxxx]
    */
  def relaunch(inputs: Map[TAT.InputDefinition, WdlValues.V],
               originalInputs: JsValue): Map[String, JsValue] = {
    dxApi.logger.traceLimited(s"inputs: ${inputsDbg(inputs)}")

    // evaluate the runtime attributes
    // determine the instance type
    val instanceType: String = calcInstanceType(inputs)

    // Run a sub-job with the "body" entry point, and the required instance type
    val dxSubJob: DxJob =
      dxApi.runSubJob("body",
                      Some(instanceType),
                      originalInputs,
                      Vector.empty,
                      delayWorkspaceDestruction)

    // Return promises (JBORs) for all the outputs. Since the signature of the sub-job
    // is exactly the same as the parent, we can immediately exit the parent job.
    val outputs: Map[String, JsValue] = task.outputs.flatMap { outDef: TAT.OutputDefinition =>
      val wvl = WdlVarLinks(outDef.wdlType, DxlExec(dxSubJob, outDef.name))
      wdlVarLinksConverter.genFields(wvl, outDef.name)
    }.toMap
    outputs
  }
}


text:
package org.eclipse.rdf4j.sail.memory.model;

import java.math.BigDecimal;
import java.math.BigInteger;

import org.eclipse.rdf4j.model.IRI;
import org.eclipse.rdf4j.model.base.CoreDatatype;
import org.eclipse.rdf4j.model.vocabulary.XSD;

/**
 * An extension of MemLiteral that stores a decimal value to avoid parsing.
 *
 * @author Arjohn Kampman
 */
public class DecimalMemLiteral extends MemLiteral {

	private static final long serialVersionUID = 6760727653986046772L;

	/*-----------*
	 * Variables *
	 *-----------*/

	private final BigDecimal value;

	/*--------------*
	 * Constructors *
	 *--------------*/

	public DecimalMemLiteral(Object creator, BigDecimal value) {
		this(creator, value, XSD.DECIMAL);
	}

	public DecimalMemLiteral(Object creator, BigDecimal value, IRI datatype) {
		this(creator, value.toPlainString(), value, datatype);
	}

	public DecimalMemLiteral(Object creator, String label, BigDecimal value, IRI datatype) {
		super(creator, label, datatype);
		this.value = value;
	}

	public DecimalMemLiteral(Object creator, String label, BigDecimal value, CoreDatatype datatype) {
		super(creator, label, datatype);
		this.value = value;
	}

	/*---------*
	 * Methods *
	 *---------*/

	@Override
	public byte byteValue() {
		return value.byteValue();
	}

	@Override
	public short shortValue() {
		return value.shortValue();
	}

	@Override
	public int intValue() {
		return value.intValue();
	}

	@Override
	public long longValue() {
		return value.longValue();
	}

	@Override
	public float floatValue() {
		return value.floatValue();
	}

	@Override
	public double doubleValue() {
		return value.doubleValue();
	}

	@Override
	public BigInteger integerValue() {
		return value.toBigInteger();
	}

	@Override
	public BigDecimal decimalValue() {
		return value;
	}
}


text:
package org.tinyj.lava;

/**
 * A supplier of values.
 *

 * This is the exception declaring version of {@link java.util.function.Supplier}
 *

 * There is no requirement that a new or distinct result be returned each
 * time the supplier is invoked.
 *

 * This is a functional interface whose functional method is
 * {@link #checkedGet}.
 *
 * @param <R> type of supplied values
 * @param <E> upper limit of thrown exception types
 */
@FunctionalInterface
public interface LavaSupplier<R, E extends Exception> {

  /**
   * Produce a value.
   *
   * @return a value
   */
  R checkedGet() throws E;

  /**
   * Safely casts between different {@link LavaSupplier} parametrization
   *
   * @param <R> required result type
   * @param <E> required exception limit
   * @param supplier supplier to adopt
   * @return {@code supplier} casted to the compatible parametrization {@link LavaSupplier}{@code <R, E>}
   */
  @SuppressWarnings("unchecked")
  static <R, E extends Exception>
  LavaSupplier<R, E> castDown(LavaSupplier<? extends R, ? extends E> supplier) {
    return (LavaSupplier<R, E>) supplier;
  }
}


text:
<?php

namespace Snazzware\Entity\Preferences;

/** @MappedSuperclass **/
class GridColumn extends \Snazzware\Entity {

	/**
	 *
	 * @ManyToOne(targetEntity="Grid", inversedBy="columns")
	 */
	protected $grid;

	/**
	 * @Column(type="string", nullable=true)
	 */
	protected $name;

	/**
	 * @Column(type="string", nullable=true)
	 */
	protected $caption;

	/**
	 * @Column(type="integer", nullable=true)
	 */
	protected $display;

	/**
	 * @Column(type="integer", nullable=true)
	 */
	protected $export;

	/**
	 * @Column(type="integer", nullable=true)
	 */
	protected $rank;

	/**
	 * @Column(type="decimal", nullable=true, precision=2, scale=2)
	 */
	protected $width;

}


text:
from .worker import BaseTask
import time

class ReadChannelValues(BaseTask):

    def __init__(self, worker, channel):
        super(ReadChannelValues, self).__init__(worker)
        self.channel = channel

    def __str__(self):
        return 'Measurements : %s' % self.channel

    def run(self):
        self.channel.read(self.client)

class WriteChannelValue(BaseTask):

    def __init__(self, worker, variable):
        super(WriteChannelValue, self).__init__(worker)
        self.variable = variable

    def run(self):
        self.variable.write(self.client)

class TuneUpCommand(BaseTask):
    # TODO : Integrate this in channel variable (or alike stuff) to manage events
    def run(self):
        self.client.tune_up()

class TuneDownCommand(BaseTask):

    def run(self):
        self.client.tune_down()


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WhallaLabs.Services.PayU.Helpers
{
    public class QueryCore
    {
        protected string _filedSeparator = ",";

        protected string ToQueryString(Dictionary<string, object> data)
        {
            return string.Join("&", data
                .Select(x => string.Concat(
                    Uri.EscapeDataString(x.Key), "=",
                    Uri.EscapeDataString(x.Value.ToString()))));
        }

        protected virtual string SerializeObject(object data)
        {
            if (data == null)
                throw new ArgumentNullException("data");

            // Get all properties on the object
            var allPriperties = data.GetType().GetProperties()
                .Where(x => x.CanRead)
                .Where(x => x.GetValue(data, null) != null)
                .Where(x => !Attribute.IsDefined(x, typeof(QueryIgnoreAttribute)));

            var nonTaggedProperties = allPriperties.Where(x => !Attribute.IsDefined(x, typeof(QueryPropertyAttribute)))
                .ToDictionary(x => x.Name, x => x.GetValue(data, null));

            var taggedProperties = allPriperties.Where(x => Attribute.IsDefined(x, typeof(QueryPropertyAttribute)))
                .ToDictionary(x => ((IEnumerable<QueryPropertyAttribute>)x.GetCustomAttributes(typeof(QueryPropertyAttribute), true)).First().Name, x => x.GetValue(data, null));

            string result = string.Empty;

            if (nonTaggedProperties.Any())
            {
                result += ToQueryString(nonTaggedProperties);
            }

            if (taggedProperties.Any())
            {
                if (!string.IsNullOrEmpty(result))
                    result += "&";

                result += ToQueryString(taggedProperties);
            }

            return result;
        }
    }
}


text:
using System;
using System.Reflection;

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Google.Maps
{
	public abstract class JsonCreationConverter<T> : JsonConverter
	{
		protected abstract T Create(Type objectType, JObject jsonObject);

		public override bool CanConvert(Type objectType)
		{
			return typeof(T).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
		}

		public override object ReadJson(JsonReader reader, Type objectType,
			object existingValue, JsonSerializer serializer)
		{
			var jsonObject = JObject.Load(reader);
			var target = Create(objectType, jsonObject);
			serializer.Populate(jsonObject.CreateReader(), target);
			return target;
		}

		public override void WriteJson(JsonWriter writer, object value,
			JsonSerializer serializer)
		{
			throw new NotImplementedException();
		}
	}

	public class JsonLocationConverter : JsonCreationConverter<Location>
	{
		protected override Location Create(Type objectType, JObject jsonObject)
		{
			return new LatLng(jsonObject.Value<double>("lat"), jsonObject.Value<double>("lng"));
		}
	}
}


text:
import { Component, Input } from '@angular/core';
import { ButtonSize, ButtonType } from 'app/shared/components/button.component';
import { FeatureToggle } from 'app/shared/feature-toggle/feature-toggle.service';
import { ProgrammingExerciseInstructorRepositoryType, ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service';
import { downloadZipFileFromResponse } from 'app/shared/util/download.util';
import { AlertService } from 'app/core/util/alert.service';
import { faDownload } from '@fortawesome/free-solid-svg-icons';

@Component({
    selector: 'jhi-programming-exercise-instructor-repo-download',
    template: `
        <jhi-button
            [disabled]="!exerciseId"
            [btnType]="ButtonType.INFO"
            [btnSize]="ButtonSize.SMALL"
            [shouldSubmit]="false"
            [featureToggle]="FeatureToggle.ProgrammingExercises"
            [icon]="faDownload"
            [title]="'artemisApp.programmingExercise.export.downloadRepo'"
            (onClick)="exportRepository()"
        ></jhi-button>
    `,
})
export class ProgrammingExerciseInstructorRepoDownloadComponent {
    ButtonType = ButtonType;
    ButtonSize = ButtonSize;
    readonly FeatureToggle = FeatureToggle;

    @Input()
    exerciseId: number;

    @Input()
    repositoryType: ProgrammingExerciseInstructorRepositoryType;

    @Input()
    auxiliaryRepositoryId: number;

    // Icons
    faDownload = faDownload;

    constructor(private programmingExerciseService: ProgrammingExerciseService, private alertService: AlertService) {}

    exportRepository() {
        if (this.exerciseId && this.repositoryType) {
            this.programmingExerciseService.exportInstructorRepository(this.exerciseId, this.repositoryType, this.auxiliaryRepositoryId).subscribe((response) => {
                downloadZipFileFromResponse(response);
                this.alertService.success('artemisApp.programmingExercise.export.successMessageRepos');
            });
        }
    }
}


text:
'use strict';

const { Router } = require('express');
const router = Router();
const { startLiveVideo } = require('../controllers/liveVideo.js');
/////////////////////////////////////////

router.get('/api/live', startLiveVideo);

/////////////////////////////////////////
module.exports = router;


text:
package ser2mat;

import ibm.*;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;

import com.jmatio.io.*;
import com.jmatio.types.*;

public class ser2mat {

	public MLChar GetString(String i) {
		MLChar o = new MLChar(null, new String[] {i}, i.length());
		return o;
	}

	public MLDouble GetDouble(double i) {
		MLDouble o = new MLDouble(null, new double[] {i}, 1);
		return o;
	}

	public MLDouble GetDouble(double[] i) {
		MLDouble o = new MLDouble(null, i, i.length);
		return o;
	}

	public MLDouble GetBoolean(boolean i) {
		MLDouble o = new MLDouble(null, new double[] {i?1:0}, 1);
		return o;
	}

	@SuppressWarnings("unchecked")
	public static void Convert(Model model) {
		// Loop over classes, starting with model
		ArrayList<Object> oTodoArray = new ArrayList<Object>();			// Array to-do array - yes, can be an "ArrayList< ArrayList<?> >"
		ArrayList<MLStructure> mlObjectArray = new ArrayList<MLStructure>();
		oTodoArray.add(model);
		mlObjectArray.add(new MLStructure("model", new int[] {1,1}));
		int it = 0; 													// it for Todo
		while(it<oTodoArray.size()) {
			Object oRaw = oTodoArray.get(it); 							// Perhaps still to be wrapped
			MLStructure mlO = mlObjectArray.get(it);
			// Wrap oRaw into an ArrayList oArray if we haven't already
			ArrayList<Object> oArray;
			if(oRaw instanceof ArrayList<?>) {
				oArray = (ArrayList<Object>) oRaw;						// This causes a "unchecked" warning we don't need to worry about. Will always be an ArrayList<Object>. Suppressed
			} else if(oRaw instanceof Object[]) {
				oArray = new ArrayList<Object>(Arrays.asList(oRaw));
			} else {
				oArray = new ArrayList<Object>();
				oArray.add(oRaw);
			}
			// And loop over the different elements in ArrayList<o.class> oArray
			for(int io=0; io<oArray.size(); io++) {
				Object o = oArray.get(io);
				Field[] fields = GetAllClassFields(o.getClass()); 		// Should remain the same for oArray
				// Loop over the fields in o
				for(Field f : fields) {
					try {
						// Don't want to try private fields
						if(Modifier.isPrivate(f.getModifiers()))
							continue;
						/* Simple types (where we can use the .class field) */
						if(f.getGenericType() 		== long.class) {
							String fname = f.getName();
							long val = f.getLong(o);
							mlO.setField(fname, new MLDouble(null, new double[] {val}, 1), io);
						}
						else if (f.getGenericType() == String.class) {
							String fname = f.getName();
							String val = String.valueOf(f.get(o));
							mlO.setField(fname, new MLChar(null, new String[] {val}, Math.max(val.length(),1)), io);
						}
						else if(f.getGenericType() 	== int.class) {
							String fname = f.getName();
							int val = f.getInt(o);
							mlO.setField(fname, new MLDouble(null, new double[] {val}, 1), io);
						}
						else if(f.getGenericType() 	== double.class) {
							String fname = f.getName();
							double val = f.getDouble(o);
							mlO.setField(fname, new MLDouble(null, new double[] {val}, 1), io);
						}
						else if(f.getGenericType() 	== boolean.class) {
							String fname = f.getName();
							boolean val = f.getBoolean(o);
							mlO.setField(fname, new MLDouble(null, new double[] {val?1:0}, 1), io);
						}
						else if(f.getGenericType() 	== ibm.Vector3d.class) {
							String fname = f.getName();
							Vector3d val = (Vector3d) f.get(o);
							mlO.setField(fname, new MLDouble(null, new double[] {val.x, val.y, val.z}, 3), io);
						}
						else if(f.getGenericType() 	== Cell.class) {
							String fname = f.getName();
							int val;
							if(f.get(o) != null)
								val = ((Cell) f.get(o)).Index();
							else
								val = -1;
							mlO.setField(fname, new MLDouble(null, new double[] {val}, 1), io);
						}
						else if(f.getGenericType() 	== Model.class) {
							continue; 									// Don't save Model class
						}
						else if(f.getType() == int[].class) {
							String fname = f.getName();
							int[] val = (int[]) f.get(o);
							// Convert int[] to double[] (there is no other way than this)
							double[] valDouble = new double[val.length];
							for(int ii=0; ii<val.length; ii++) {
								valDouble[ii] = (int) val[ii];
							}
							mlO.setField(fname, new MLDouble(null, valDouble, Math.max(valDouble.length,1)), io);
						}
						else if(f.getType() == int[][].class) {
							String fname = f.getName();
							int[][] val = (int[][]) f.get(o);
							// Convert int[][] to double[][] (there is no other way than this)
							double[][] valDouble = new double[val.length][val[0].length];
							for(int ii=0; ii<val.length; ii++) {
								for(int jj=0; jj<val[0].length; jj++) {
									valDouble[ii][jj] = (int) val[ii][jj];
								}
							}
							mlO.setField(fname, new MLDouble(null, valDouble), io);
						}
						else if(f.getType() == double[].class) {
							String fname = f.getName();
							double[] val = (double[]) f.get(o);
							mlO.setField(fname, new MLDouble(null, val, Math.max(val.length,1)), io);
						}
						else if(f.getType() == double[][].class) {
							String fname = f.getName();
							double[][] val = (double[][]) f.get(o);
							mlO.setField(fname, new MLDouble(null, val), io);
						}
						else if(f.getType() == boolean[].class) { 		// Alternatively: f.get(model).getClass().getComponentType()
							String fname = f.getName();
							boolean[] val = (boolean[]) f.get(o);
							// Convert boolean[] to double[]
							double[] valDouble = new double[val.length];
							for(int ii=0; ii<val.length; ii++)
								valDouble[ii] = val[ii] ? 1.0 : 0.0;
							mlO.setField(fname, new MLDouble(null, valDouble, Math.max(valDouble.length,1)), io);
						}
						else if(f.getType() == boolean[][].class) {
							String fname = f.getName();
							boolean[][] val = (boolean[][]) f.get(o);
							// Convert boolean[][] to double[][]
							double[][] valDouble = new double[val.length][val[0].length];
							for(int ii=0; ii<val.length; ii++)
								for(int jj=0; jj<val[0].length; jj++)
									valDouble[ii][jj] = val[ii][jj] ? 1.0 : 0.0;
							mlO.setField(fname, new MLDouble(null, valDouble), io);
						}
						else if(f.getType() == Ball[].class) {
							String fname = f.getName();
							Ball[] val = (Ball[]) f.get(o);
							// Convert Ball[] to double[] by looking at indices
							double[] valDouble = new double[val.length];
							for(int ii=0; ii<val.length; ii++)
								valDouble[ii] = val[ii].Index();
							mlO.setField(fname, new MLDouble(null, valDouble, Math.max(valDouble.length,1)), io);
						}
						else if(f.getType() == Vector3d[].class) {
							String fname = f.getName();
							Vector3d[] val = (Vector3d[]) f.get(o);
							// Convert Vector3d[] to double[][]
							double[][] valDouble = new double[val.length][3];
							for(int ii=0; ii<val.length; ii++) {
								valDouble[ii][0] = val[ii].x;
								valDouble[ii][1] = val[ii].y;
								valDouble[ii][2] = val[ii].z;
							}
							mlO.setField(fname, new MLDouble(null, valDouble), io);
						}
						// Get the really tricky ones (cellArray, ballArray, ...). Luckily we can generalise these
						else if(f.get(o) instanceof ArrayList) { 			// It's an ArrayList
							String fname = f.getName();
							ArrayList<?> fArrayList = (ArrayList<?>) f.get(o);
							Class<?> c = GetParClass(f);					// It's an ArrayList<Class c>
								if(o == model) {							// This ArrayList is nested directly under Model class
									MLStructure mlONew = new MLStructure(fname, new int[] {((ArrayList<?>) f.get(o)).size() ,1});
									oTodoArray.add(f.get(o));
									mlObjectArray.add(mlONew);
								} else {									// NOT nested directly under Model class --> find indices now
									Method IndexMethod = c.getMethod("Index");
									double[] fIndexArray = new double[fArrayList.size()]; 		// Though it is int, we'll save it as double
									for(int ie=0; ie<fArrayList.size(); ie++) {
										Object e1 = fArrayList.get(ie);
										fIndexArray[ie] = (Integer) IndexMethod.invoke(e1);
									}
									mlO.setField(fname, new MLDouble(null, fIndexArray, Math.max(fIndexArray.length,1)), io);
								}
						}
						else {
							throw new RuntimeException("Unknown class: "+f.getGenericType().toString()+" for variable "+f.getName());
						}
					} catch (IllegalArgumentException e) {
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						e.printStackTrace();
					} catch (NoSuchMethodException e) {
						e.printStackTrace();
					} catch (SecurityException e) {
						e.printStackTrace();
					} catch (InvocationTargetException e) {
						e.printStackTrace();
					}
				}
			}
			it++;
		}
		// populate mlModel and save
		ArrayList<MLArray> list = new ArrayList<MLArray>(1);
		MLStructure mlModel = mlObjectArray.get(0);
		for(int is=1; is<mlObjectArray.size(); is++) { 			// Don't start at 0, that's mlModel
			MLStructure mlO = mlObjectArray.get(is);
			mlModel.setField(mlO.name, 		   mlO);
		}
		list.add(mlModel);

		try {
			new MatFileWriter("results/" + model.name + "/output/" + String.format("g%04dr%04d", model.growthIter, model.relaxationIter) + ".mat",list);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static Class<?> GetParClass(Field f) {
		return (Class<?>) ((ParameterizedType) f.getGenericType()).getActualTypeArguments()[0];
	}

	private static Field[] GetAllClassFields(Class<?> c) {
		if(c.getSuperclass() == null || c.getSuperclass() == Object.class) {
			return c.getDeclaredFields();
		} else {
			ArrayList<Field> allFields = new ArrayList<Field>();
			// Add this class' fields
			for( Field f : c.getDeclaredFields() )					allFields.add(f);
			// Analyse superclass in the same way as this class (might have another super class)
			for( Field f : GetAllClassFields(c.getSuperclass()))	allFields.add(f);
			return  Arrays.copyOf(allFields.toArray(), allFields.size(), Field[].class);
		}
	}
}


text:
package uk.me.graphe.shared.messages;

import uk.me.graphe.shared.jsonwrapper.JSONException;
import uk.me.graphe.shared.jsonwrapper.JSONImplHolder;
import uk.me.graphe.shared.jsonwrapper.JSONObject;

public class SetGraphPropertiesMessage extends Message {

    private boolean mWeight;
    private boolean mDir;
    private boolean mFlowChart;

    public SetGraphPropertiesMessage(boolean weight, boolean directed, boolean flowchart) {
        mWeight = weight;
        mDir = directed;
        mFlowChart = flowchart;
    }

    public boolean hasWeight() {
        return mWeight;
    }

    public boolean hasDirection() {
        return mDir;
    }

    public boolean hasFlowChart() {
        return mFlowChart;
    }

    @Override
    public String toJson() {
        JSONObject repr = JSONImplHolder.make();
        try {
            repr.put("message", this.getMessage());
            repr.put("weight", mWeight ? "yes" : "no");
            repr.put("dir", mDir ? "yes" : "no");
            repr.put("flow", mFlowChart ? "yes" : "no");
        } catch (JSONException jse) {
            throw new Error(jse);
        }
        return repr.toString();
    }

    @Override
    public String getMessage() {
        return "sgp";
    }

}


text:
/**
 * Creates an adapter to post data to the SMAP server
 */
package edu.berkeley.eecs.cfc_tracker.smap;

import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.Context;
import android.content.Intent;
import android.content.SyncResult;
import android.net.http.AndroidHttpClient;
import android.os.Bundle;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;
import java.util.UUID;

import edu.berkeley.eecs.cfc_tracker.CommunicationHelper;
import edu.berkeley.eecs.cfc_tracker.ConnectionSettings;
import edu.berkeley.eecs.cfc_tracker.Constants;
import edu.berkeley.eecs.cfc_tracker.R;
import edu.berkeley.eecs.cfc_tracker.auth.GoogleAccountManagerAuth;
import edu.berkeley.eecs.cfc_tracker.auth.UserProfile;
import edu.berkeley.eecs.cfc_tracker.location.TripDiaryStateMachineIntentService;
import edu.berkeley.eecs.cfc_tracker.log.Log;
import edu.berkeley.eecs.cfc_tracker.usercache.BuiltinUserCache;
import edu.berkeley.eecs.cfc_tracker.usercache.UserCache;

/**
 * @author shankari
 *
 */
public class AddDataAdapter extends AbstractThreadedSyncAdapter {
	private static final String USER = "userName";

	private static final String TAG = "AddDataAdapter";

	private String projectName;
	private static String READINGS_NAME = "Readings";

	// private String userName;

	File privateFileDir;
	Properties uuidMap;
	// TODO: Delete after we start getting real values
	Random pseudoRandom;
	boolean syncSkip = false;
    private Context mContext = null;

	public AddDataAdapter(Context context, boolean autoInitialize) {
		super(context, autoInitialize);
		privateFileDir = context.getFilesDir();
		System.out.println("AddDataAdapter constructor called with "+privateFileDir);
		// We read the project name here because that's where we have access to a context
		projectName = context.getString(R.string.app_name);
		// It's enough to initialize the uuidMap at startup, since they don't change on a regular basis
		try {
			uuidMap = getUUIDMap(privateFileDir);
		} catch (IOException e) {
			// TODO: Built in some retry logic here
			System.err.println("Unable to save uuid map to file, so no point in publishing data anyway. Skipping sync ");
			syncSkip = true;
		}
		// The username is currently a uuid, which is better for privacy, and is also easier to implement
		// because we don't have to pass data between the main activity and this adapter, AND we don't have
		// to worry about what will happen if the user forgets to sign in, etc

		// userName = (String)uuidMap.get(USER);
        /*
		System.out.println("uuidMap.get(USER) = "+uuidMap.get(USER)+
				" userName = "+userName);
				*/

		// Create a random number generator since we don't yet have real values
		// TODO: Remove this once we get real values
		pseudoRandom = new Random();

        mContext = context;
		// Our ContentProvider is a dummy so there is nothing else to do here
	}

	/* (non-Javadoc)
	 * @see android.content.AbstractThreadedSyncAdapter#onPerformSync(android.accounts.Account, android.os.Bundle, java.lang.String, android.content.ContentProviderClient, android.content.SyncResult)
	 */
	@Override
	public void onPerformSync(Account account, Bundle extras, String authority,
			ContentProviderClient provider, SyncResult syncResult) {
		if (syncSkip == true) {
			System.err.println("Something is wrong and we have been asked to skip the sync, exiting immediately");
			return;
		}

        String emission_host = ConnectionSettings.getConnectURL(mContext);
        System.out.println("About to connect to host "+emission_host);

        String userName = UserProfile.getInstance(mContext).getUserEmail();
        System.out.println("retrieved user name = "+userName);

        if (userName == null || userName.trim().equals("")) {
            System.err.println("Don't have a username, exiting immediately");
            return;
        }
        // First, get a token so that we can make the authorized calls to the server
        String userToken = GoogleAccountManagerAuth.getServerToken(mContext, userName);
		/*
		 * We send almost all pending trips to the server
		 */

		/*
		 * We are going to send over information for all the data in a single JSON object, to avoid overhead.
		 * So we take a quick check to see if the number of entries is zero.
		 */
        BuiltinUserCache biuc = new BuiltinUserCache(mContext);

        try {
			JSONArray entriesToPush = biuc.sync_phone_to_server();
			if (entriesToPush.length() == 0) {
				System.out.println("No data to send, returning early!");
            } else {
				CommunicationHelper.phone_to_server(mContext, userToken, entriesToPush);
				UserCache.TimeQuery tq = getTimeQuery(entriesToPush);
				biuc.clearMessages(tq);
			}
        } catch (JSONException e) {
			Log.e(mContext, TAG, "Error "+e+" while saving converting trips to JSON, skipping all of them");
		} catch (IOException e) {
			Log.e(mContext, TAG, "IO Error "+e+" while posting converted trips to JSON");
		}

		Log.i(mContext, TAG, "Push complete, now pulling");

        /*
         * Now, read all the information from the server. This is in a different try/catch block,
         * because we want to try it even if the push fails.
         */
        try {
            JSONArray entriesReceived = CommunicationHelper.server_to_phone(mContext, userToken);
            biuc.sync_server_to_phone(entriesReceived);
        } catch (JSONException e) {
            Log.e(mContext, TAG, "Error "+e+" while saving converting trips to JSON, skipping all of them");
        } catch (IOException e) {
            Log.e(mContext, TAG, "IO Error "+e+" while posting converted trips to JSON");
        }

		/*
		 * Now, do some validation of the current state and clean it up if necessary. This should
		 * help with issues we have seen in the field where location updates pause mysteriously, or
		 * geofences are never exited.
		 */
        validateAndCleanupState();
    }

    public void validateAndCleanupState() {
        /*
         * Check for being in geofence if in waiting_for_trip_state.
         */
        if (TripDiaryStateMachineIntentService.getState(mContext).equals(mContext.getString(R.string.state_start))) {
            mContext.sendBroadcast(new Intent(mContext.getString(R.string.transition_initialize)));
        } else if (TripDiaryStateMachineIntentService.getState(mContext).equals(
                mContext.getString(R.string.state_waiting_for_trip_start))) {
            // check in geofence
        }
    }

	public Properties getUUIDMap(File privateFileDir) throws FileNotFoundException, IOException {
		File uuidFile = new File(privateFileDir, "sensor-uuid.props");
		Properties uuidMap = new Properties();
		try {
			uuidMap.load(new FileInputStream(uuidFile));
		} catch (IOException e) {
			uuidMap.put(USER, UUID.randomUUID().toString());
			System.out.println("Created UUID for USER");
			for (int i = 0; i < Constants.sensors.length; i++) {
				uuidMap.put(Constants.sensors[i], UUID.randomUUID().toString());
			}
			uuidMap.store(new FileOutputStream(uuidFile), null);
		}
		return uuidMap;
	}

    public static UserCache.TimeQuery getTimeQuery(JSONArray pointList) throws JSONException {
        long start_ts = pointList.getJSONObject(0).getJSONObject("metadata").getLong("write_ts");
        long end_ts = pointList.getJSONObject(pointList.length() - 1).getJSONObject("metadata").getLong("write_ts");
        // This might still have a race in which there are new entries added with the same timestamp as the last
        // entry. Use an id instead? Or manually choose a slightly earlier ts to be on the safe side?
        // TODO: Need to figure out which one to do
		// Start slightly before and end slightly after to make sure that we get all entries
        UserCache.TimeQuery tq = new UserCache.TimeQuery(R.string.metadata_usercache_write_ts,
                start_ts - 1, end_ts + 1);
        return tq;
    }

	/*
	 * We add the parts to the object for each sensor based on the order in:
	 * http://www.cs.berkeley.edu/~stevedh/smap2/archiver.html
	 *
	 * The Metadata name recommendations are from Tyler.
	 * TODO: Check with him on whether these are special or not
	 */
	public JSONObject createTopLevelObject() throws JSONException {
		JSONObject retObject = new JSONObject();
		for (int i = 0; i < Constants.sensors.length; i++) {
			JSONObject sensorObj = new JSONObject();
			/*
			 * Note the / before the name here. That's because this name represents a path.
			 * If you remove it, this won't show up in the tree view of the sMAP server.
			 * Note also that none of the other names require this /
			 */
			// retObject.put(getPath(Constants.sensors[i]), sensorObj);

			JSONObject metadataObj = new JSONObject();
			// All our data is for the E-Mission project
			metadataObj.put("SourceName", projectName);
			metadataObj.put("PointName", Constants.sensors[i]);
			// At this point, we don't know who the user is. Put that into settings?
			sensorObj.put("Metadata", metadataObj);

			JSONObject propertyObject = new JSONObject();
			propertyObject.put("Timezone", java.util.TimeZone.getDefault().getID());
			propertyObject.put("ReadingType", "double");
			sensorObj.put("Properties", propertyObject);

			JSONArray readings = new JSONArray();
			sensorObj.put(READINGS_NAME, readings);

			sensorObj.put("uuid", uuidMap.get(Constants.sensors[i]));
		}
		System.out.println("Returning object skeleton "+retObject);
		return retObject;
	}

	class NotUUIDFileFilter extends Object implements FilenameFilter {
		public boolean accept(File dir, String fileName) {
			if(fileName.contains("uuid")) {
				return false;
			} else {
				return true;
			}
		}
	}

	public void addDataToSmapServer(JSONObject data, String smapHost)
			throws IOException {
		HttpPost msg = new HttpPost(smapHost+"/add/"+ConnectionSettings.getSmapKey(mContext));
		System.out.println("Posting data to "+msg);
		msg.setHeader("Content-Type", "application/json");
		msg.setEntity(new StringEntity(data.toString()));
		AndroidHttpClient connection = AndroidHttpClient.newInstance(projectName);
		HttpResponse response = connection.execute(msg);
		System.out.println("Got response "+response+" with status "+response.getStatusLine());
		connection.close();
	}

	public boolean pushTripsToServer(String emissionServer, JSONObject data)
			throws IOException {
		HttpPost msg = new HttpPost(emissionServer+"/tripManager/storeSensedTrips");

		System.out.println("Posting data to "+msg);
		msg.setHeader("Content-Type", "application/json");
		msg.setEntity(new StringEntity(data.toString()));
		AndroidHttpClient connection = AndroidHttpClient.newInstance(projectName);
		HttpResponse response = connection.execute(msg);
		System.out.println("Got response "+response+" with status "+response.getStatusLine());
		connection.close();
        if (response.getStatusLine().getStatusCode() == 200) {
            return true;
        } else {
            return false;
        }
	}

    /*
	public String getPath(String serviceName) {
		return "/"+userName+"/"+serviceName;
	}
	*/
}


text:
package com.github.coolcool.sloth.lianjiadb.mapper;
import java.util.*;
import com.github.coolcool.sloth.lianjiadb.model.Area;
import javax.annotation.Generated;
import org.apache.ibatis.annotations.*;

@Generated(
		value = {
				"https://github.com/coolcooldee/sloth",
				"Sloth version:1.0"
		},
		comments = "This class is generated by Sloth"
)
public interface AreaMapper{

	@Select("SELECT COUNT(*) FROM area ")
	Integer count();

	@Select("SELECT * FROM area WHERE id = #{primaryKey} LIMIT 1 ")
	Area getByPrimaryKey(@Param("primaryKey") Object primaryKey);

	@Delete("DELETE FROM area WHERE id = #{primaryKey} ")
	Integer deleteByPrimaryKey(@Param("primaryKey") Object primaryKey);

	@Update({
			"UPDATE area SET id=#{id}, name=#{name}, code=#{code}, link=#{link}, parentsId=#{parentsId}, parentsName=#{parentsName}, parentsCode=#{parentsCode}, level=#{level} where id = #{id}"
	})
	Integer updateByPrimaryKey(Area area);

	@Insert({
			"INSERT INTO area (id, name, code, link, parentsId, parentsName, parentsCode, level)",
			"VALUE (#{id}, #{name}, #{code}, #{link}, #{parentsId}, #{parentsName}, #{parentsCode}, #{level}) ON DUPLICATE KEY UPDATE id=#{id}"
	})
	Integer insert(Area area);

	@Select("SELECT * FROM area LIMIT 10 ")
	List<Area> list();

	@Select("SELECT * FROM area ")
	List<Area> listAll();

	@Select("SELECT * FROM area where  parentsId=#{parentsId}")
	List<Area> listOneLevelChilden(@Param("parentsId") int parentsId);

	@Select("SELECT * FROM area where  parentsId in (select id from area where parentsId=#{parentsId})")
	List<Area> listTwoLevelChilden(@Param("parentsId") int parentsId);

	@Select("SELECT * FROM area LIMIT #{start}, #{step}")
	List<Area> page(@Param("start") int start, @Param("step") int step );

	@Select("SELECT `AUTO_INCREMENT` as number FROM  INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'test' AND TABLE_NAME = 'area'")
	Integer increment();

}