text:
package cmwell.common.formats

import cmwell.domain._
import cmwell.stats.Stats.Settings
import cmwell.common._
import cmwell.common.BulkCommand
import cmwell.common.WriteCommand
import cmwell.common.MergedInfotonCommand
import com.typesafe.scalalogging.LazyLogging
import com.fasterxml.jackson.core._

/**
 * Created by gilad on 2/26/15.
 */
object JsonSerializer0 extends AbstractJsonSerializer with LazyLogging {

  private def decodeFieldsWithParser(parser:JsonParser):Map[String, Set[FieldValue]] = {
    assume(parser.nextToken()== JsonToken.START_OBJECT, s"expected start of 'fields' object\n${parser.getCurrentLocation.toString}")
    val fields = collection.mutable.Map[String, collection.mutable.Set[FieldValue]]()
    while(parser.nextToken() != JsonToken.END_OBJECT) {
      val fieldName = parser.getCurrentName
      assume(parser.nextToken()==JsonToken.START_ARRAY, s"expected START_ARARY token\n${parser.getCurrentLocation.toString}")
      val values = collection.mutable.Set[FieldValue]()

      var jType = parser.nextToken()
      while(jType != JsonToken.END_ARRAY) {
        jType match {
          case JsonToken.VALUE_NUMBER_INT | JsonToken.VALUE_NUMBER_FLOAT => values.add(getFieldValue(parser))
          case JsonToken.VALUE_STRING => {
            val v: String = parser.getText
            require(!v.isEmpty)
            val fv: FieldValue = v.head match {
              case 'd' => FDate(v.tail)
              case 'f' => FFloat(v.tail.toFloat)
              case 'g' => FDouble(v.tail.toDouble)
              case 'h' => FBigDecimal(BigDecimal(v.tail).underlying())
              case 'i' => FInt(v.tail.toInt)
              case 'j' => FLong(v.tail.toLong)
              case 'k' => FBigInt(BigInt(v.tail).underlying())
              case 'r' => FReference(v.tail)
              case 's' => FString(v.tail)
              case 'x' => {
                val arr = v.tail.split('\n')
                val (uri,value) = (arr(1),arr.drop(2).mkString("\n"))
                FExternal(value,uri)
              }
              case _ => ???
            }
            values.add(fv)
          }
          case JsonToken.VALUE_TRUE => values.add(FBoolean(true))
          case JsonToken.VALUE_FALSE => values.add(FBoolean(false))
          case _ => ??? // added this to suppress build warning. (added by Michael)
        }
        jType = parser.nextToken()
      }
      fields.put(fieldName, values)
    }
    fields.map{case (k, v) => (k, v.toSet)}.toMap
  }

  private def getFieldValue(jp: JsonParser): FieldValue = jp.getNumberType match {
    case JsonParser.NumberType.INT         => FInt(jp.getIntValue)
    case JsonParser.NumberType.LONG        => FLong(jp.getLongValue)
    case JsonParser.NumberType.BIG_INTEGER => FBigInt(jp.getBigIntegerValue)
    case JsonParser.NumberType.FLOAT       => FFloat(jp.getFloatValue)
    case JsonParser.NumberType.DOUBLE      => FDouble(jp.getDoubleValue)
    case JsonParser.NumberType.BIG_DECIMAL => FBigDecimal(jp.getDecimalValue)
  }

  /**
   *
   * @param jsonParser
   * @return
   */
  private def decodeInfotonWithParser(jsonParser:JsonParser):Infoton = {

      // expecting start of json object
    assume(jsonParser.nextToken()== JsonToken.START_OBJECT, s"expected start of infoton object\n${jsonParser.getCurrentLocation.toString}")

    assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "type".equals(jsonParser.getCurrentName()), s"expected 'type' field name\n${jsonParser.getCurrentLocation.toString}")
    assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'type' field\n${jsonParser.getCurrentLocation.toString}")
    val infotonType = jsonParser.getText()
      // Start of system object
    assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "system".equals(jsonParser.getCurrentName()), s"expected 'system' field name\n${jsonParser.getCurrentLocation.toString}")
    assume(jsonParser.nextToken()== JsonToken.START_OBJECT, s"expected start of 'system' object\n${jsonParser.getCurrentLocation.toString}")

    assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "path".equals(jsonParser.getCurrentName()), s"expected 'path' field name\n${jsonParser.getCurrentLocation.toString}")
    assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'path' field\n${jsonParser.getCurrentLocation.toString}")
    val path = jsonParser.getText()

    assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "lastModified".equals(jsonParser.getCurrentName()), s"expected 'lastModified' field name\n${jsonParser.getCurrentLocation.toString}")
    assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'lastModified' field\n${jsonParser.getCurrentLocation.toString}")
    val lastModified = dateFormatter.parseDateTime(jsonParser.getText())

    assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "uuid".equals(jsonParser.getCurrentName()), s"expected 'uuid' field name\n${jsonParser.getCurrentLocation.toString}")
    assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'uuid' field\n${jsonParser.getCurrentLocation.toString}")
    val uuid = jsonParser.getText()

    assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "parent".equals(jsonParser.getCurrentName()), s"expected 'parent' field name\n${jsonParser.getCurrentLocation.toString}")
    assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'parent' field\n${jsonParser.getCurrentLocation.toString}")
    val parent = jsonParser.getText()

      // End of system object
    assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of 'system' object\n${jsonParser.getCurrentLocation.toString}")

    var fields:Option[Map[String, Set[FieldValue]]] = None

    val nextToken = jsonParser.nextToken().id() match {
      case JsonTokenId.ID_FIELD_NAME => jsonParser.getText() match {
        case "fields" =>
          fields = Some(decodeFieldsWithParser(jsonParser))
          jsonParser.nextToken()
        case _ => jsonParser.getCurrentToken
      }
      case _ => jsonParser.getCurrentToken
    }
    val dc = SettingsHelper.dataCenter
      // the rest is up to the infoton's type
    infotonType match {
      case "ObjectInfoton" =>
        //expecting end of json object
        assume(nextToken== JsonToken.END_OBJECT, s"expected end of json object\n${jsonParser.getCurrentLocation.toString}")
        ObjectInfoton(path, dc, None, lastModified, fields)
      case "LinkInfoton" =>
        assume(nextToken == JsonToken.FIELD_NAME && "linkTo".equals(jsonParser.getCurrentName()), s"expected 'linkTo' field name\n${jsonParser.getCurrentLocation.toString}")
        assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'linkTo' field\n${jsonParser.getCurrentLocation.toString}")
        val linkTo = jsonParser.getText()

        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "linkType".equals(jsonParser.getCurrentName()), s"expected 'linkType' field name\n${jsonParser.getCurrentLocation.toString}")
        assume(jsonParser.nextToken()==JsonToken.VALUE_NUMBER_INT, s"expected value for 'linkType' field\n${jsonParser.getCurrentLocation.toString}")
        val linkType = jsonParser.getIntValue

        //expecting end of json object
        assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of json object\n${jsonParser.getCurrentLocation.toString}")
        LinkInfoton(path, dc, None, lastModified, fields, linkTo, linkType)
      case "FileInfoton" =>
        var fileContent:Option[FileContent] = None
        if(nextToken.id == JsonTokenId.ID_FIELD_NAME){
          assume(nextToken == JsonToken.FIELD_NAME && "content".equals(jsonParser.getCurrentName()), s"expected 'content' field name\n${jsonParser.getCurrentLocation.toString}")
          // expecting start of 'content' object
          assume(jsonParser.nextToken()== JsonToken.START_OBJECT, s"expected start of 'content' object\n${jsonParser.getCurrentLocation.toString}")
            // expecting 'mimetype' fields
          assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "mimeType".equals(jsonParser.getCurrentName()), s"expected 'mimeType' field name\n${jsonParser.getCurrentLocation.toString}")
          assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'mimeType' field\n${jsonParser.getCurrentLocation.toString}")
          val mimeType = jsonParser.getText()

            //expecting either 'data|base64-data' field or skipping to length
          assume(jsonParser.nextToken()==JsonToken.FIELD_NAME, s"expected field name token, either 'data|base64' or 'content'\n${jsonParser.getCurrentLocation.toString}")
          var data:Option[Array[Byte]] = None
          jsonParser.getCurrentName match {
            case "data" =>
              assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'data' field\n${jsonParser.getCurrentLocation.toString}")
              val charset = mimeType.lastIndexOf("charset=") match {
                case i if (i != -1) => mimeType.substring(i + 8).trim
                case _ => "UTF-8"
              }
              data = Some(jsonParser.getText.getBytes(charset))
                // skipping to next token
              assume(jsonParser.nextToken()==JsonToken.FIELD_NAME,  s"expected 'length' field name token\n${jsonParser.getCurrentLocation.toString}")
            case "base64-data" =>
              assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'base64-data' field\n${jsonParser.getCurrentLocation.toString}")
              data = Some(jsonParser.getBinaryValue)
                // skipping to next token
              assume(jsonParser.nextToken()==JsonToken.FIELD_NAME ,s"expected 'length' field name token\n${jsonParser.getCurrentLocation.toString}")

          }
          assume("length".equals(jsonParser.getCurrentName), s"expected 'length' field name token\n${jsonParser.getCurrentLocation.toString}")
            // expecting 'length' field
          assume(jsonParser.nextToken()==JsonToken.VALUE_NUMBER_INT, s"expected value for 'length' field\n${jsonParser.getCurrentLocation.toString}")
          val dataLength = jsonParser.getIntValue()

          //expecting end of content object
          assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of json object\n${jsonParser.getCurrentLocation.toString}")

          //expecting end of infoton object
          assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of json object\n${jsonParser.getCurrentLocation.toString}")

          fileContent = Some(FileContent(data, mimeType, dataLength))
        } else {
          //expecting end of infoton object
          assume(nextToken == JsonToken.END_OBJECT, s"expected end of json object\n${jsonParser.getCurrentLocation.toString}")
        }

        FileInfoton(path, dc, None, lastModified, fields, fileContent)
    }
  }

  def decodeCommandWithParser(jsonParser:JsonParser):Command = {
      // expecting type field
    assume(jsonParser.getCurrentToken()==JsonToken.FIELD_NAME && "type".equals(jsonParser.getCurrentName()), s"expected 'type' field name\n${jsonParser.getCurrentLocation.toString}")
    assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'type' field\n${jsonParser.getCurrentLocation.toString}")
    val commandType = jsonParser.getText()
    var command:Command = null
    commandType match {
      case "WriteCommand" =>
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "infoton".equals(jsonParser.getCurrentName()), s"expected 'infoton' field name\n${jsonParser.getCurrentLocation.toString}")
        val infoton = decodeInfotonWithParser(jsonParser)
        command = WriteCommand(infoton)
        //expecting end of command object
        assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of command object\n${jsonParser.getCurrentLocation.toString}")
      case "BulkCommand" =>
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "commands".equals(jsonParser.getCurrentName()), s"expected 'commands' field name\n${jsonParser.getCurrentLocation.toString}")
        val commands = new collection.mutable.ListBuffer[Command]()
        assume(jsonParser.nextToken()==JsonToken.START_ARRAY, s"expected start array token for 'commands' object\n${jsonParser.getCurrentLocation.toString}")
        while(jsonParser.nextToken() != JsonToken.END_ARRAY){
          assume(jsonParser.nextToken()==JsonToken.FIELD_NAME, s"expected field ${jsonParser.getCurrentLocation.toString}")
          commands += decodeCommandWithParser(jsonParser)
        }
        command = BulkCommand(commands.toList)
        //expecting end of command object
        assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of command object\n${jsonParser.getCurrentLocation.toString}")
      case "MergedInfotonCommand" =>
          // expecting either previousInfoton field or currentInfoton field
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME, s"expected field token for either 'previousInfoton' or 'currentInfoton'\n${jsonParser.getCurrentLocation.toString}")
        var previousInfoton:Option[(String , Long) ] = None
        if("previousInfoton".equals(jsonParser.getCurrentName)) {
          assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'previousInfoton' field\n${jsonParser.getCurrentLocation.toString}")
          val prevUuid = jsonParser.getText
          // TODO backward supporting tlogs that have commands without the infoton size field. Remove when not needed any more
          val nextToken = jsonParser.nextToken()
          assume(nextToken==JsonToken.FIELD_NAME, s"expected value for 'previousInfotonSize' field or field token for 'currentInfoton'\n${jsonParser.getCurrentLocation.toString}")
          if("previousInfotonSize".equals(jsonParser.getCurrentName)) {
            assume(jsonParser.nextToken()==JsonToken.VALUE_NUMBER_INT, s"expected value for 'previousInfotonSize' field\n${jsonParser.getCurrentLocation.toString}")
            previousInfoton = Some( (prevUuid, jsonParser.getLongValue) )
            // skipping to currentInfoton token
            assume(jsonParser.nextToken()==JsonToken.FIELD_NAME, s"expected field token for 'currentInfoton'\n${jsonParser.getCurrentLocation.toString}")
          }
        }
        assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'currentInfoton' field\n${jsonParser.getCurrentLocation.toString}")
        val currentInfoton = jsonParser.getText

        // TODO backward supporting tlogs that have commands without the infoton size field. Remove when not needed any more
        val nextToken = jsonParser.nextToken()
        if(nextToken==JsonToken.FIELD_NAME) {
          assume(jsonParser.nextToken()==JsonToken.VALUE_NUMBER_INT, s"expected value for 'currentInfotonSize' field\n${jsonParser.getCurrentLocation.toString}")
          val currentInfotonSize = jsonParser.getLongValue
          command = MergedInfotonCommand(previousInfoton, (currentInfoton , currentInfotonSize) )
          //expecting end of command object
          assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of command object\n${jsonParser.getCurrentLocation.toString}")
        } else {
          assume(nextToken == JsonToken.END_OBJECT, s"expected end of command object\n${jsonParser.getCurrentLocation.toString}")
          command = MergedInfotonCommand(previousInfoton, (currentInfoton, 0L))
        }

      case "DeleteAttributesCommand" =>
          // expecting 'path' field
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "path".equals(jsonParser.getCurrentName()), "expected 'path' field name\\n${jsonParser.getCurrentLocation.toString}")
        assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'path' field\n${jsonParser.getCurrentLocation.toString}")
        val path = jsonParser.getText
          // expecting 'fields' object
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "fields".equals(jsonParser.getCurrentName()), s"expected 'fields' field name token\n${jsonParser.getCurrentLocation.toString}")
        val fields = decodeFieldsWithParser(jsonParser)
          // expecting 'lastModified' field
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "lastModified".equals(jsonParser.getCurrentName()), "expected 'lastModified' field name\\n${jsonParser.getCurrentLocation.toString}")
        assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'lastModified' field\n${jsonParser.getCurrentLocation.toString}")
        val lastModified = dateFormatter.parseDateTime(jsonParser.getText())
        command = DeleteAttributesCommand(path, fields, lastModified)
        //expecting end of command object
        assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of command object\n${jsonParser.getCurrentLocation.toString}")
      case "DeletePathCommand" =>
        // expecting 'path' field
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "path".equals(jsonParser.getCurrentName()), "expected 'path' field name\\n${jsonParser.getCurrentLocation.toString}")
        assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'path' field\n${jsonParser.getCurrentLocation.toString}")
        val path = jsonParser.getText
        // expecting 'lastModified' field
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "lastModified".equals(jsonParser.getCurrentName()), "expected 'lastModified' field name\\n${jsonParser.getCurrentLocation.toString}")
        assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'lastModified' field\n${jsonParser.getCurrentLocation.toString}")
        val lastModified = dateFormatter.parseDateTime(jsonParser.getText())
        command = DeletePathCommand(path, lastModified)
        //expecting end of command object
        assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of command object\n${jsonParser.getCurrentLocation.toString}")
      case "UpdatePathCommand" =>
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "path".equals(jsonParser.getCurrentName()), "expected 'path' field name\\n${jsonParser.getCurrentLocation.toString}")
        assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'path' field\n${jsonParser.getCurrentLocation.toString}")
        val path = jsonParser.getText
        // expecting 'deleteFields' object
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "deleteFields".equals(jsonParser.getCurrentName()), s"expected 'deleteFields' field name token\n${jsonParser.getCurrentLocation.toString}")
        val deleteFields = decodeFieldsWithParser(jsonParser)
        // expecting 'updateFields' object
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "updateFields".equals(jsonParser.getCurrentName()), s"expected 'updateFields' field name token\n${jsonParser.getCurrentLocation.toString}")
        val updateFields = decodeFieldsWithParser(jsonParser)
        // expecting 'lastModified' field
        assume(jsonParser.nextToken()==JsonToken.FIELD_NAME && "lastModified".equals(jsonParser.getCurrentName()), "expected 'lastModified' field name\\n${jsonParser.getCurrentLocation.toString}")
        assume(jsonParser.nextToken()==JsonToken.VALUE_STRING, s"expected value for 'lastModified' field\n${jsonParser.getCurrentLocation.toString}")
        val lastModified = dateFormatter.parseDateTime(jsonParser.getText())
        command = UpdatePathCommand(path, deleteFields, updateFields,lastModified)
        //expecting end of command object
        assume(jsonParser.nextToken()== JsonToken.END_OBJECT, s"expected end of command object\n${jsonParser.getCurrentLocation.toString}")

    }

    command
  }
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syll. fung. (Abellini) 3: 685 (1884)

#### Original name
Peziza hispidula Schrad.

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
package org.apache.continuum.release.distributed.manager;

import org.apache.continuum.configuration.BuildAgentConfigurationException;
import org.apache.continuum.model.repository.LocalRepository;
import org.apache.continuum.release.model.PreparedRelease;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.release.ContinuumReleaseException;
import org.apache.maven.shared.release.ReleaseResult;

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

public interface DistributedReleaseManager
{
    Map getReleasePluginParameters( int projectId, String pomFilename )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    List<Map<String, String>> processProject( int projectId, String pomFilename, boolean autoVersionSubmodules )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    String releasePrepare( Project project, Properties releaseProperties, Map<String, String> releaseVersion,
                           Map<String, String> developmentVersion, Map<String, String> environments, String username )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    ReleaseResult getReleaseResult( String releaseId )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    Map<String, Object> getListener( String releaseId )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    void removeListener( String releaseId )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    @Deprecated
    String getPreparedReleaseName( String releaseId )
        throws ContinuumReleaseException;

    Map<String, String> getPreparedReleases( String groupId, String artifactId )
        throws ContinuumReleaseException;

    void releasePerform( int projectId, String releaseId, String goals, String arguments, boolean useReleaseProfile,
                         LocalRepository repository, String username )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    String releasePerformFromScm( int projectId, String goals, String arguments, boolean useReleaseProfile,
                                  LocalRepository repository, String scmUrl, String scmUsername, String scmPassword,
                                  String scmTag, String scmTagBase, Map environments, String username )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    void releaseRollback( String releaseId, int projectId )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    String releaseCleanup( String releaseId )
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    List<Map<String, Object>> getAllReleasesInProgress()
        throws ContinuumReleaseException, BuildAgentConfigurationException;

    String getDefaultBuildagent( int projectId );

    PreparedRelease getPreparedRelease( String releaseId, String releaseType )
        throws ContinuumReleaseException;
}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="HandheldFriendly" content="True">
        <meta name="MobileOptimized" content="320">
        <meta name="viewport" content="width=device-width, initial-scale=1 user-scalable=no,maximum-scale=1">

        <title>Curtis Barlow-Wilkes</title>
        <link href="//fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

        <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Open+Sans|Lobster+Two|Gentium+Basic">

        <link href="css/bootstrap.css" rel="stylesheet">
        <link href="css/styles.css" rel="stylesheet">

                        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mainNavBar">

                        </button>
                        Curtis Barlow-Wilkes

 Home

 Projects

                                 Connect

 Github

 Facebook

 Google+

 LinkedIn

 Email

Saurus-Othello

Star me on github!

 Source


text:
package nl.coenvl.sam.exceptions;

/**
 * InvalidDomainException
 *
 * @author leeuwencjv
 * @version 0.1
 * @since 7 feb. 2014
 *
 */
public class InvalidDomainException extends RuntimeException {

    /**
     *
     */
    private static final long serialVersionUID = -5736784528951113460L;

}


text:
import gc
import sys
import os
import math
import unittest

import IECore

class LinkedSceneTest( unittest.TestCase ) :

	@staticmethod
	def compareBBox( box1, box2 ):
		errorTolerance = IECore.V3d(1e-5, 1e-5, 1e-5)
		boxTmp = IECore.Box3d( box1.min - errorTolerance, box1.max + errorTolerance )
		if not boxTmp.contains( box2 ):
			return False
		boxTmp = IECore.Box3d( box2.min - errorTolerance, box2.max + errorTolerance )
		if not boxTmp.contains( box1 ):
			return False
		return True

	def testSupportedExtension( self ) :
		self.assertTrue( "lscc" in IECore.SceneInterface.supportedExtensions() )
		self.assertTrue( "lscc" in IECore.SceneInterface.supportedExtensions( IECore.IndexedIO.OpenMode.Read ) )
		self.assertTrue( "lscc" in IECore.SceneInterface.supportedExtensions( IECore.IndexedIO.OpenMode.Write ) )
		self.assertTrue( "lscc" in IECore.SceneInterface.supportedExtensions( IECore.IndexedIO.OpenMode.Write + IECore.IndexedIO.OpenMode.Read ) )
		self.assertFalse( "lscc" in IECore.SceneInterface.supportedExtensions( IECore.IndexedIO.OpenMode.Append ) )

	def testFactoryFunction( self ):
		# test Write factory function
		m = IECore.SceneInterface.create( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Write )
		self.assertTrue( isinstance( m, IECore.LinkedScene ) )
		self.assertEqual( m.fileName(), "/tmp/test.lscc" )
		self.assertRaises( RuntimeError, m.readBound, 0.0 )
		del m
		# test Read factory function
		m = IECore.SceneInterface.create( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Read )
		self.assertTrue( isinstance( m, IECore.LinkedScene ) )
		self.assertEqual( m.fileName(), "/tmp/test.lscc" )
		m.readBound( 0.0 )

	def testConstructors( self ):

		# test Read from a previously opened scene.
		m = IECore.SceneCache( "test/IECore/data/sccFiles/animatedSpheres.scc", IECore.IndexedIO.OpenMode.Read )
		l = IECore.LinkedScene( m )
		# test Write mode
		m = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Write )
		self.assertTrue( isinstance( m, IECore.LinkedScene ) )
		self.assertEqual( m.fileName(), "/tmp/test.lscc" )
		self.assertRaises( RuntimeError, m.readBound, 0.0 )
		del m
		# test Read mode
		m = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Read )
		self.assertTrue( isinstance( m, IECore.LinkedScene ) )
		self.assertEqual( m.fileName(), "/tmp/test.lscc" )
		m.readBound( 0.0 )

	def testAppendRaises( self ) :
		self.assertRaises( RuntimeError, IECore.SceneInterface.create, "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Append )
		self.assertRaises( RuntimeError, IECore.LinkedScene, "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Append )

	def testReadNonExistentRaises( self ) :
		self.assertRaises( RuntimeError, IECore.LinkedScene, "iDontExist.lscc", IECore.IndexedIO.OpenMode.Read )

	def testLinkAttribute( self ):

		self.assertEqual( IECore.LinkedScene.linkAttribute, "sceneInterface:link" )

		m = IECore.SceneCache( "test/IECore/data/sccFiles/animatedSpheres.scc", IECore.IndexedIO.OpenMode.Read )
		attr = IECore.LinkedScene.linkAttributeData( m )
		expectedAttr = IECore.CompoundData(
			{
				"fileName": IECore.StringData("test/IECore/data/sccFiles/animatedSpheres.scc"),
				"root": IECore.InternedStringVectorData( [] )
			}
		)
		self.assertEqual( attr, expectedAttr )

		A = m.child("A")
		attr = IECore.LinkedScene.linkAttributeData( A )
		expectedAttr = IECore.CompoundData(
			{
				"fileName": IECore.StringData("test/IECore/data/sccFiles/animatedSpheres.scc"),
				"root": IECore.InternedStringVectorData( [ 'A' ] )
			}
		)
		self.assertEqual( attr, expectedAttr )

		A = m.child("A")
		attr = IECore.LinkedScene.linkAttributeData( A, 10.0 )
		expectedAttr['time'] = IECore.DoubleData(10.0)
		self.assertEqual( attr, expectedAttr )

	def testWriting( self ):

		generateTestFiles = False	# change this to True to recreate the LinkedScene files for other tests.
		testFilesSuffix = "_newTags"
		if generateTestFiles :
			outputPath = "test/IECore/data/sccFiles"
		else :
			outputPath = "/tmp"

		m = IECore.SceneCache( "test/IECore/data/sccFiles/animatedSpheres.scc", IECore.IndexedIO.OpenMode.Read )
		A = m.child("A")

		l = IECore.LinkedScene( os.path.join(outputPath,"instancedSpheres%s.lscc"%testFilesSuffix), IECore.IndexedIO.OpenMode.Write )
		i0 = l.createChild("instance0")
		i0.writeLink( m )
		i1 = l.createChild("instance1")
		i1.writeLink( m )
		i1.writeAttribute( "testAttr", IECore.StringData("test"), 0 )
		i1.writeTransform( IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1, 0, 0 ) ) ), 0.0 )
		i2 = l.createChild("instance2")
		i2.writeLink( A )
		i2.writeTransform( IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 2, 0, 0 ) ) ), 0.0 )
		self.assertRaises( RuntimeError, i2.createChild, "cannotHaveChildrenAtLinks" )
		i2.writeTags( ["canHaveTagsAtLinks"] )
		self.assertRaises( RuntimeError, i2.writeObject, IECore.SpherePrimitive( 1 ), 0.0 )  # cannot save objects at link locations.
		b1 = l.createChild("branch1")
		b1.writeObject( IECore.SpherePrimitive( 1 ), 0.0 )
		self.assertRaises( RuntimeError, b1.writeLink, A )
		b2 = l.createChild("branch2")
		c2 = b2.createChild("child2")
		self.assertRaises( RuntimeError, b2.writeLink, A )
		del i0, i1, i2, l, b1, b2, c2

		l = IECore.LinkedScene( os.path.join(outputPath,"instancedSpheres%s.lscc"%testFilesSuffix), IECore.IndexedIO.OpenMode.Read )

		self.assertEqual( l.numBoundSamples(), 4 )
		self.assertEqual( set(l.childNames()), set(['instance0','instance1','instance2','branch1','branch2']) )
		i0 = l.child("instance0")
		self.assertEqual( i0.numBoundSamples(), 4 )
		self.failUnless( LinkedSceneTest.compareBBox( i0.readBoundAtSample(0), IECore.Box3d( IECore.V3d( -1,-1,-1 ), IECore.V3d( 2,2,1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i0.readBoundAtSample(1), IECore.Box3d( IECore.V3d( -1,-1,-1 ), IECore.V3d( 3,3,1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i0.readBoundAtSample(2), IECore.Box3d( IECore.V3d( -2,-1,-2 ), IECore.V3d( 4,5,2 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i0.readBoundAtSample(3), IECore.Box3d( IECore.V3d( -3,-1,-3 ), IECore.V3d( 4,6,3 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i0.readBound(0), IECore.Box3d( IECore.V3d( -1,-1,-1 ), IECore.V3d( 2,2,1 ) ) ) )

		A = i0.child("A")
		self.failUnless( LinkedSceneTest.compareBBox( A.readBoundAtSample(0), IECore.Box3d(IECore.V3d( -1,-1,-1 ), IECore.V3d( 1,1,1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( A.readBoundAtSample(1), IECore.Box3d(IECore.V3d( -1,-1,-1 ), IECore.V3d( 1,1,1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( A.readBoundAtSample(2), IECore.Box3d(IECore.V3d( 0,-1,-1 ), IECore.V3d( 2,1,1 ) ) ) )
		self.assertEqual( i0.readTransform( 0 ), IECore.M44dData( IECore.M44d() ) )

		i1 = l.child("instance1")
		self.assertEqual( i1.numBoundSamples(), 4 )
		self.failUnless( LinkedSceneTest.compareBBox( i1.readBoundAtSample(0), IECore.Box3d( IECore.V3d( -1,-1,-1 ), IECore.V3d( 2,2,1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i1.readBoundAtSample(2), IECore.Box3d( IECore.V3d( -2,-1,-2 ), IECore.V3d( 4,5,2 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i1.readBoundAtSample(3), IECore.Box3d( IECore.V3d( -3,-1,-3 ), IECore.V3d( 4,6,3 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i1.readBound(0), IECore.Box3d( IECore.V3d( -1,-1,-1 ), IECore.V3d( 2,2,1 ) ) ) )
		self.assertEqual( i1.readTransform( 0 ), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1, 0, 0 ) ) ) )
		self.assertEqual( i1.readAttribute( "testAttr", 0 ), IECore.StringData("test") )

		i2 = l.child("instance2")
		self.assertEqual( i2.numBoundSamples(), 3 )
		self.failUnless( LinkedSceneTest.compareBBox( i2.readBoundAtSample(0), IECore.Box3d(IECore.V3d( -1,-1,-1 ), IECore.V3d( 1,1,1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i2.readBoundAtSample(1), IECore.Box3d(IECore.V3d( -1,-1,-1 ), IECore.V3d( 1,1,1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( i2.readBoundAtSample(2), IECore.Box3d(IECore.V3d( 0,-1,-1 ), IECore.V3d( 2,1,1 ) ) ) )
		self.assertEqual( i2.readTransform( 0 ), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 2, 0, 0 ) ) ) )
		self.assertTrue( i2.hasTag( "canHaveTagsAtLinks", IECore.SceneInterface.TagFilter.EveryTag ) )
		self.assertTrue( l.hasTag( "canHaveTagsAtLinks", IECore.SceneInterface.TagFilter.EveryTag ) )	# tags propagate up
		self.assertTrue( i2.child("a").hasTag( "canHaveTagsAtLinks", IECore.SceneInterface.TagFilter.EveryTag ) )		# tags at link locations propagate down as well

		self.assertEqual( l.scene( [ 'instance0' ] ).path(), [ 'instance0' ] )
		self.assertEqual( l.scene( [ 'instance0', 'A' ] ).path(), [ 'instance0', 'A' ] )
		self.assertEqual( i0.path(), [ 'instance0' ] )

		# test saving a two level LinkedScene
		l2 = IECore.LinkedScene( os.path.join(outputPath,"environment%s.lscc"%testFilesSuffix), IECore.IndexedIO.OpenMode.Write )
		base = l2.createChild("base")
		t1 = base.createChild("test1")
		t1.writeLink( l )
		t2 = base.createChild("test2")
		t2.writeLink( i0 )
		t3 = base.createChild("test3")
		t3.writeLink( i1 )
		t4 = base.createChild("test4")
		t4.writeLink( i2 )
		t5 = base.createChild("test5")
		t5.writeLink( A )
		del l2, t1, t2, t3, t4, t5

	def testWriteLinkAnimatedTransform( self ):

		messageHandler = IECore.CapturingMessageHandler()
		with messageHandler :

			m = IECore.SceneCache( "test/IECore/data/sccFiles/animatedSpheres.scc", IECore.IndexedIO.OpenMode.Read )

			l = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Write )
			i0 = l.createChild("instance0")
			i0.writeLink( m )

			# this was causing a problem upon deleting l, as the first transform sample doesn't coincide with the
			# first bound sample in the link
			i0.writeTransform( IECore.M44dData( IECore.M44d() ), 5.0 )
			i0.writeTransform( IECore.M44dData( IECore.M44d() ), 6.0 )

			del i0, l, m

		for messageInfo in messageHandler.messages:
			if not messageInfo.message.startswith( "Detected ancestor tags" ) :
				self.fail( messageInfo.message )

	def testTimeRemapping( self ):

		m = IECore.SceneCache( "test/IECore/data/sccFiles/animatedSpheres.scc", IECore.IndexedIO.OpenMode.Read )

		l = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Write )
		# save animated spheres with double the speed and with offset, using less samples (time remapping)
		i0 = l.createChild("instance0")
		i0.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 0.0 ), 1.0 )
		i0.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 3.0 ), 2.0 )
		# save animated spheres with same speed and with offset, same samples (time remapping is identity)
		i1 = l.createChild("instance1")
		i1.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 0.0 ), 1.0 )
		i1.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 1.0 ), 2.0 )
		i1.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 2.0 ), 3.0 )
		i1.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 3.0 ), 4.0 )
		# save animated spheres with half the speed, adding more samples to a range of the original (time remapping)
		i2 = l.createChild("instance2")
		i2.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 0.0 ), 0.0 )
		i2.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 0.5 ), 1.0 )
		i2.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 1.0 ), 2.0 )

		del i0, i1, i2, l

		l = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Read )
		self.assertEqual( l.numBoundSamples(), 5 )
		self.assertEqual( l.hasAttribute( "sceneInterface:link.time" ), False )
		i0 = l.child("instance0")

		self.assertEqual( i0.hasAttribute( "sceneInterface:link.time" ), True )
		self.assertEqual( i0.readAttribute( "sceneInterface:link.time", 1 ).value, 0 )
		self.assertEqual( i0.readAttribute( "sceneInterface:link.time", 2 ).value, 3 )

		self.assertEqual( i0.numBoundSamples(), 2 )
		self.assertEqual( i0.numTransformSamples(), 1 )
		self.assertEqual( i0.readTransformAtSample(0), IECore.M44dData() )
		A0 = i0.child("A")
		self.assertEqual( A0.hasAttribute( "sceneInterface:link.time" ), False )

		self.assertEqual( A0.numBoundSamples(), 2 )
		self.assertEqual( A0.numTransformSamples(), 2 )
		self.failUnless( LinkedSceneTest.compareBBox( A0.readBoundAtSample(0), IECore.Box3d(IECore.V3d( -1,-1,-1 ), IECore.V3d( 1,1,1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( A0.readBoundAtSample(1), IECore.Box3d(IECore.V3d( 0,-1,-1 ), IECore.V3d( 2,1,1 ) ) ) )
		self.assertEqual( A0.readTransformAtSample(0), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1, 0, 0 ) ) ) )
		self.assertEqual( A0.readTransformAtSample(1), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 2, 0, 0 ) ) ) )
		i1 = l.child("instance1")

		self.assertEqual( i1.hasAttribute( "sceneInterface:link.time" ), True )
		self.assertEqual( i1.readAttribute( "sceneInterface:link.time", 1 ).value, 0 )
		self.assertEqual( i1.readAttribute( "sceneInterface:link.time", 2 ).value, 1 )
		self.assertEqual( i1.readAttribute( "sceneInterface:link.time", 3 ).value, 2 )
		self.assertEqual( i1.readAttribute( "sceneInterface:link.time", 4 ).value, 3 )

		self.assertEqual( i1.numBoundSamples(), 4 )
		self.assertEqual( i1.numTransformSamples(), 1 )
		A1 = i1.child("A")
		self.assertEqual( A1.numTransformSamples(), 4 )
		self.assertEqual( A1.readTransformAtSample(0), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1, 0, 0 ) ) ) )
		self.assertEqual( A1.readTransformAtSample(1), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 2, 0, 0 ) ) ) )
		self.assertEqual( A1.readTransformAtSample(2), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 2, 0, 0 ) ) ) )
		self.assertEqual( A1.readTransformAtSample(3), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 2, 0, 0 ) ) ) )

		self.assertEqual( A1.hasAttribute( "sceneInterface:link.time" ), False )

		i2 = l.child("instance2")

		self.assertEqual( i2.hasAttribute( "sceneInterface:link.time" ), True )
		self.assertEqual( i2.readAttribute( "sceneInterface:link.time", 0 ).value, 0 )
		self.assertEqual( i2.readAttribute( "sceneInterface:link.time", 1 ).value, 0.5 )
		self.assertEqual( i2.readAttribute( "sceneInterface:link.time", 2 ).value, 1 )

		self.assertEqual( i2.numBoundSamples(), 3 )
		self.assertEqual( i2.numTransformSamples(), 1 )
		A2 = i2.child("A")
		self.assertEqual( A2.numBoundSamples(), 3 )
		self.assertEqual( A2.numTransformSamples(), 3 )
		self.assertEqual( A2.readTransform(1.0), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1.5, 0, 0 ) ) ) )
		self.assertEqual( A2.readTransformAtSample(0), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1, 0, 0 ) ) ) )
		self.assertEqual( A2.readTransformAtSample(1), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1.5, 0, 0 ) ) ) )
		self.assertEqual( A2.readTransformAtSample(2), IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 2, 0, 0 ) ) ) )

		self.assertEqual( A2.hasAttribute( "sceneInterface:link.time" ), False )

	def testNestedTimeRemapping( self ):

		m = IECore.SceneCache( "test/IECore/data/sccFiles/animatedSpheres.scc", IECore.IndexedIO.OpenMode.Read )

		A = m.child("A")

		l2 = IECore.LinkedScene( "/tmp/test3.lscc", IECore.IndexedIO.OpenMode.Write )
		t2 = l2.createChild("transform2")
		i2 = t2.createChild("instance2")
		i2.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 0.0 ), 0.0 )
		i2.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( m, 2.0 ), 1.0 )

		del l2, i2, t2
		l2 = IECore.LinkedScene( "/tmp/test3.lscc", IECore.IndexedIO.OpenMode.Read )

		l1 = IECore.LinkedScene( "/tmp/test2.lscc", IECore.IndexedIO.OpenMode.Write )
		t1 = l1.createChild("transform1")
		i1 = t1.createChild("instance1")
		i1.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( l2, 0.0 ), 0.0 )
		i1.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( l2, 2.0 ), 1.0 )

		del l1, i1, t1
		l1 = IECore.LinkedScene( "/tmp/test2.lscc", IECore.IndexedIO.OpenMode.Read )

		l0 = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Write )
		t0 = l0.createChild("transform0")
		i0 = t0.createChild("instance0")
		i0.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( l1, 0.0 ), 0.0 )
		i0.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( l1, 2.0 ), 1.0 )

		del l0, i0, t0

		l0 = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Read )
		l = IECore.LinkedScene( "/tmp/testTop.lscc", IECore.IndexedIO.OpenMode.Write )
		t = l.createChild("transform")
		i = t.createChild("instance")
		i.writeLink( l0 )

		del l, i, t

		del m, l0, l1, l2

		l = IECore.LinkedScene( "/tmp/testTop.lscc", IECore.IndexedIO.OpenMode.Read )
		t = l.child("transform")
		i = t.child("instance")
		t0 = i.child("transform0")
		i0 = t0.child("instance0")
		t1 = i0.child("transform1")
		i1 = t1.child("instance1")
		t2 = i1.child("transform2")
		i2 = t2.child("instance2")
		A = i2.child("A")

		# this location shouldn't be retimed:
		self.assertEqual( i.hasAttribute( "sceneInterface:link.time" ), True )
		self.assertEqual( i.readAttribute( "sceneInterface:link.time", 0.25 ).value, 0.25 )

		# this location should be sped up by a factor of 2:
		self.assertEqual( i0.hasAttribute( "sceneInterface:link.time" ), True )
		self.assertEqual( i0.readAttribute( "sceneInterface:link.time", 0.25 ).value, 0.5 )

		# this one is remapped twice, so it's sped up by a factor of 4:
		self.assertEqual( i1.hasAttribute( "sceneInterface:link.time" ), True )
		self.assertEqual( i1.readAttribute( "sceneInterface:link.time", 0.25 ).value, 1 )

		# and this one is remapped three times, so it's sped up by a factor of 8:
		self.assertEqual( i2.hasAttribute( "sceneInterface:link.time" ), True )
		self.assertEqual( i2.readAttribute( "sceneInterface:link.time", 0.25 ).value, 2 )

		# sanity check:
		self.assertEqual( i.readAttribute( "sceneInterface:link.time", 0 ).value, 0 )
		self.assertEqual( i0.readAttribute( "sceneInterface:link.time", 0 ).value, 0 )
		self.assertEqual( i1.readAttribute( "sceneInterface:link.time", 0 ).value, 0 )
		self.assertEqual( i2.readAttribute( "sceneInterface:link.time", 0 ).value, 0 )

		# test multiple retiming of the transform:
		m = IECore.SceneCache( "test/IECore/data/sccFiles/animatedSpheres.scc", IECore.IndexedIO.OpenMode.Read )
		Aa = m.child("A")
		self.assertEqual( Aa.readTransformAsMatrix( 0.1 ), A.readTransformAsMatrix( 0.1 / 8 ) )
		self.assertEqual( Aa.readTransformAsMatrix( 0.2 ), A.readTransformAsMatrix( 0.2 / 8 ) )
		self.assertEqual( Aa.readTransformAsMatrix( 0.3 ), A.readTransformAsMatrix( 0.3 / 8 ) )
		self.assertEqual( Aa.readTransformAsMatrix( 0.4 ), A.readTransformAsMatrix( 0.4 / 8 ) )
		self.assertEqual( Aa.readTransformAsMatrix( 0.5 ), A.readTransformAsMatrix( 0.5 / 8 ) )
		self.assertEqual( Aa.readTransformAsMatrix( 0.6 ), A.readTransformAsMatrix( 0.6 / 8 ) )
		self.assertEqual( Aa.readTransformAsMatrix( 0.7 ), A.readTransformAsMatrix( 0.7 / 8 ) )
		self.assertEqual( Aa.readTransformAsMatrix( 0.8 ), A.readTransformAsMatrix( 0.8 / 8 ) )
		self.assertEqual( Aa.readTransformAsMatrix( 0.9 ), A.readTransformAsMatrix( 0.9 / 8 ) )

	def readSavedScenes( self, fileVersion ):

		def recurseCompare( basePath, virtualScene, realScene, atLink = True ) :
			self.assertEqual( basePath, virtualScene.path() )

			if atLink :

				self.assertEqual( set(virtualScene.readTags(IECore.SceneInterface.TagFilter.DescendantTag)), set(realScene.readTags(IECore.SceneInterface.TagFilter.DescendantTag)) )

			else: # attributes and tranforms at link location are not loaded.

				self.assertEqual( set(virtualScene.attributeNames()), set(realScene.attributeNames()) )
				for attr in realScene.attributeNames() :
					self.assertTrue( virtualScene.hasAttribute( attr ) )
					self.assertEqual( virtualScene.numAttributeSamples(attr), realScene.numAttributeSamples(attr) )
					for s in xrange(0,virtualScene.numAttributeSamples(attr)) :
						self.assertEqual( virtualScene.readAttributeAtSample(attr, s), realScene.readAttributeAtSample(attr, s) )

				self.assertEqual( virtualScene.numTransformSamples(), realScene.numTransformSamples() )
				for s in xrange(0,virtualScene.numTransformSamples()) :
					self.assertEqual( virtualScene.readTransformAtSample(s), realScene.readTransformAtSample(s) )

				self.assertEqual( set(virtualScene.readTags()), set(realScene.readTags()) )
				self.assertEqual( set(virtualScene.readTags(IECore.SceneInterface.TagFilter.LocalTag|IECore.SceneInterface.TagFilter.DescendantTag)), set(realScene.readTags(IECore.SceneInterface.TagFilter.LocalTag|IECore.SceneInterface.TagFilter.DescendantTag)) )

			self.assertEqual( virtualScene.numBoundSamples(), realScene.numBoundSamples() )
			for s in xrange(0,virtualScene.numBoundSamples()) :
				self.assertEqual( virtualScene.readBoundAtSample(s), realScene.readBoundAtSample(s) )

			self.assertEqual( virtualScene.hasObject(), realScene.hasObject() )
			if virtualScene.hasObject() :
				self.assertEqual( virtualScene.numObjectSamples(), realScene.numObjectSamples() )
				for s in xrange(0,virtualScene.numObjectSamples()) :
					self.assertEqual( virtualScene.readObjectAtSample(s), realScene.readObjectAtSample(s) )

			self.assertEqual( set(virtualScene.childNames()), set(realScene.childNames()) )
			for c in virtualScene.childNames() :
				self.assertTrue( virtualScene.hasChild(c) )
				recurseCompare( basePath + [ str(c) ], virtualScene.child(c), realScene.child(c), False )

		env = IECore.LinkedScene( "test/IECore/data/sccFiles/environment%s.lscc" % fileVersion, IECore.IndexedIO.OpenMode.Read )	# created by testWriting() when generateTestFiles=True and testFilesSuffix is defined.
		l = IECore.LinkedScene( "test/IECore/data/sccFiles/instancedSpheres%s.lscc" % fileVersion, IECore.IndexedIO.OpenMode.Read )	# created by testWriting() when generateTestFiles=True and testFilesSuffix is defined.
		m = IECore.SceneCache( "test/IECore/data/sccFiles/animatedSpheres.scc", IECore.IndexedIO.OpenMode.Read )

		base = env.child('base')
		self.assertEqual( set(base.childNames()), set(['test1','test2','test3','test4','test5']) )
		test1 = base.child('test1')
		self.assertEqual( test1.path(), [ "base", "test1" ] )
		recurseCompare( test1.path(), test1, l )
		test2 = base.child('test2')
		self.assertEqual( test2.path(), [ "base", "test2" ] )
		recurseCompare( test2.path(), test2, l.child('instance0') )
		test3 = base.child('test3')
		self.assertEqual( test3.path(), [ "base", "test3" ] )
		recurseCompare( test3.path(), test3, l.child('instance1') )
		test4 = base.child('test4')
		self.assertEqual( test4.path(), [ "base", "test4" ] )
		recurseCompare( test4.path(), test4, l.child('instance2') )
		test5 = base.child('test5')
		self.assertEqual( test5.path(), [ "base", "test5" ] )
		recurseCompare( test5.path(), test5, l.child('instance1').child('A') )

		# attributes like sceneInterface:link.root, sceneInterface:link.fileName, and sceneInterface:link.time shouldn't show up at links, although they might be there...
		self.assertEqual( test1.child('instance0').attributeNames(), [] )
		self.assertEqual( test1.child('instance1').attributeNames(), [ 'testAttr' ] )
		self.assertEqual( test1.child('instance2').attributeNames(), [] )

		# hasAttribute should tell the truth though...
		self.assertEqual( test1.child('instance0').hasAttribute( "sceneInterface:link.fileName" ), True )
		self.assertEqual( test1.child('instance0').hasAttribute( "sceneInterface:link.root" ), True )

		self.assertEqual( test1.child('instance1').hasAttribute( "sceneInterface:link.fileName" ), True )
		self.assertEqual( test1.child('instance1').hasAttribute( "sceneInterface:link.root" ), True )

		self.assertEqual( test1.child('instance2').hasAttribute( "sceneInterface:link.fileName" ), True )
		self.assertEqual( test1.child('instance2').hasAttribute( "sceneInterface:link.root" ), True )

		self.assertEqual( test1.child('instance0').path(), [ "base", "test1", "instance0" ] )
		recurseCompare( test1.child('instance0').path(), test1.child('instance0'), m )
		recurseCompare( test2.path(), test2, m )
		recurseCompare( test3.path(), test3, m )
		recurseCompare( test4.path(), test4, m.child('A') )
		recurseCompare( test5.path(), test5, m.child('A') )

		recurseCompare( test1.path(), env.scene( [ 'base', 'test1' ] ), l )
		recurseCompare( test1.path(), env.scene( [ 'base' ] ).child( 'test1' ), l )

	def testReadingFormats( self ):

		self.readSavedScenes( "" )		# tests first LinkedScene file format, with tags represented under the entry "tags"
		self.readSavedScenes( "_newTags" ) # tests second LinkedScene file format, with tags represented in separated entries: "localTags", "descendentTags" and "ancestorTags".

	def testTags( self ) :

		def testSet( values ):
			return set( map( lambda s: IECore.InternedString(s), values ) )

		# create a base scene
		l = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Write )
		a = l.createChild('a')
		a.writeTags( [ "testA" ] )
		b = l.createChild('b')
		b.writeTags(  [ "testB" ] )
		l.writeTags( [ "tags" ] )
		del a, b, l

		# now create a linked scene that should inherit the tags from the base one, plus add other ones
		l = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Read )
		a = l.child('a')
		b = l.child('b')

		self.assertEqual( set(l.readTags(IECore.SceneInterface.TagFilter.EveryTag)), testSet(["testA", "testB", "tags"]) )
		self.assertEqual( set(l.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["tags"]) )
		self.assertEqual( set(a.readTags(IECore.SceneInterface.TagFilter.AncestorTag)), testSet(["tags"]) )
		self.assertEqual( set(a.readTags(IECore.SceneInterface.TagFilter.DescendantTag)), set() )
		self.assertEqual( set(a.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["testA"]) )
		self.assertEqual( set(b.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["testB"]) )
		self.assertEqual( set(b.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["testB"]) )
		self.assertTrue( l.hasTag("testA", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertTrue( l.hasTag("testB", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertFalse( l.hasTag("testA", IECore.SceneInterface.TagFilter.LocalTag) )
		self.assertFalse( l.hasTag("testB", IECore.SceneInterface.TagFilter.LocalTag) )
		self.assertTrue( a.hasTag("testA", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertFalse( a.hasTag("testB", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertTrue( b.hasTag("testB", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertFalse( b.hasTag("testA", IECore.SceneInterface.TagFilter.EveryTag) )

		l2 = IECore.LinkedScene( "/tmp/test2.lscc", IECore.IndexedIO.OpenMode.Write )

		A = l2.createChild('A')
		A.writeLink( l )
		A.writeTags( ['linkedA'] )	# creating tag after link

		B = l2.createChild('B')

		# creating a link to a branch of an external file.
		messageHandler = IECore.CapturingMessageHandler()
		with messageHandler :
			# will have warnings as the branch inherits ancestor tags...
			B.writeLink( a )
		if not len( messageHandler.messages ):
			self.fail( "Was expecting a warning message when linking to a location that had ancestor tags!" )
		else :
			for messageInfo in messageHandler.messages:
				if not messageInfo.message.startswith( "Detected ancestor tags" ) :
					self.fail( messageHandler.message )

		C = l2.createChild('C')
		c = C.createChild('c')
		c.writeLink( l )
		C.writeTags( [ 'C' ] )

		D = l2.createChild('D')
		D.writeTags( [ 'D' ] )
		D.writeLink( a )	# creating link after tag

		del l, a, b, l2, A, B, C, c, D

		l2 = IECore.LinkedScene( "/tmp/test2.lscc", IECore.IndexedIO.OpenMode.Read )
		A = l2.child("A")
		Aa = A.child("a")
		B = l2.child("B")
		C = l2.child("C")
		c = C.child("c")
		ca = c.child("a")
		D = l2.child("D")

		self.assertTrue( l2.hasTag("testA", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertTrue( l2.hasTag("testB", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertFalse( l2.hasTag("t", IECore.SceneInterface.TagFilter.EveryTag) )

		self.assertEqual( set(l2.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet([]) )
		self.assertEqual( set(l2.readTags(IECore.SceneInterface.TagFilter.DescendantTag)), testSet(["testA", "testB","tags", "C", "D","linkedA"]) )
		self.assertEqual( set(l2.readTags(IECore.SceneInterface.TagFilter.LocalTag|IECore.SceneInterface.TagFilter.DescendantTag)), testSet(["testA", "testB","tags", "C", "D","linkedA"]) )
		self.assertEqual( set(l2.readTags(IECore.SceneInterface.TagFilter.AncestorTag)), testSet([]) )
		self.assertEqual( set(A.readTags(IECore.SceneInterface.TagFilter.EveryTag)), testSet(["testA","testB", "tags","linkedA"]) )
		self.assertTrue( A.hasTag( "linkedA", IECore.SceneInterface.TagFilter.EveryTag ) )
		self.assertTrue( A.hasTag( "tags", IECore.SceneInterface.TagFilter.EveryTag ) )
		self.assertTrue( A.hasTag( "testA", IECore.SceneInterface.TagFilter.EveryTag ) )
		self.assertTrue( A.hasTag( "testB", IECore.SceneInterface.TagFilter.EveryTag ) )
		self.assertFalse( A.hasTag("C", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertEqual( set(A.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["tags","linkedA"]) )
		self.assertEqual( set(Aa.readTags(IECore.SceneInterface.TagFilter.EveryTag)), testSet(["tags","testA", "linkedA"]) )
		self.assertEqual( set(Aa.readTags(IECore.SceneInterface.TagFilter.AncestorTag)), testSet(["tags", "linkedA"]) )
		self.assertEqual( set(Aa.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["testA"]) )
		self.assertTrue( Aa.hasTag("testA", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertFalse( Aa.hasTag("testB", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertEqual( set(B.readTags(IECore.SceneInterface.TagFilter.EveryTag)), testSet(["testA", "tags"]) )	# should not list "linkedA" as the link pointed to a child location.
		self.assertEqual( set(C.readTags(IECore.SceneInterface.TagFilter.EveryTag)), testSet(["testA","testB","tags","C"]) )
		self.assertEqual( set(C.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["C"]) )
		self.assertEqual( set(c.readTags(IECore.SceneInterface.TagFilter.EveryTag)), testSet(["C", "testA", "testB","tags"]) )
		self.assertEqual( set(c.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["tags"]) )
		self.assertEqual( set(c.readTags(IECore.SceneInterface.TagFilter.DescendantTag)), testSet([ "testA", "testB" ]) )
		self.assertEqual( set(ca.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["testA"]) )
		self.assertEqual( set(ca.readTags(IECore.SceneInterface.TagFilter.AncestorTag)), testSet(["C", "tags"]) )
		self.assertTrue( ca.hasTag("testA", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertFalse( ca.hasTag("testB", IECore.SceneInterface.TagFilter.EveryTag) )
		self.assertEqual( set(C.readTags(IECore.SceneInterface.TagFilter.LocalTag)), testSet(["C"]) )
		self.assertEqual( set(D.readTags(IECore.SceneInterface.TagFilter.EveryTag)), testSet(["tags", "D", "testA"]) )

	def testMissingLinkedScene( self ) :

		import shutil
		shutil.copyfile( "test/IECore/data/sccFiles/animatedSpheres.scc", "/tmp/toBeRemoved.scc" )

		m = IECore.SceneCache( "/tmp/toBeRemoved.scc", IECore.IndexedIO.OpenMode.Read )
		A = m.child("A")

		l = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Write )
		i0 = l.createChild("instance0")
		i0.writeLink( m )
		i1 = l.createChild("instance1")
		i1.writeLink( m )
		i1.writeTransform( IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1, 0, 0 ) ) ), 0.0 )
		i2 = l.createChild("instance2")
		i2.writeLink( A )
		i2.writeTransform( IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 2, 0, 0 ) ) ), 0.0 )
		del i0, i1, i2, l, m, A

		l = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Read )
		self.assertEqual( sorted(l.childNames()), [ "instance0", "instance1", "instance2" ] )
		i0 = l.child( "instance0" )
		self.assertEqual( sorted(i0.childNames()), [ "A", "B" ] )
		i1 = l.child( "instance1" )
		self.assertEqual( sorted(i1.childNames()), [ "A", "B" ] )
		i2 = l.child( "instance2" )
		self.assertEqual( i2.childNames(), [ "a" ] )
		del l, i0, i1, i2

		os.remove( "/tmp/toBeRemoved.scc" )
		IECore.SharedSceneInterfaces.clear()

		l = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Read )
		self.assertEqual( sorted(l.childNames()), [ "instance0", "instance1", "instance2" ] )
		i0 = l.child( "instance0" )
		self.assertEqual( i0.childNames(), [] )
		i1 = l.child( "instance1" )
		self.assertEqual( i1.childNames(), [] )
		i2 = l.child( "instance2" )
		self.assertEqual( i2.childNames(), [] )

	def testLinkBoundTransformMismatch( self ) :

		scene = IECore.SceneCache( "/tmp/test.scc", IECore.IndexedIO.OpenMode.Write )
		child = scene.createChild( "child" )
		mesh = IECore.MeshPrimitive.createBox( IECore.Box3f( IECore.V3f( 0 ), IECore.V3f( 1 ) ) )
		child.writeObject( mesh, 0 )

		del scene, child

		child = IECore.SceneCache( "/tmp/test.scc", IECore.IndexedIO.OpenMode.Read ).child( "child" )

		linked = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Write )
		parent = linked.createChild( "parent" )
		transform = IECore.M44dData( IECore.M44d.createTranslated( IECore.V3d( 1, 0, 0 ) ) )
		parent.writeTransform( transform, 1.0 )
		parent.writeObject( mesh, 1.0 )
		childLink = parent.createChild( "childLink" )
		childLink.writeTransform( transform, 1.0 )
		childLink.writeAttribute( IECore.LinkedScene.linkAttribute, IECore.LinkedScene.linkAttributeData( child ), 1.0 )

		del linked, parent, child, childLink

		linked = IECore.LinkedScene( "/tmp/test.lscc", IECore.IndexedIO.OpenMode.Read )
		parent = linked.child( "parent" )
		childLink = parent.child( "childLink" )

		# there are 2 bound samples, because the link has bounds at time 0, but a transform at time 1
		self.assertEqual( linked.numBoundSamples(), 2 )
		self.assertEqual( parent.numBoundSamples(), 2 )
		self.assertEqual( childLink.numBoundSamples(), 1 )

		self.assertEqual( linked.numTransformSamples(), 1 )
		self.assertEqual( parent.numTransformSamples(), 1 )
		self.assertEqual( childLink.numTransformSamples(), 1 )

		# object at the origin
		self.failUnless( LinkedSceneTest.compareBBox( childLink.readBoundAtSample( 0 ), IECore.Box3d( IECore.V3d( 0 ), IECore.V3d( 1 ) ) ) )

		# transformed the childLink by ( 1, 0, 0 ) and added an object at the origin
		self.assertEqual( childLink.readTransformAtSample( 0 ), transform )
		self.failUnless( LinkedSceneTest.compareBBox( parent.readBoundAtSample( 0 ), IECore.Box3d( IECore.V3d( 0 ), IECore.V3d( 2, 1, 1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( parent.readBoundAtSample( 0 ), parent.readBoundAtSample( 1 ) ) )

		# transformed the parent by ( 1, 0, 0 )
		self.assertEqual( parent.readTransformAtSample( 0 ), transform )
		self.failUnless( LinkedSceneTest.compareBBox( linked.readBoundAtSample( 0 ), IECore.Box3d( IECore.V3d( 1, 0, 0 ), IECore.V3d( 3, 1, 1 ) ) ) )
		self.failUnless( LinkedSceneTest.compareBBox( linked.readBoundAtSample( 0 ), linked.readBoundAtSample( 1 ) ) )

	def testMemoryIndexedIOReadWrite( self ) :

		# create inital file structure in memory:
		mio = IECore.MemoryIndexedIO( IECore.CharVectorData(), IECore.IndexedIO.OpenMode.Write )

		# write to the actual linkedscene:
		scc = IECore.SceneCache( mio )
		l = IECore.LinkedScene( scc )

		c0 = l.createChild("child0")
		c1 = l.createChild("child1")

		c0.writeAttribute( "testAttr", IECore.StringData("test0"), 0 )
		c1.writeAttribute( "testAttr", IECore.StringData("test1"), 0 )

		# write the "file" to memory
		del l, scc, c0, c1

		# can we read it back again?
		mioData = mio.buffer()
		mio = IECore.MemoryIndexedIO( mioData, IECore.IndexedIO.OpenMode.Read )

		scc = IECore.SceneCache( mio )
		l = IECore.LinkedScene( scc )

		self.assertEqual( set( l.childNames() ), set( ["child0", "child1"] ) )

		# no write access!
		self.assertRaises( RuntimeError, l.createChild, "child2" )

		c0 = l.child("child0")
		c1 = l.child("child1")

		self.assertEqual( c0.readAttribute( "testAttr", 0 ), IECore.StringData( "test0" ) )
		self.assertEqual( c1.readAttribute( "testAttr", 0 ), IECore.StringData( "test1" ) )

if __name__ == "__main__":
	unittest.main()


text:
```javascript
npm install jumpa --save
```

After NPM install, simply require Jumpa into a variable:

```javascript
const Jumpa = require('jumpa');
```

Now Jumpa is loaded into your source code. It's really lightweight. Don't worry!

##### Via the normal way:
1. Simply download or Git Clone the repo
2. Navigate to the dist folder
3. Choose between the regular or minified Jumpa.js
4. Load file into your website

```html
<script src="Jumpa.js"></script>
```

In your code, you can now call on Jumpa through a pre-defined `Jumpa` variable

## Usage

#### Automatic Mode

For Automatic mode simply add `data-jumpa` and then the target `data-jumpa-target=".target-jump-to-elem"` to the element that you want to be clicked on to perform the jump. Do this for each element you wish this to happen for and call:

```javascript
Jumpa.automatic();
```

This method will take care of the rest for you. Easy peasy!

##### Of course you can pass through options...

The default options so far are:

* **Duration**: (How long the animation between jumps should last)
* **Easing**: (What kind of animation should happen)
* **Callback**: (What custom stuff you want to happen after jump is finished)

```javascript
let options = {
	duration: 2000,
	easing: 'linear',
	callback: () => {
		console.log('Custom callback function that activates once jump animation has finished.');
	}
};

Jumpa.automatic(options);
```

#### Semi-Automatic Mode

Semi automatic allows you to set individual elements to jump instead of auto selecting every elem on page via data attributes. This way you can target custom elements via JS by setting the clickable jumpa elem and target individually:

```javascript
let jumper = '.section-hero__jumper'; 	// Element you want to click on
let target = '.section-next'; 			// Elem you want to jump to

Jumpa.semiAutomatic(jumper, target, options);
```

#### Manual Mode

Manual mode cuts out the event listeners and allows you to use the Jumpa scripts how you like:

```javascript
let jumper = document.querySelector('.section-hero__jumper');
let target = '.section-next';

jumper.addEventListener('click', () => {
	Jumpa.manual(target, options);
});
```


text:
package dcode.games.uEngine2.games.LD33;

import dcode.games.uEngine2.StData;

import java.awt.event.KeyEvent;

public class InputHandler extends dcode.games.uEngine2.PInputHandler {

	@Override
	public void keyTyped(char Char) {

	}

	@Override
	public void keyPressed(int ID) {
		if(StData.threadManager.KW.isIsCONTROLLHeld() && StData.threadManager.KW.isIsSHIFTHeld() && ID == KeyEvent.VK_F){
			LStData.playerSpeed += 1;
		}
		if(StData.threadManager.KW.isIsCONTROLLHeld() && StData.threadManager.KW.isIsSHIFTHeld() && ID == KeyEvent.VK_R && LStData.playerSpeed > 1.5){
			LStData.playerSpeed -= 1;
		}
	}

	@Override
	public void keyReleased(int ID) {

	}

	@Override
	public void keyPressed(String Key) {

	}

	@Override
	public void keyReleased(String Key) {

	}

	@Override
	public void keyPressed_W() {
		LStData.currentInputProcessor.upPressed();

	}

	@Override
	public void keyPressed_S() {
		LStData.currentInputProcessor.downPressed();

	}

	@Override
	public void keyPressed_A() {
		LStData.currentInputProcessor.leftPressed();

	}

	@Override
	public void keyPressed_D() {
		LStData.currentInputProcessor.rightPressed();

	}

	@Override
	public void keyPressed_Z() {
		LStData.currentInputProcessor.confirmPressed();

	}

	@Override
	public void keyPressed_X() {}

	@Override
	public void keyPressed_UP() {
		LStData.currentInputProcessor.upPressed();

	}

	@Override
	public void keyPressed_DOWN() {
		LStData.currentInputProcessor.downPressed();

	}

	@Override
	public void keyPressed_LEFT() {
		LStData.currentInputProcessor.leftPressed();

	}

	@Override
	public void keyPressed_RIGHT() {
		LStData.currentInputProcessor.rightPressed();

	}

	@Override
	public void keyPressed_ENTER() {
		LStData.currentInputProcessor.confirmPressed();

	}

	@Override
	public void keyPressed_SPACE() {

	}

	@Override
	public void keyPressed_BACKSPACE() {

	}

	@Override
	public void keyPressed_ESC() {

	}

	@Override
	public void keyPressed_TAB() {

	}

	@Override
	public void keyPressed_KonamiCode() {
		//still not working...
	}

	@Override
	public void clickedRight(int x, int y) {

	}

	@Override
	public void clickedLeft(int x, int y) {

	}

	@Override
	public void clickedMiddle(int x, int y) {

	}

	@Override
	public void scrolledUp(int x, int y) {

	}

	@Override
	public void scrolledDown(int x, int y) {

	}
}


text:
module ProjectMiscDefinitionx
  VERSION = "3.2.12.01"
end


text:
package com.acedened.vkutils;

import com.google.gson.*;
import com.google.gson.internal.LinkedTreeMap;

import java.util.HashMap;

public class VKApiException extends Exception {
    public VKApiException(LinkedTreeMap errorData) {
        super((String) errorData.get("error_msg"));
    }
}


text:
package me.shoutto.sdk.internal.usecases;

import android.util.Log;

import me.shoutto.sdk.StmBaseEntity;
import me.shoutto.sdk.StmCallback;
import me.shoutto.sdk.StmError;
import me.shoutto.sdk.StmService;
import me.shoutto.sdk.UpdateUserRequest;
import me.shoutto.sdk.User;
import me.shoutto.sdk.internal.StmObservableResults;
import me.shoutto.sdk.internal.http.HttpMethod;
import me.shoutto.sdk.internal.http.StmRequestProcessor;

/**
 * Updates a Shout to Me user object.
 */

public class UpdateUser extends BaseUseCase<StmBaseEntity, User> {

    private static final String TAG = UpdateUser.class.getSimpleName();
    private static final int STATE_GET_USER = 1;
    private static final int STATE_UPDATE_USER = 2;
    private static final int STATE_COMPLETED = 3;
    private StmService stmService;
    private int processingState;
    private User user;

    public UpdateUser(StmRequestProcessor<StmBaseEntity> stmRequestProcessor, StmService stmService) {
        super(stmRequestProcessor);
        this.stmService = stmService;
    }

    public void update(UpdateUserRequest updateUserRequest, String userId, boolean requiresGet, StmCallback<User> callback) {

        String errorMessage = "";

        if (!updateUserRequest.isValid()) {
            errorMessage = "UpdateUserRequest object is invalid";
        } else if (userId == null || "".equals(userId)) {
            errorMessage = "Invalid user ID. Cannot update user";
        }

        if (!"".equals(errorMessage)) {
            if (callback != null) {
                StmError error = new StmError(errorMessage, false, StmError.SEVERITY_MAJOR);
                callback.onError(error);
            } else {
                Log.w(TAG, errorMessage);
            }
            stmRequestProcessor.deleteObserver(this);
            return;
        }

        this.callback = callback;
        user = (User)updateUserRequest.adaptToBaseEntity();
        user.setId(userId);

        if (requiresGet) {
            processingState = STATE_GET_USER;
            executeGetUser();
        } else {
            processingState = STATE_UPDATE_USER;
            executeUpdateUser();
        }
    }

    private void executeGetUser() {
        stmRequestProcessor.processRequest(HttpMethod.GET, user);
    }

    private void executeUpdateUser() {
        stmRequestProcessor.processRequest(HttpMethod.PUT, user);
    }

    @Override
    public void update(StmObservableResults stmObservableResults) {

        if (stmObservableResults.isError()) {
            processCallbackError(stmObservableResults);
            return;
        }

        processCallback(stmObservableResults);

        if (processingState == STATE_COMPLETED)
            stmRequestProcessor.deleteObserver(this);
    }

    @Override
    public void processCallback(StmObservableResults stmObservableResults) {
        User userFromResults = (User)stmObservableResults.getResult();

        if (processingState == STATE_GET_USER) {
            if (userFromResults != null) {
                if (user.getMetaInfo() != null) {
                    User.MetaInfo metaInfoFromResults = userFromResults.getMetaInfo();
                    if (metaInfoFromResults == null) {
                        metaInfoFromResults = new User.MetaInfo();
                    }

                    if (user.getMetaInfo().getGender() != null) {
                        if ("".equals(user.getMetaInfo().getGender())) {
                            metaInfoFromResults.setGender(null);
                        } else {
                            metaInfoFromResults.setGender(user.getMetaInfo().getGender());
                        }
                    }

                    user.setMetaInfo(metaInfoFromResults);
                }

                processingState = STATE_UPDATE_USER;
                executeUpdateUser();
            } else {
                Log.e(TAG, "Did not successfully retrieve user from server");
                if (callback != null) {
                    StmError error = new StmError("Did not successfully retrieve user from server",
                            false, StmError.SEVERITY_MAJOR);
                    callback.onError(error);
                }
            }
        } else if (processingState == STATE_UPDATE_USER) {
            if (userFromResults != null && stmService != null) {
                stmService.getUser().setChannelSubscriptions(userFromResults.getChannelSubscriptions());
                stmService.getUser().setEmail(userFromResults.getEmail());
                stmService.getUser().setHandle(userFromResults.getHandle());
                stmService.getUser().setPlatformEndpointEnabled(userFromResults.getPlatformEndpointEnabled());
                stmService.getUser().setPhone(userFromResults.getPhone());
                stmService.getUser().setTopicPreferences(userFromResults.getTopicPreferences());
            }

            if (callback != null) {
                callback.onResponse(userFromResults);
            }

            processingState = STATE_COMPLETED;
        } else {
            Log.e(TAG, "Unknown UpdateUser processing state " + String.valueOf(processingState));
            if (callback != null) {
                StmError error = new StmError("Unknown UpdateUser processing state "
                        + String.valueOf(processingState),false, StmError.SEVERITY_MAJOR);
                callback.onError(error);
            }
        }
    }

    @Override
    public void processCallbackError(StmObservableResults stmObservableResults) {
        if (callback != null) {
            StmError error = new StmError(stmObservableResults.getErrorMessage(), false, StmError.SEVERITY_MAJOR);
            callback.onError(error);
        }
    }
}


text:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Song extends GlobalModel
{
    public function user()
    {
        return $this->belongsTo('App\User');
    }
    public function attachments() {
        return $this->hasMany('App\Attachment');
    }
    public function songcasts() {
        return $this->hasMany('App\Songcast');
    }
    public function most_recent_audiofile() {
	    $audiofile_type = Attachmenttype::where('typical_extension','mp3')->orderBy('created_at','desc')->first();

    	return $this->hasOne('App\Attachment')->where('type',$audiofile_type->id);
    }
}


text:
@interface GeoSearch()
@property NSArray *result;
@end

@implementation GeoSearch
{
    NSInteger seq_;
}

- (id)init
{
    self = [super init];
    if (self) {
        seq_ = 0;
    }
    return self;
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _result.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SearchResultCell"];

    cell.textLabel.text = _result[indexPath.row][@"addr"];

    return cell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    @synchronized(self) {
        CLLocationCoordinate2D co = CLLocationCoordinate2DMake(0.0, 0.0);
        if ([GeoUtil strToCoordinate2D:_result[indexPath.row][@"latlng"] co:&co]) {
            tableView.hidden = YES;
            [tableView deselectRowAtIndexPath:indexPath animated:YES];
            if (_didTapRowCallback)
                _didTapRowCallback(co, _result[indexPath.row][@"addr"]);
        }
    }
}

#pragma mark - UIScrollViewDelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //DLog(@"%@", scrollView);
    [_srcViewController hideKeyboard];
}

#pragma mark - public

- (void)searchByStr:(NSString *)str
{
    ++seq_;
    __block NSInteger no = seq_;

    if ([StringUtil empty:str]) {
        [self clear];
        return;
    }

    [GeoUtil searchByStr:str handler:^(NSArray *res, NSError *err) {
        if (err) {
            ELog(@"%@", err);
            return;
        }
        if (no < seq_)      // newer request was sent
            return;
        @synchronized(self) {
            self.result = res ? res : @[];
            [ProcUtil asyncMainq:^{
                [self.tableView reloadData];
            }];
        }
    }];
}

- (void)clear
{
    @synchronized(self) {
        self.result = @[];
        [ProcUtil asyncMainq:^{
            [self.tableView reloadData];
        }];
    }
}

@end


text:
namespace chromeos {
namespace first_run {

namespace {

void LaunchDialogForProfile(Profile* profile) {
  ExtensionService* service =
      extensions::ExtensionSystem::Get(profile)->extension_service();
  if (!service)
    return;

  const extensions::Extension* extension =
      service->GetExtensionById(extension_misc::kFirstRunDialogId, false);
  if (!extension)
    return;

  OpenApplication(
      AppLaunchParams(profile, extension, extensions::LAUNCH_CONTAINER_WINDOW,
                      NEW_WINDOW, extensions::SOURCE_CHROME_INTERNAL));
  profile->GetPrefs()->SetBoolean(prefs::kFirstRunTutorialShown, true);
}

// Object of this class waits for session start. Then it launches or not
// launches first-run dialog depending on user prefs and flags. Than object
// deletes itself.
class DialogLauncher : public content::NotificationObserver {
 public:
  explicit DialogLauncher(Profile* profile)
      : profile_(profile) {
    DCHECK(profile);
    registrar_.Add(this,
                   chrome::NOTIFICATION_SESSION_STARTED,
                   content::NotificationService::AllSources());
  }

  ~DialogLauncher() override {}

  void Observe(int type,
               const content::NotificationSource& source,
               const content::NotificationDetails& details) override {
    DCHECK(type == chrome::NOTIFICATION_SESSION_STARTED);
    DCHECK(content::Details<const user_manager::User>(details).ptr() ==
           ProfileHelper::Get()->GetUserByProfile(profile_));
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    bool launched_in_test = command_line->HasSwitch(::switches::kTestType);
    bool launched_in_telemetry =
        command_line->HasSwitch(switches::kOobeSkipPostLogin);
    bool is_user_new = user_manager::UserManager::Get()->IsCurrentUserNew();
    bool first_run_forced = command_line->HasSwitch(switches::kForceFirstRunUI);
    bool first_run_seen =
        profile_->GetPrefs()->GetBoolean(prefs::kFirstRunTutorialShown);
    bool is_pref_synced =
        PrefServiceSyncableFromProfile(profile_)->IsPrioritySyncing();
    bool is_user_ephemeral = user_manager::UserManager::Get()
                                 ->IsCurrentUserNonCryptohomeDataEphemeral();
    if (!launched_in_telemetry &&
        ((is_user_new && !first_run_seen &&
          (is_pref_synced || !is_user_ephemeral) && !launched_in_test) ||
         first_run_forced)) {
      LaunchDialogForProfile(profile_);
    }
    delete this;
  }

 private:
  Profile* profile_;
  content::NotificationRegistrar registrar_;

  DISALLOW_COPY_AND_ASSIGN(DialogLauncher);
};

}  // namespace

void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) {
  registry->RegisterBooleanPref(
      prefs::kFirstRunTutorialShown,
      false,
      user_prefs::PrefRegistrySyncable::SYNCABLE_PRIORITY_PREF);
}

void MaybeLaunchDialogAfterSessionStart() {
  new DialogLauncher(ProfileHelper::Get()->GetProfileByUserUnsafe(
      user_manager::UserManager::Get()->GetActiveUser()));
}

void LaunchTutorial() {
  UMA_HISTOGRAM_BOOLEAN("CrosFirstRun.TutorialLaunched", true);
  FirstRunController::Start();
}

}  // namespace first_run
}  // namespace chromeos


text:
"""Robust Bi-Tempered Logistic Loss Based on Bregman Divergences.

Source: https://bit.ly/3jSol8T
"""

import functools
import tensorflow as tf

def for_loop(num_iters, body, initial_args):
  """Runs a simple for-loop with given body and initial_args.

  Args:
    num_iters: Maximum number of iterations.
    body: Body of the for-loop.
    initial_args: Args to the body for the first iteration.

  Returns:
    Output of the final iteration.
  """
  for i in range(num_iters):
    if i == 0:
      outputs = body(*initial_args)
    else:
      outputs = body(*outputs)
  return outputs

def log_t(u, t):
  """Compute log_t for `u`."""

  def _internal_log_t(u, t):
    return (u**(1.0 - t) - 1.0) / (1.0 - t)

  return tf.cond(
      tf.equal(t, 1.0), lambda: tf.math.log(u),
      functools.partial(_internal_log_t, u, t))

def exp_t(u, t):
  """Compute exp_t for `u`."""

  def _internal_exp_t(u, t):
    return tf.nn.relu(1.0 + (1.0 - t) * u)**(1.0 / (1.0 - t))

  return tf.cond(
      tf.equal(t, 1.0), lambda: tf.math.exp(u),
      functools.partial(_internal_exp_t, u, t))

def compute_normalization_fixed_point(activations, t, num_iters=5):
  """Returns the normalization value for each example (t > 1.0).

  Args:
    activations: A multi-dimensional tensor with last dimension `num_classes`.
    t: Temperature 2 (> 1.0 for tail heaviness).
    num_iters: Number of iterations to run the method.
  Return: A tensor of same rank as activation with the last dimension being 1.
  """

  mu = tf.reduce_max(activations, -1, True)
  normalized_activations_step_0 = activations - mu
  shape_normalized_activations = tf.shape(normalized_activations_step_0)

  def iter_body(i, normalized_activations):
    logt_partition = tf.reduce_sum(
        exp_t(normalized_activations, t), -1, True)
    normalized_activations_t = tf.reshape(
        normalized_activations_step_0 * tf.pow(logt_partition, 1.0 - t),
        shape_normalized_activations)
    return [i + 1, normalized_activations_t]

  _, normalized_activations_t = for_loop(num_iters, iter_body,
                                         [0, normalized_activations_step_0])
  logt_partition = tf.reduce_sum(
      exp_t(normalized_activations_t, t), -1, True)
  return -log_t(1.0 / logt_partition, t) + mu

def compute_normalization_binary_search(activations, t, num_iters=10):
  """Returns the normalization value for each example (t < 1.0).

  Args:
    activations: A multi-dimensional tensor with last dimension `num_classes`.
    t: Temperature 2 (< 1.0 for finite support).
    num_iters: Number of iterations to run the method.
  Return: A tensor of same rank as activation with the last dimension being 1.
  """
  mu = tf.reduce_max(activations, -1, True)
  normalized_activations = activations - mu
  shape_activations = tf.shape(activations)
  effective_dim = tf.cast(
      tf.reduce_sum(
          tf.cast(
              tf.greater(normalized_activations, -1.0 / (1.0 - t)), tf.int32),
          -1,
          True), tf.float32)
  shape_partition = tf.concat([shape_activations[:-1], [1]], 0)
  lower = tf.zeros(shape_partition)
  upper = -log_t(1.0 / effective_dim, t) * tf.ones(shape_partition)

  def iter_body(i, lower, upper):
    logt_partition = (upper + lower)/2.0
    sum_probs = tf.reduce_sum(exp_t(
        normalized_activations - logt_partition, t), -1, True)
    update = tf.cast(tf.less(sum_probs, 1.0), tf.float32)
    lower = tf.reshape(lower * update + (1.0 - update) * logt_partition,
                       shape_partition)
    upper = tf.reshape(upper * (1.0 - update) + update * logt_partition,
                       shape_partition)
    return [i + 1, lower, upper]

  _, lower, upper = for_loop(num_iters, iter_body, [0, lower, upper])
  logt_partition = (upper + lower)/2.0
  return logt_partition + mu

def compute_normalization(activations, t, num_iters=5):
  """Returns the normalization value for each example.

  Args:
    activations: A multi-dimensional tensor with last dimension `num_classes`.
    t: Temperature 2 (< 1.0 for finite support, > 1.0 for tail heaviness).
    num_iters: Number of iterations to run the method.
  Return: A tensor of same rank as activation with the last dimension being 1.
  """
  return tf.cond(
      tf.less(t, 1.0),
      functools.partial(compute_normalization_binary_search, activations, t,
                        num_iters),
      functools.partial(compute_normalization_fixed_point, activations, t,
                        num_iters))

def _internal_bi_tempered_logistic_loss(activations, labels, t1, t2):
  """Computes the Bi-Tempered logistic loss.

  Args:
    activations: A multi-dimensional tensor with last dimension `num_classes`.
    labels: batch_size
    t1: Temperature 1 (< 1.0 for boundedness).
    t2: Temperature 2 (> 1.0 for tail heaviness).

  Returns:
    A loss tensor for robust loss.
  """
  if t2 == 1.0:
    normalization_constants = tf.math.log(
        tf.reduce_sum(tf.math.exp(activations), -1, True))
    if t1 == 1.0:
      return normalization_constants + tf.reduce_sum(
          tf.multiply(labels, tf.math.log(labels + 1e-10) - activations), -1)
    else:
      shifted_activations = tf.math.exp(activations - normalization_constants)
      one_minus_t1 = (1.0 - t1)
      one_minus_t2 = 1.0
  else:
    one_minus_t1 = (1.0 - t1)
    one_minus_t2 = (1.0 - t2)
    normalization_constants = compute_normalization(
        activations, t2, num_iters=5)
    shifted_activations = tf.nn.relu(1.0 + one_minus_t2 *
                                     (activations - normalization_constants))

  if t1 == 1.0:
    return tf.reduce_sum(
        tf.multiply(
            tf.math.log(labels + 1e-10) -
            tf.math.log(tf.pow(shifted_activations, 1.0 / one_minus_t2)),
            labels), -1)
  else:
    beta = 1.0 + one_minus_t1
    logt_probs = (tf.pow(shifted_activations, one_minus_t1 / one_minus_t2) -
                  1.0) / one_minus_t1
    return tf.reduce_sum(
        tf.multiply(log_t(labels, t1) - logt_probs, labels) - 1.0 / beta *
        (tf.pow(labels, beta) -
         tf.pow(shifted_activations, beta / one_minus_t2)), -1)

def tempered_sigmoid(activations, t, num_iters=5):
  """Tempered sigmoid function.

  Args:
    activations: Activations for the positive class for binary classification.
    t: Temperature tensor > 0.0.
    num_iters: Number of iterations to run the method.

  Returns:
    A probabilities tensor.
  """
  t = tf.convert_to_tensor(t)
  input_shape = tf.shape(activations)
  activations_2d = tf.reshape(activations, [-1, 1])
  internal_activations = tf.concat(
      [tf.zeros_like(activations_2d), activations_2d], 1)
  normalization_constants = tf.cond(
      # pylint: disable=g-long-lambda
      tf.equal(t, 1.0),
      lambda: tf.math.log(
          tf.reduce_sum(tf.math.exp(internal_activations), -1, True)),
      functools.partial(compute_normalization, internal_activations, t,
                        num_iters))
  internal_probabilities = exp_t(internal_activations - normalization_constants,
                                 t)
  one_class_probabilities = tf.split(internal_probabilities, 2, axis=1)[1]
  return tf.reshape(one_class_probabilities, input_shape)

def tempered_softmax(activations, t, num_iters=5):
  """Tempered softmax function.

  Args:
    activations: A multi-dimensional tensor with last dimension `num_classes`.
    t: Temperature tensor > 0.0.
    num_iters: Number of iterations to run the method.

  Returns:
    A probabilities tensor.
  """
  t = tf.convert_to_tensor(t)
  normalization_constants = tf.cond(
      tf.equal(t, 1.0),
      lambda: tf.math.log(tf.reduce_sum(tf.math.exp(activations), -1, True)),
      functools.partial(compute_normalization, activations, t, num_iters))
  return exp_t(activations - normalization_constants, t)

def bi_tempered_binary_logistic_loss(activations,
                                     labels,
                                     t1,
                                     t2,
                                     label_smoothing=0.0,
                                     num_iters=5):
  """Bi-Tempered binary logistic loss.

  Args:
    activations: A tensor containing activations for class 1.
    labels: A tensor with shape and dtype as activations.
    t1: Temperature 1 (< 1.0 for boundedness).
    t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support).
    label_smoothing: Label smoothing
    num_iters: Number of iterations to run the method.

  Returns:
    A loss tensor.
  """
  with tf.name_scope('binary_bitempered_logistic'):
    t1 = tf.convert_to_tensor(t1)
    t2 = tf.convert_to_tensor(t2)
    out_shape = tf.shape(labels)
    labels_2d = tf.reshape(labels, [-1, 1])
    activations_2d = tf.reshape(activations, [-1, 1])
    internal_labels = tf.concat([1.0 - labels_2d, labels_2d], 1)
    internal_logits = tf.concat([tf.zeros_like(activations_2d), activations_2d],
                                1)
    losses = bi_tempered_logistic_loss(internal_logits, internal_labels, t1, t2,
                                       label_smoothing, num_iters)
    return tf.reshape(losses, out_shape)

def bi_tempered_logistic_loss(activations,
                              labels,
                              t1,
                              t2,
                              label_smoothing=0.0,
                              num_iters=5):
  """Bi-Tempered Logistic Loss with custom gradient.

  Args:
    activations: A multi-dimensional tensor with last dimension `num_classes`.
    labels: A tensor with shape and dtype as activations.
    t1: Temperature 1 (< 1.0 for boundedness).
    t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support).
    label_smoothing: Label smoothing parameter between [0, 1).
    num_iters: Number of iterations to run the method.

  Returns:
    A loss tensor.
  """
  with tf.name_scope('bitempered_logistic'):
    t1 = tf.convert_to_tensor(t1)
    t2 = tf.convert_to_tensor(t2)
    if label_smoothing > 0.0:
      num_classes = tf.cast(tf.shape(labels)[-1], tf.float32)
      labels = (
          1 - num_classes /
          (num_classes - 1) * label_smoothing) * labels + label_smoothing / (
              num_classes - 1)

    @tf.custom_gradient
    def _custom_gradient_bi_tempered_logistic_loss(activations):
      """Bi-Tempered Logistic Loss with custom gradient.

      Args:
        activations: A multi-dimensional tensor with last dim `num_classes`.

      Returns:
        A loss tensor, grad.
      """
      with tf.name_scope('gradient_bitempered_logistic'):
        probabilities = tempered_softmax(activations, t2, num_iters)
        loss_values = tf.multiply(
            labels,
            log_t(labels + 1e-10, t1) -
            log_t(probabilities, t1)) - 1.0 / (2.0 - t1) * (
                tf.pow(labels, 2.0 - t1) - tf.pow(probabilities, 2.0 - t1))

        def grad(d_loss):
          """Explicit gradient calculation.

          Args:
            d_loss: Infinitesimal change in the loss value.
          Returns:
            Loss gradient.
          """
          delta_probs = probabilities - labels
          forget_factor = tf.pow(probabilities, t2 - t1)
          delta_probs_times_forget_factor = tf.multiply(delta_probs,
                                                        forget_factor)
          delta_forget_sum = tf.reduce_sum(
              delta_probs_times_forget_factor, -1, True)
          escorts = tf.pow(probabilities, t2)
          escorts = escorts / tf.reduce_sum(escorts, -1, True)
          derivative = delta_probs_times_forget_factor - tf.multiply(
              escorts, delta_forget_sum)
          return tf.multiply(d_loss, derivative)

        return loss_values, grad

    def reduced_loss(activations):
      return tf.reduce_sum(
          _custom_gradient_bi_tempered_logistic_loss(activations), -1)

    loss_values = tf.cond(
        tf.math.logical_and(tf.equal(t1, 1.0), tf.equal(t2, 1.0)),
        functools.partial(
            tf.nn.softmax_cross_entropy_with_logits,
            labels=labels,
            logits=activations), functools.partial(reduced_loss, activations))
    return loss_values

def sparse_bi_tempered_logistic_loss(activations, labels, t1, t2, num_iters=5):
  """Sparse Bi-Tempered Logistic Loss with custom gradient.

  Args:
    activations: A multi-dimensional tensor with last dimension `num_classes`.
    labels: A tensor with dtype of int32.
    t1: Temperature 1 (< 1.0 for boundedness).
    t2: Temperature 2 (> 1.0 for tail heaviness, < 1.0 for finite support).
    num_iters: Number of iterations to run the method.

  Returns:
    A loss tensor.
  """
  with tf.name_scope('sparse_bitempered_logistic'):
    t1 = tf.convert_to_tensor(t1)
    t2 = tf.convert_to_tensor(t2)
    num_classes = tf.shape(activations)[-1]

    @tf.custom_gradient
    def _custom_gradient_sparse_bi_tempered_logistic_loss(activations):
      """Sparse Bi-Tempered Logistic Loss with custom gradient.

      Args:
        activations: A multi-dimensional tensor with last dim `num_classes`.

      Returns:
        A loss tensor, grad.
      """
      with tf.name_scope('gradient_sparse_bitempered_logistic'):
        probabilities = tempered_softmax(activations, t2, num_iters)
        # TODO(eamid): Replace one hot with gather.
        loss_values = -log_t(
            tf.reshape(
                tf.gather_nd(probabilities,
                             tf.where(tf.one_hot(labels, num_classes))),
                tf.shape(activations)[:-1]), t1) - 1.0 / (2.0 - t1) * (
                    1.0 - tf.reduce_sum(tf.pow(probabilities, 2.0 - t1), -1))

        def grad(d_loss):
          """Explicit gradient calculation.

          Args:
            d_loss: Infinitesimal change in the loss value.
          Returns:
            Loss gradient.
          """
          delta_probs = probabilities - tf.one_hot(labels, num_classes)
          forget_factor = tf.pow(probabilities, t2 - t1)
          delta_probs_times_forget_factor = tf.multiply(delta_probs,
                                                        forget_factor)
          delta_forget_sum = tf.reduce_sum(
              delta_probs_times_forget_factor, -1, True)
          escorts = tf.pow(probabilities, t2)
          escorts = escorts / tf.reduce_sum(escorts, -1, True)
          derivative = delta_probs_times_forget_factor - tf.multiply(
              escorts, delta_forget_sum)
          return tf.multiply(d_loss, derivative)

        return loss_values, grad

    loss_values = tf.cond(
        tf.math.logical_and(tf.equal(t1, 1.0), tf.equal(t2, 1.0)),
        functools.partial(tf.nn.sparse_softmax_cross_entropy_with_logits,
                          labels=labels, logits=activations),
        functools.partial(_custom_gradient_sparse_bi_tempered_logistic_loss,
                          activations))
    return loss_values


text:
<?php

namespace Mews\Tests\Captcha;

use Mockery;

class CaptchaTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructor()
    {
        $this->assertTrue(true);
    }
}


text:
#include "common.h"
#include "compile_time_macros.h"
#include "console.h"
#include "cros_board_info.h"
#include "fw_config.h"
#include "gpio.h"

#define CPRINTS(format, args...) cprints(CC_CHIPSET, format, ##args)

static union taeko_cbi_fw_config fw_config;
BUILD_ASSERT(sizeof(fw_config) == sizeof(uint32_t));

/*
 * FW_CONFIG defaults for Taeko if the CBI.FW_CONFIG data is not
 * initialized.
 */
static const union taeko_cbi_fw_config fw_config_defaults = {
	.usb_db = DB_USB3_PS8815,
	.kb_bl = KEYBOARD_BACKLIGHT_ENABLED,
};

/****************************************************************************
 * Taeko FW_CONFIG access
 */
static void determine_storage(void)
{
	const bool has_nvme = fw_config.nvme_status == NVME_ENABLED;
	const bool has_emmc = fw_config.emmc_status == EMMC_ENABLED;

	/*
	 * If both masks are enabled or disabled, read the EMMC_SKU_DET pin
	 * (should happen only in the factory).
	 */
	if (has_nvme == has_emmc) {
		/* 0 = eMMC SKU, 1 = NVMe SKU */
		if (gpio_get_level(GPIO_EMMC_SKU_DET)) {
			CPRINTS("CBI: Detected NVMe SKU, disabling eMMC");
			fw_config.emmc_status = EMMC_DISABLED;
			fw_config.nvme_status = NVME_ENABLED;
		} else {
			CPRINTS("CBI: Detected eMMC SKU, disabling NVMe");
			fw_config.nvme_status = NVME_DISABLED;
			fw_config.emmc_status = EMMC_ENABLED;
		}
	}

	cbi_set_board_info(CBI_TAG_FW_CONFIG, (uint8_t *)&fw_config,
			   sizeof(fw_config));
}

void board_init_fw_config(void)
{
	if (cbi_get_fw_config(&fw_config.raw_value)) {
		CPRINTS("CBI: Read FW_CONFIG failed, using board defaults");
		fw_config = fw_config_defaults;
	}

	if (get_board_id() == 0) {
		/*
		 * Early boards doesn't have correct FW_CONFIG, so replace
		 * it with a sensible default value.
		 */
		CPRINTS("CBI: Using board defaults for early board");
		if (ec_cfg_has_tabletmode()) {
			fw_config = fw_config_defaults;
			fw_config.tabletmode = TABLETMODE_ENABLED;
		} else
			fw_config = fw_config_defaults;
	}

	determine_storage();
}

union taeko_cbi_fw_config get_fw_config(void)
{
	return fw_config;
}

enum ec_cfg_usb_db_type ec_cfg_usb_db_type(void)
{
	return fw_config.usb_db;
}

bool ec_cfg_has_keyboard_backlight(void)
{
	return (fw_config.kb_bl == KEYBOARD_BACKLIGHT_ENABLED);
}

bool ec_cfg_has_tabletmode(void)
{
	return (fw_config.tabletmode == TABLETMODE_ENABLED);
}

bool ec_cfg_has_keyboard_number_pad(void)
{
	return (fw_config.kbnumpad == KEYBOARD_NUMBER_PAD);
}