text:
package com.midi_automator.view.windows.MainFrame.listener;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.midi_automator.presenter.services.PresenterService;
import com.midi_automator.view.windows.MainFrame.MainFrame;
import com.midi_automator.view.windows.MainFrame.actions.HideShowMainFrameAction;

/**
 * Hides the window and displays a dialog that the program was just hidden.
 *
 * @author aguelle
 *
 */
@Component
public class HideMainFrameListener extends WindowAdapter {

	@Autowired
	private MainFrame programFrame;

	@Autowired
	private PresenterService presenterService;

	@Autowired
	private HideShowMainFrameAction hideShowAction;

	@Override
	public void windowClosing(WindowEvent e) {

		if (!programFrame.isExiting() && presenterService.isMinimizeOnClose()) {
			hideShowAction.actionPerformed(null);
		} else {
			programFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		}

	}
}

redpajama_set_name: RedPajamaGithub


text:
--
-- Table structure for irc feature
--

DROP TABLE IF EXISTS `irc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `irc` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `postmortem_id` bigint(20) NOT NULL,
  `channel` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
  `deleted` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `postmortem_id` (`postmortem_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


text:
<?php

namespace Drupal\Tests\field\Functional\EntityReference;

use Drupal\field\Entity\FieldConfig;
use Drupal\language\Entity\ConfigurableLanguage;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Entity\FieldStorageConfig;

/**
 * Tests the translation of entity reference field display on nodes.
 *
 * @group entity_reference
 */
class EntityReferenceFieldTranslatedReferenceViewTest extends BrowserTestBase {

  /**
   * Flag indicating whether the field is translatable.
   *
   * @var bool
   */
  protected $translatable = TRUE;

  /**
   * The langcode of the source language.
   *
   * @var string
   */
  protected $baseLangcode = 'en';

  /**
   * Target langcode for translation.
   *
   * @var string
   */
  protected $translateToLangcode = 'hu';

  /**
   * The test entity type name.
   *
   * @var string
   */
  protected $testEntityTypeName = 'node';

  /**
   * Entity type which have the entity reference field.
   *
   * @var \Drupal\node\Entity\NodeType
   */
  protected $referrerType;

  /**
   * Entity type which can be referenced.
   *
   * @var \Drupal\node\Entity\NodeType
   */
  protected $referencedType;

  /**
   * The referrer entity.
   *
   * @var \Drupal\node\Entity\Node
   */
  protected $referrerEntity;

  /**
   * The entity to refer.
   *
   * @var \Drupal\node\Entity\Node
   */
  protected $referencedEntityWithoutTranslation;

  /**
   * The entity to refer.
   *
   * @var \Drupal\node\Entity\Node
   */
  protected $referencedEntityWithTranslation;

  /**
   * The machine name of the entity reference field.
   *
   * @var string
   */
  protected $referenceFieldName = 'test_reference_field';

  /**
   * The label of the untranslated referenced entity, used in assertions.
   *
   * @var string
   */
  protected $labelOfNotTranslatedReference;

  /**
   * The original label of the referenced entity, used in assertions.
   *
   * @var string
   */
  protected $originalLabel;

  /**
   * The translated label of the referenced entity, used in assertions.
   *
   * @var string
   */
  protected $translatedLabel;

  /**
   * A user with permission to edit the referrer entity.
   *
   * @var \Drupal\user\UserInterface
   */
  protected $webUser;

  /**
   * Modules to enable.
   *
   * @var array
   */
  protected static $modules = [
    'language',
    'content_translation',
    'node',
  ];

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'stark';

  protected function setUp(): void {
    parent::setUp();

    $this->labelOfNotTranslatedReference = $this->randomMachineName();
    $this->originalLabel = $this->randomMachineName();
    $this->translatedLabel = $this->randomMachineName();

    $this->setUpLanguages();

    // We setup languages, so we need to ensure that the language manager
    // and language path processor is updated.
    $this->rebuildContainer();

    $this->setUpContentTypes();
    $this->enableTranslation();
    $this->setUpEntityReferenceField();
    $this->createContent();

    $this->webUser = $this->drupalCreateUser([
      'edit any ' . $this->referrerType->id() . ' content',
    ]);
  }

  /**
   * Tests if the entity is displayed in an entity reference field.
   */
  public function testEntityReferenceDisplay() {
    // Create a translated referrer entity.
    $this->referrerEntity = $this->createReferrerEntity();
    $this->assertEntityReferenceDisplay();
    $this->assertEntityReferenceFormDisplay();

    // Disable translation for referrer content type.
    $this->drupalLogin($this->rootUser);
    $this->drupalGet('admin/config/regional/content-language');
    $this->submitForm(['settings[node][referrer][translatable]' => FALSE], 'Save configuration');
    $this->drupalLogout();

    // Create a referrer entity without translation.
    $this->referrerEntity = $this->createReferrerEntity(FALSE);
    $this->assertEntityReferenceDisplay();
    $this->assertEntityReferenceFormDisplay();
  }

  /**
   * Assert entity reference display.
   *
   * @internal
   */
  protected function assertEntityReferenceDisplay(): void {
    $url = $this->referrerEntity->toUrl();
    $translation_url = $this->referrerEntity->toUrl('canonical', ['language' => ConfigurableLanguage::load($this->translateToLangcode)]);

    $this->drupalGet($url);
    $this->assertSession()->pageTextContains($this->labelOfNotTranslatedReference);
    $this->assertSession()->pageTextContains($this->originalLabel);
    $this->assertSession()->pageTextNotContains($this->translatedLabel);
    $this->drupalGet($translation_url);
    $this->assertSession()->pageTextContains($this->labelOfNotTranslatedReference);
    $this->assertSession()->pageTextNotContains($this->originalLabel);
    $this->assertSession()->pageTextContains($this->translatedLabel);
  }

  /**
   * Assert entity reference form display.
   *
   * @internal
   */
  protected function assertEntityReferenceFormDisplay(): void {
    $this->drupalLogin($this->webUser);
    $url = $this->referrerEntity->toUrl('edit-form');
    $translation_url = $this->referrerEntity->toUrl('edit-form', ['language' => ConfigurableLanguage::load($this->translateToLangcode)]);

    $this->drupalGet($url);
    $this->assertSession()->fieldValueEquals('test_reference_field[0][target_id]', $this->originalLabel . ' (1)');
    $this->assertSession()->fieldValueEquals('test_reference_field[1][target_id]', $this->labelOfNotTranslatedReference . ' (2)');
    $this->drupalGet($translation_url);
    $this->assertSession()->fieldValueEquals('test_reference_field[0][target_id]', $this->translatedLabel . ' (1)');
    $this->assertSession()->fieldValueEquals('test_reference_field[1][target_id]', $this->labelOfNotTranslatedReference . ' (2)');
    $this->drupalLogout();
  }

  /**
   * Adds additional languages.
   */
  protected function setUpLanguages() {
    ConfigurableLanguage::createFromLangcode($this->translateToLangcode)->save();
  }

  /**
   * Creates a test subject contents, with translation.
   */
  protected function createContent() {
    $this->referencedEntityWithTranslation = $this->createReferencedEntityWithTranslation();
    $this->referencedEntityWithoutTranslation = $this->createNotTranslatedReferencedEntity();
  }

  /**
   * Enables translations where it needed.
   */
  protected function enableTranslation() {
    // Enable translation for the entity types and ensure the change is picked
    // up.
    \Drupal::service('content_translation.manager')->setEnabled($this->testEntityTypeName, $this->referrerType->id(), TRUE);
    \Drupal::service('content_translation.manager')->setEnabled($this->testEntityTypeName, $this->referencedType->id(), TRUE);
  }

  /**
   * Adds term reference field for the article content type.
   */
  protected function setUpEntityReferenceField() {
    FieldStorageConfig::create([
      'field_name' => $this->referenceFieldName,
      'entity_type' => $this->testEntityTypeName,
      'type' => 'entity_reference',
      'cardinality' => FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
      'translatable' => $this->translatable,
      'settings' => [
        'allowed_values' => [
          [
            'target_type' => $this->testEntityTypeName,
          ],
        ],
      ],
    ])->save();

    FieldConfig::create([
      'field_name' => $this->referenceFieldName,
      'bundle' => $this->referrerType->id(),
      'entity_type' => $this->testEntityTypeName,
    ])
      ->save();

    /** @var \Drupal\Core\Entity\EntityDisplayRepositoryInterface $display_repository */
    $display_repository = \Drupal::service('entity_display.repository');

    $display_repository->getFormDisplay($this->testEntityTypeName, $this->referrerType->id())
      ->setComponent($this->referenceFieldName, [
        'type' => 'entity_reference_autocomplete',
      ])
      ->save();
    $display_repository->getViewDisplay($this->testEntityTypeName, $this->referrerType->id())
      ->setComponent($this->referenceFieldName, [
        'type' => 'entity_reference_label',
      ])
      ->save();
  }

  /**
   * Create content types.
   */
  protected function setUpContentTypes() {
    $this->referrerType = $this->drupalCreateContentType([
        'type' => 'referrer',
        'name' => 'Referrer',
      ]);
    $this->referencedType = $this->drupalCreateContentType([
        'type' => 'referenced_page',
        'name' => 'Referenced Page',
      ]);
  }

  /**
   * Create a referenced entity with a translation.
   */
  protected function createReferencedEntityWithTranslation() {
    /** @var \Drupal\node\Entity\Node $node */
    $node = \Drupal::entityTypeManager()->getStorage($this->testEntityTypeName)->create([
      'title' => $this->originalLabel,
      'type' => $this->referencedType->id(),
      'description' => [
        'value' => $this->randomMachineName(),
        'format' => 'basic_html',
      ],
      'langcode' => $this->baseLangcode,
    ]);
    $node->save();
    $node->addTranslation($this->translateToLangcode, [
      'title' => $this->translatedLabel,
    ]);
    $node->save();

    return $node;
  }

  /**
   * Create the referenced entity.
   */
  protected function createNotTranslatedReferencedEntity() {
    /** @var \Drupal\node\Entity\Node $node */
    $node = \Drupal::entityTypeManager()->getStorage($this->testEntityTypeName)->create([
      'title' => $this->labelOfNotTranslatedReference,
      'type' => $this->referencedType->id(),
      'description' => [
        'value' => $this->randomMachineName(),
        'format' => 'basic_html',
      ],
      'langcode' => $this->baseLangcode,
    ]);
    $node->save();

    return $node;
  }

  /**
   * Create the referrer entity.
   */
  protected function createReferrerEntity($translatable = TRUE) {
    /** @var \Drupal\node\Entity\Node $node */
    $node = \Drupal::entityTypeManager()->getStorage($this->testEntityTypeName)->create([
      'title' => $this->randomMachineName(),
      'type' => $this->referrerType->id(),
      'description' => [
        'value' => $this->randomMachineName(),
        'format' => 'basic_html',
      ],
      $this->referenceFieldName => [
        ['target_id' => $this->referencedEntityWithTranslation->id()],
        ['target_id' => $this->referencedEntityWithoutTranslation->id()],
      ],
      'langcode' => $this->baseLangcode,
    ]);
    if ($translatable) {
      $node->addTranslation($this->translateToLangcode, $node->toArray());
    }
    $node->save();

    return $node;
  }

}


text:
#include "link.h"

// attach an entry as a child directly
// both fs_entry structures must be write-locked
int fs_entry_attach_lowlevel( struct fs_core* core, struct fs_entry* parent, struct fs_entry* fent ) {
   fs_core_fs_rlock( core );
   fent->link_count++;

   struct timespec ts;
   clock_gettime( CLOCK_REALTIME, &ts );
   parent->mtime_sec = ts.tv_sec;
   parent->mtime_nsec = ts.tv_nsec;

   fs_entry_set_insert( parent->children, fent->name, fent );
   fs_core_fs_unlock( core );
   return 0;
}

// attach a file to the filesystem (same as link())
// THIS METHOD ONLY UPDATES THE METADATA; IT DOES NOT TOUCH STABLE STORAGE
int fs_entry_attach( struct fs_core* core, struct fs_entry* fent, char const* path, uint64_t user, uint64_t vol ) {
   // sanity check: path's basename should be fent's name
   char* path_base = md_basename( path, NULL );
   if( strcmp( fent->name, path_base ) != 0 ) {
      free(path_base);
      return -EINVAL;      // invalid entry
   }
   free( path_base );

   int err = 0;
   char* dirname = md_dirname( path, NULL );
   struct fs_entry* parent = fs_entry_resolve_path( core, dirname, user, vol, true, &err );
   free( dirname );
   if( parent == NULL ) {
      return err;
   }

   err = 0;

   fs_entry_wlock( fent );

   if( !IS_DIR_READABLE( parent->mode, parent->owner, parent->volume, user, vol ) ) {
      // directory not searchable
      fs_entry_unlock( fent );
      fs_entry_unlock( parent );
      return -EACCES;
   }
   if( !IS_WRITEABLE( parent->mode, parent->owner, parent->volume, user, vol ) ) {
      // not writable--cannot insert
      fs_entry_unlock( fent );
      fs_entry_unlock( parent );
      return -EACCES;
   }
   if( fs_entry_set_find_name( parent->children, fent->name ) == NULL ) {
      fs_entry_attach_lowlevel( core, parent, fent );
   }
   else {
      err = -EEXIST;
   }

   fs_entry_unlock( fent );

   fs_entry_unlock( parent );

   return err;
}


text:
Make sure `node` and `tsc` are installed and in your PATH. There are detailed instructions below.
(`tsc -v` should be at least `4.2.4`.)
Get the typescript code for the jsonrpc protocol with

`git clone git@github.com:microsoft vscode-languageserver-node.git` or
`git clone https://github.com/microsoft/vscode-languageserver-node.git`

`util.ts` expects it to be in your HOME directory

If you want to reproduce the existing files you need to be on a branch with the same git hash that `util.ts` expects, for instance, `git checkout 7b90c29`

## Usage

Code is generated and normalized by

`tsc && node code.js && gofmt -w ts*.go`

(`code.ts` imports `util.ts`.) This generates 3 files in the current directory, `tsprotocol.go`
containing type definitions, and `tsserver.go`, `tsclient.go` containing API stubs.

## Notes

1. `code.ts` and `util.ts` use the Typescript compiler's API, which is [introduced](https://github.com/Microsoft/TypeScript/wiki/Architectural-Overview) in their wiki.
2. Because the Typescript and Go type systems are incompatible, `code.ts` and `util.ts` are filled with heuristics and special cases. Therefore they are tied to a specific commit of `vscode-languageserver-node`. The hash code of the commit is included in the header of
the generated files and stored in the variable `gitHash` in `go.ts`. It is checked (see `git()` in `util.ts`) on every execution.
3. Generating the `ts*.go` files is only semi-automated. Please file an issue if the released version is too far behind.
4. For the impatient, first change `gitHash` by hand (`git()` shows how to find the hash).
    1. Then try to run `code.ts`. This will likely fail because the heuristics don't cover some new case. For instance, some simple type like `string` might have changed to a union type `string | [number,number]`. Another example is that some generated formal parameter may have anonymous structure type, which is essentially unusable.
    2. Next step is to move the generated code to `internal/lsp/protocol` and try to build `gopls` and its tests. This will likely fail because types have changed. Generally the fixes are fairly easy. Then run all the tests.
    3. Since there are not adequate integration tests, the next step is to run `gopls`.

## Detailed instructions for installing node and typescript

(The instructions are somewhat different for  Linux and MacOS. They install some things locally, so `$PATH` needs to be changed.)

1. For Linux, it is possible to build node from scratch, but if there's a package manager, that's simpler.
    1. To use the Ubuntu package manager
        1. `sudo apt update` (if you can't `sudo` then these instructions are not helpful)
        2. `sudo apt install nodejs` (this may install `/usr/bin/nodejs` rather than `/usr/bin/node`. For me, `/usr/bin/nodejs` pointed to an actual executable `/etc/alternatives/nodejs`, which should be copied to `/usr/bin/node`)
        3. `sudo apt intall npm`
    1. To build from scratch
        1. Go to the [node site](https://nodejs.org), and download the one recommended for most users, and then you're on your own. (It's got binaries in it. Untar the file somewhere and put its `bin` directory in your path, perhaps?)
2. The Mac is easier. Download the macOS installer from [nodejs](https://nodejs.org), click on it, and let it install.
3. (There's a good chance that soon you will be asked to upgrade your new npm. `sudo npm install -g npm` is the command.)
4. For either system, node and nvm should now be available. Running `node -v` and `npm -v` should produce version numbers.
5. `npm install typescript`
    1. This may give warning messages that indicate you've failed to set up a project. Ignore them.
    2. Your home directory will now have new directories `.npm` and `node_modules` (and a `package_lock.json` file)
    3. The typescript executable `tsc` will be in `node_modules/.bin`, so put that directory in your path.
    4. `tsc -v` should print "Version 4.2.4" (or later). If not you may (as I did) have an obsolete tsc earlier in your path.
6. `npm install @types/node` (Without this there will be many incomprehensible typescript error messages.)


text:
/**
 * VR tool for LMV
 *
 * @author Hans Kellner (Oct 2014)
 */

AutodeskNamespace ('Autodesk.Viewing.Extensions.VR') ;

Autodesk.Viewing.Extensions.VR.VRTool =function (viewer, vrExtension) {
    var _self =this ;

	var _viewer =viewer ;
    var _navapi =viewer.navigation ;
    var _container =viewer.container ;
    var _camera =_navapi.getCamera () ;
    var _names =['vr'] ;

    var _isActive =false ;

    var _renderContext =null ; // stereo render context

    var _isXUp =false ;
    var _isYUp =true ;
    var _isZUp =false ;

    // HACK: The first two delta mouse moves are extreme jumps and need to be
    // rejected.  This is used to skip those moves.  Note, it must also be reset
    // to zero whenever switching on/off pointer lock
    var _hackMouseMoveCounter = 0;

    var _modifierState = { SHIFT: 0, ALT: 0, CONTROL: 0 };  // TODO: Use the hotkeymanager for these.
    var _keys = Autodesk.Viewing.theHotkeyManager.KEYCODES;

    var _wheelDelta = 0;

    var _moveForward = false;
    var _moveBackward = false;
    var _moveLeft = false;
    var _moveRight = false;
    var _moveUp = false;
    var _moveDown = false;

    var _touchDragging = false;

    var _clock = new THREE.Clock(true);

    var _hudMessageStartShowTime = -1;
    var _hudMessageShowTime = 5000;         // milliseconds to show HUD

    var _modelScaleFactor = 1.0;

    var _movementSpeedDefault = 16.0;       // for VR make slower (35 for 1st person tool)
	var _movementSpeed = 16.0;
	var _verticalMovementSpeed = 15.0;
	var _wheelMovementSpeed = 3.0;

    var _autoMove = false;                  // true to automatically move camera forward
    var _autoMoveDefaultSpeed = 1.75;       // Default auto-move speed
    var _autoMoveDir = 1;                   // 1 == forward, -1 == reverse (TODO: disabled for now)
    var _autoMoveStartingSpeed = 16.0;      // Save the _movementSpeed at the start of auto-move

    var _darknessThresholdAutoMove = 15;    // avg gray scale pixel value of camera image to trigger auto-move

	var _previousFov = _camera.fov;
    var _wasPerspective = _camera.isPerspective;

    //
    // Google Goggle VR
    //
    var _deviceOrientationVR = null;
    var _noSleepVR = null;
    var _videoHelper = null;

    var _deviceAutoMoveTrigger = false;   // true if device pointed down (trigger); stays true until device tilted back up

    var _toggleAutoMoveStartTime = -1;
    var _firstAutoMoveSpeedChange = true;

    //
    // WebVR Device initialization (Oculus, etc)
    //
    var _deviceWebAPIVR = null;
    var _deviceSensorVR = null;
    var _vrMode = false;

    var _toggleDeviceVRMovementActivateDistance = 0.15;  // distance in meters before active movement
    var _toggleDeviceVRMovement = false;
    var _toggleDeviceVRMovementOrigin = new THREE.Vector3(0,0,0);
    var _toggleDeviceVRMovementLast = new THREE.Vector3(0,0,0);

    //
    // Wearality HMD
    //
    var _deviceWearalityHMD = false;

    // Constants

    var PI_2 = Math.PI / 2.0;

    /////////////////////////////////////////////////////////////////////////
    // ToolInterface

    this.isActive = function()
    {
        return _isActive;
    };

    this.getNames = function()
    {
        return _names;
    };

    this.getName = function()
    {
        return _names[0];
    };

    this.activate = function(name)
    {
        if (_isActive)
            return;

        _isXUp = (_camera.worldup && _camera.worldup.x === 1);
        _isYUp = (_camera.worldup && _camera.worldup.y === 1);
        _isZUp = (_camera.worldup && _camera.worldup.z === 1);

        console.log("VRTool : camera world up = "+_camera.worldup.x+","+_camera.worldup.y+","+_camera.worldup.z);

        _clock.start();

        // First check for Oculus or similar device through Web API
        if (getWebAPIVRDevice()) {
            //showHelpVRDeviceHMD();
            showUIElements(false);
            console.log("VR Supported (Web API): Oculus, etc.");
        }
        else {
            // Next check for Google Goggle style support
            //showHelpVRDeviceOrientation();
            window.addEventListener('deviceorientation', setOrientationControls, true);
        }

        var useVR = (viewer.config && viewer.config.useVR) ? viewer.config.useVR : "";

        // Check for Wearality setting to enable by default
        _deviceWearalityHMD = (useVR.toLowerCase() === "wearality");

        // Create the custom render context for stereo and HMDs
        enableRenderContext(true);

        // NOTE: Handled in stereorendercontext
        //_previousFov = _camera.fov;
        //_navapi.setVerticalFov(75, true);

        // Calculate a movement scale factor based on the model bounds (ignore selection).
        var boundsSize = viewer.utilities.getBoundingBox(true).size();
        _modelScaleFactor = Math.max(Math.min(Math.min(boundsSize.x,boundsSize.y),boundsSize.z) / 100.0, 1.0);

        this.resetPointerTracking();

        // HACK: Attempt to place focus in canvas so we get key events.
        viewer.canvas.focus();

        //showHelpHUD();

        _isActive = true;
    };

    this.deactivate = function(name)
    {
        if (!_isActive)
            return;

        _isActive = false;

        hideHUD();

        if (_deviceOrientationVR) {

            if (_videoHelper) {
                _videoHelper.stop();
                _videoHelper = null;
            }

            _deviceOrientationVR.disconnect();
            _deviceOrientationVR = null;

            // turn off no-sleep mode
            if (_noSleepVR)
                _noSleepVR.disable();
        }

        enableRenderContext(false);

        exitFullscreen();

        _clock.stop();

		//_navapi.setVerticalFov(_previousFov, true);
        //if (!_wasPerspective)
        //    _navapi.toOrthographic();

        showUIElements(true);
    };

    this.getCursor = function()
    {
        return "url(data:image/gif;base64,R0lGODlhGAAYAMIDAAQEBH19feDg4P///////////////////yH+EUNyZWF0ZWQgd2l0aCBHSU1QACH5BAEKAAQALAAAAAAYABgAAAMqSLrc/jDKSau9OOvN8fjDNghBIITZEABAgHpr+15jeYpgp+987//AICEBADs=), wait";
    };

    /////////////////////////////////////////////////////////////////////////

    var showUIElements = function(show)
    {
        // Show/hide the toolbar
        var toolbarMenuElements = document.getElementsByClassName('toolbar-menu');
        if (toolbarMenuElements.length > 0) { // HACK: Assume only 1
            if (toolbarMenuElements[0] !== '')
                toolbarMenuElements[0].style.display = show ? 'block' : 'none';
        }
    };

    var adjustSpeed = function( direction )
    {
        if ( direction === 0 ) // reset to default
        {
        	_movementSpeed = _movementSpeedDefault;
        }
        else
        {
            _movementSpeed *= (direction > 0) ?  1.10 : 0.90;
            if ( _movementSpeed < 0.000001 )
                _movementSpeed = 0.000001;
        }
        //console.log("Move Speed = "+_movementSpeed);
    };

    var enableRenderContext = function(enable)
    {
        if ( enable === !!_renderContext )
            return; // no change

        console.log("Enable Render Context: "+enable);

        if (enable)
        {
            if ( viewer.displayViewCube ) // Cyrille
            	viewer.displayViewCube(false, false);

            _wasPerspective = viewer.navigation.isPerspective;
            if (!_wasPerspective)
                viewer.navigation.toPerspective();

            // Enable WarpShade if using an HMD like the Oculus.
			//var bUseWarpShader = !!_deviceWebAPIVR; // Cyrille
			var bUseWarpShader =true ;

            var options = null;

            // Support for Wearality HMD?
            if (_deviceWearalityHMD)
            {
                // From Wearality:
                var DEFAULT_IPD = 0.075;  // meters (this kinda depends on person, and latest device has a physical IPD of 0.069  or 69 mm)
                var DEFAULT_CAMERA_ANGLE_OFFSET = -1.5;  // degrees
                var DEFAULT_ASYMMETRY = 0.07;

                // Here is how to set Asytemtric frusum:
                //
                //var horizOblLeft = -DEFAULT_ASYMMETRY;
                //var horizOblRight = DEFAULT_ASYMMETRY;
                //SetObliqueness(horizOblLeft , horizOblRight);
                //
                //private void SetObliqueness(float horizOblLeft, float horizOblRight)
                //{
                //    Matrix4x4 mat1 = camLeft.camera.projectionMatrix;
                //    mat1[0, 2] = horizOblLeft;
                //    mat1[1, 2] = 0;
                //    camLeft.camera.projectionMatrix = mat1;
                //
                //    Matrix4x4 mat2 = camRight.camera.projectionMatrix;
                //    mat2[0, 2] = horizOblRight;
                //    mat2[1, 2] = 0;
                //    camRight.camera.projectionMatrix = mat2;
                //}

                options = {
                    useWarp: bUseWarpShader,

                    HMD: {
                        // Parameters from the Wearality HMD
                        // TODO: Set eyeToScreenDistance, distortionK, and chromaAbParameter values
                        // to match Wearality's.
                        hResolution: 1920,
                        vResolution: 1080,
                        hScreenSize: 0.12576,
                        vScreenSize: 0.07074,
                        interpupillaryDistance: DEFAULT_IPD, // Oculus == 0.0635,
                        lensSeparationDistance: DEFAULT_IPD, // Oculus == 0.0635,
                        eyeToScreenDistance: 0.041,
                        distortionK : [1.0, 0.22, 0.24, 0.0],
                        chromaAbParameter: [ 0.996, -0.004, 1.014, 0.0]
                    }
                };
            }
            else {
                // Default HMD options
                options = {
                    useWarp: bUseWarpShader
                };
            }

            _renderContext = new Autodesk.Viewing.Extensions.Oculus.StereoRenderContext( options );
            viewer.impl.setUserRenderContext(_renderContext);

            //TODO: Not sure why we need this call in order to force the
            //stereo layout to fix itself.
            viewer.resize(viewer.canvas.clientWidth, viewer.canvas.clientHeight);

            // Go fullscreen
            if (_deviceWebAPIVR) {
                launchFullscreen(viewer.impl.canvas, { vrDisplay: _deviceWebAPIVR });
            } else {
                launchFullscreen(viewer.impl.canvas);
            }
        }
        else {
            // disable
            _renderContext = null;
            viewer.impl.setUserRenderContext(null);

            // Restore screen to normal and re-enable viewcube
            viewer.getScreenModeDelegate().setMode(Autodesk.Viewing.Viewer.ScreenMode.kNormal);
            if ( viewer.displayViewCube ) // Cyrille
            	viewer.displayViewCube(viewer.prefs.get("viewCube"), false);
        }
    };

    /////////////////////////////////////////////////////////////////////////
    // Tool event handler callbacks - can use "this".

    this.handleSingleTap = function( event )
    {
        //console.log("single tap ("+ (event.pointers ? event.pointers.length : 0)+")");

        // Only interested if we are being run on a mobile device using the
        // Device Orientation api.
        if (_deviceOrientationVR) {
            if ( event.pointers ) {

                if ( event.pointers.length === 1 ) {
                    // Exit VRTool and activate default tool
                    setTimeout(function () {
                        viewer.setActiveNavigationTool(viewer.defaultNavigationToolName);
                    }, 10);
                    return true;
                }
                else if ( event.pointers.length === 2 ) {
                    toggleAutoMove();
                    return true;
                }
            }
        }

        return false;
    };

    this.handleDoubleTap = function( event )
    {
        //console.log("double tap ("+ (event.pointers ? event.pointers.length : 0)+")");
        return false;
    };

    this.handlePressHold = function( event )
    {
        //console.log("press hold ["+(event.type ? event.type : "none")+"] ("+ (event.pointers ? event.pointers.length : 0)+")");
        //if( event.type === "press" )
        //{
        //    event.clientX = event.pointers[0].clientX;
        //    event.clientY = event.pointers[0].clientY;
        //}

        return false;
    };

    this.handleGesture = function( event )
    {
        //console.log("handle gesture ["+(event.type ? event.type : "none")+"]");

        // Only interested if we are being run on a mobile device using the
        // Device Orientation api.
        if (_deviceOrientationVR)
        {
            switch( event.type )
            {
            case "dragstart":
                _touchDragging = true;
                //var x = (event.normalizedX + 1.0) * 0.5;
                //var y = (event.normalizedY + 1.0) * 0.5;
                //console.log("DragStart: "+x+","+y);
                break;

            case "dragmove":
                if (_touchDragging) {
                    //var x = (event.normalizedX + 1.0) * 0.5;
                    //var y = (event.normalizedY + 1.0) * 0.5;
                    //console.log("DragMove: "+x+","+y);
                    // TODO: Use this to adjust auto move speed
                }
                break;

            case "dragend":
                //console.log("DragEnd");
                _touchDragging = false;
                break;
            }
        }

        return false;
    };

    this.handleKeyDown = function( event, keyCode )
    {
        var isModKey = false;
        var handled = false;

        switch( keyCode )
        {
            case _keys.TAB: handled = true; break;

            case _keys.SHIFT:   _modifierState.SHIFT = 1;   isModKey = true; handled = true; break;
            case _keys.CONTROL: _modifierState.CONTROL = 1; isModKey = true; handled = true; break;
            case _keys.ALT:     _modifierState.ALT = 1;     isModKey = true; handled = true; break;

            case _keys.SPACE:
                handled = true; break;

            case _keys.EQUALS: this.adjustSpeed(1);  handled = true; break;
            case _keys.DASH:   this.adjustSpeed(-1); handled = true; break;
            case _keys.ZERO:   this.adjustSpeed(0);  handled = true; break; // Reset dolly speed to default

            case _keys.w:
                // If Ctrol+Shift+W pressed then skip move handling
                if ( _modifierState.CONTROL === 1 && _modifierState.SHIFT === 1) {
                    handled = true;
                    break;
                }
                // fall through
            case _keys.UP:
                _moveForward = true; handled = true;
                break;

			case _keys.LEFT:
			case _keys.a:
                _moveLeft = true; handled = true;
                break;

			case _keys.DOWN:
			case _keys.s:
                _moveBackward = true; handled = true;
                break;

			case _keys.RIGHT:
			case _keys.d:
                _moveRight = true; handled = true;
                break;

			case _keys.q:
                _moveDown = true; handled = true;
                break;

			case _keys.e:
                _moveUp = true; handled = true;
                break;

            case _keys.h:
                handled = true;
                break;
        }

        return handled;
    };

    this.handleKeyUp = function( event, keyCode )
    {
        var isModKey = false;
        var handled = false;

        switch( keyCode )
        {
            case _keys.SHIFT:   _modifierState.SHIFT = 0;   isModKey = true; break;
            case _keys.CONTROL: _modifierState.CONTROL = 0; isModKey = true; break;
            case _keys.ALT:     _modifierState.ALT = 0;     isModKey = true; break;

            case _keys.SPACE:
                // HMD support?
                if ( !!_deviceWebAPIVR ) {
                    // Toggle movement on/off.
                    toggleDeviceVRMovement();
                }
                handled = true;
                break;

            case _keys.w:
                // Ctrl+Shift+W pressed?
                if ( !_moveForward && _modifierState.CONTROL === 1 && _modifierState.SHIFT === 1) {
                    // Toggle Wearality HMD on/off

                    // Exit VRTool and activate default tool
                    setTimeout(function () {
                        enableRenderContext(false);
                        _deviceWearalityHMD = !_deviceWearalityHMD;
                        enableRenderContext(true);
                    }, 10);

                    handled = true;
                    break;
                }
                // fall through for movement handling
            case _keys.UP:
                _moveForward = false; handled = true;
                break;

			case _keys.LEFT:
			case _keys.a:
                _moveLeft = false; handled = true;
                break;

			case _keys.DOWN:
			case _keys.s:
                _moveBackward = false; handled = true;
                break;

			case _keys.RIGHT:
			case _keys.d:
                _moveRight = false; handled = true;
                break;

			case _keys.q:
                _moveDown = false; handled = true;
                break;

			case _keys.e:
                _moveUp = false; handled = true;
                break;

            case _keys.h:
                showHelpHUD();
                handled = true;
                break;
        }

        return handled;
    };

    this.handleBlur = function(event)
    {
        // Reset things when we lose focus...
		_moveForward = false;
		_moveBackward = false;
		_moveLeft = false;
		_moveRight = false;

        return false;
    };

	this.update = function(timeStamp)
    {
        if (!_isActive)
            return;

        var delta = _clock.getDelta();

        if (_hudMessageStartShowTime > -1) {
            var curTime = new Date().getTime();
            if (curTime - _hudMessageStartShowTime > _hudMessageShowTime) { // seconds
                hideHUD();
            }
        }

        var vrUpdatedCameraTarget = false;

        // Oculus support?
        if ( !!_deviceWebAPIVR && updateVRDevice(delta) ) {
            vrUpdatedCameraTarget = true;
        } // Controlling via a VR device?  Then use that rather than default keyboard/mouse controls.
        else if ( !!_deviceOrientationVR && updateDeviceOrientationVR(delta) ) {
            vrUpdatedCameraTarget = true;
        }

		var localCam = _camera.clone();   // Copy of camera to modify

        // Handle movement changes
		var actualMoveSpeed = delta * _movementSpeed * _modelScaleFactor * (_modifierState.SHIFT === 1 ? 4 : 1);
        //console.log("Actual speed = "+actualMoveSpeed);

        var actualVerticalMoveSpeed = delta * _verticalMovementSpeed * _modelScaleFactor * (_modifierState.SHIFT === 1 ? 4 : 1);

        if (_wheelDelta != 0)
        {
            var actualWheelMoveSpeed = _wheelDelta * _wheelMovementSpeed * _modelScaleFactor * (_modifierState.SHIFT === 1 ? 4 : 1);
			localCam.translateZ( -actualWheelMoveSpeed );
            _wheelDelta = 0;
        }

        var autoMoveF = false,
            autoMoveB = false,
            autoMoveL = false,
            autoMoveR = false;

        if (_autoMove) {
            if (0) { //_deviceOrientationVR) {
                // IMPORTANT: The screen orientation effects the direction of camera movement.
                switch(_deviceOrientationVR.screenOrientation) // 0/180 = portait, 90/-90 = landscape
                {
                case 0:
                    autoMoveL = true;
                    break;
                case 180:
                    autoMoveR = true;
                    break;
                case 90:
                    autoMoveF = true;
                    break;
                case -90:
                    autoMoveB = true;
                    break;
                }
            }
            else {
                autoMoveF = true;
            }
        }

		if ( _moveForward || autoMoveF ) {
             localCam.translateZ( -actualMoveSpeed );
        }

		if ( _moveBackward || autoMoveB ) {
		     localCam.translateZ( actualMoveSpeed );
        }

		if ( _moveLeft || autoMoveL ) {
			localCam.translateX( -actualMoveSpeed );
        }

		if ( _moveRight || autoMoveR ) {
			localCam.translateX( actualMoveSpeed );
        }

		if ( _moveUp ) {
            localCam.translateY( actualVerticalMoveSpeed );
        }

		if ( _moveDown ) {
		    localCam.translateY( -actualVerticalMoveSpeed );
        }

        var newPosition = localCam.position;
        var posChanged = (newPosition.distanceToSquared(_camera.position) !== 0);
        if (posChanged) {

    		var newTarget = localCam.target;

            var dxyz = newPosition.clone().sub(_camera.position);
            newTarget.add(dxyz);

		    _navapi.setView(newPosition, newTarget);
        }

        return _camera.dirty;
	};

    this.resetPointerTracking = function()
    {
        _moveForward = _moveBackward = false;
        _moveLeft = _moveRight = false;
        _moveUp = _moveDown = false;

        _mouseDraggingLookMode = false;
    };

    /////////////////////////////////////////////////////////////////////////
    // Auto movement support
	this._toggleAutoMove_ = function() {
		toggleAutoMove() ;
	}

    var toggleAutoMove = function()
    {
        // Toggle auto-move state
        _autoMove = !_autoMove;

        // If starting to move then save current speed so it can be restored
        if (_autoMove) {
            _autoMoveStartingSpeed = _movementSpeed;
            _movementSpeed = _autoMoveDefaultSpeed;
            _toggleAutoMoveStartTime = new Date().getTime();
        }
        else {
            // Restore speed after auto-move
            _movementSpeed = _autoMoveStartingSpeed;
        }

        showHelpVRMove(_autoMove);

        return _autoMove;
    };

    /////////////////////////////////////////////////////////////////////////
    // Web API VR Support

    var getWebAPIVRDevice = function()
    {
        var foundVRDevice = false;

        // First check for Oculus style support
        function EnumerateVRDevices(devices) {
            // First find an HMD device
            for (var i = 0; i < devices.length; ++i) {
                if (devices[i] instanceof HMDVRDevice) {
                    _deviceWebAPIVR = devices[i];
                }
            }

            // Next find a sensor that matches the HMD hardwareUnitId
            for (var i = 0; i < devices.length; ++i) {
                if (devices[i] instanceof PositionSensorVRDevice &&
                    (!_deviceWebAPIVR || devices[i].hardwareUnitId == _deviceWebAPIVR.hardwareUnitId)) {
                    _deviceSensorVR = devices[i];

                    foundVRDevice = true;
                }
            }
        }

        if (navigator.getVRDevices) {
            navigator.getVRDevices().then(EnumerateVRDevices);
        } else if (navigator.mozGetVRDevices) {
            navigator.mozGetVRDevices(EnumerateVRDevices);
        } else {
            foundVRDevice = false; // WebVR API not supported
        }

        return foundVRDevice;
    };

    var updateVRDevice = function(delta)
    {
        if (!_deviceSensorVR)
            return false;

        var vrState = _deviceSensorVR.getState();

        if (_camera)
        {
            if (_isZUp) {
                _toggleDeviceVRMovementLast.x = vrState.position.x;
                _toggleDeviceVRMovementLast.y = -vrState.position.z;
                _toggleDeviceVRMovementLast.z = vrState.position.y;
            }
            else {
                _toggleDeviceVRMovementLast.x = vrState.position.x;
                _toggleDeviceVRMovementLast.y = vrState.position.y;
                _toggleDeviceVRMovementLast.z = vrState.position.z;
            }

            if (_toggleDeviceVRMovement)
            {
                // If head movement is greater than a specific amount then start
                // applying movement to camera.  This creates a neutral zone at
                // the "center of the joystick".
                var dist = _toggleDeviceVRMovementOrigin.distanceTo(_toggleDeviceVRMovementLast);
                if (dist >= _toggleDeviceVRMovementActivateDistance)
                {
                    // Every X inches from neutral scale
                    var distMovedFromNeutralScaleFactor = (dist - _toggleDeviceVRMovementActivateDistance) / 0.0762/*3in*/;
                    var actualMoveSpeed = delta * _movementSpeed * _modelScaleFactor * distMovedFromNeutralScaleFactor;

                    var dir = _toggleDeviceVRMovementLast.clone().sub(_toggleDeviceVRMovementOrigin).normalize().multiplyScalar(actualMoveSpeed);

                    _camera.position.add(dir);
                }
            }

            if (_isZUp) {
                _camera.quaternion.x = vrState.orientation.x;
                _camera.quaternion.y = -vrState.orientation.z;
                _camera.quaternion.z = vrState.orientation.y;
                _camera.quaternion.w = vrState.orientation.w;
            }
            else {
                _camera.quaternion.x = vrState.orientation.x;
                _camera.quaternion.y = vrState.orientation.y;
                _camera.quaternion.z = vrState.orientation.z;
                _camera.quaternion.w = vrState.orientation.w;
            }

            // TODO: The LMV camera still uses the old target value which threejs no longer uses.
            // Therefore we need to set it so the view changes.

            // Apply the camera's rotation to the vector looking down the Z axis
            var lookAtDir = new THREE.Vector3( 0, 0, -1 );

            // Models can have different up vectors.  The code above defaults to Y up.
            // Check for other Up directions.
            if (_isZUp) {
                lookAtDir = new THREE.Vector3(lookAtDir.x, -lookAtDir.z, lookAtDir.y);
            }

            lookAtDir.applyQuaternion( _camera.quaternion );

            // then update the target
            _camera.target = _camera.position.clone().add(lookAtDir.clone().multiplyScalar(10));

            _camera.dirty = true;
        }

        return true;
    };

    // Toggle movement on/off.
    //
    // When toggled on the current HMD postion is the new origin.  Movements away from that
    // origin will be used as a virtual joystick.
    var toggleDeviceVRMovement = function()
    {
        // Oculus support?
        if ( !_deviceWebAPIVR )
            return;

        _toggleDeviceVRMovement = !_toggleDeviceVRMovement;

        if (_toggleDeviceVRMovement) {
            _toggleDeviceVRMovementOrigin.copy(_toggleDeviceVRMovementLast);
        }

        showHelpVRMove(_toggleDeviceVRMovement);
    };

    /////////////////////////////////////////////////////////////////////////
    // Device Orientaton VR Support
    var updateDeviceOrientationVR = function(delta)
    {
        if (!_deviceOrientationVR)
            return false;

        // Get the current device orientation quaternion.
        // The quaternion can be applied to the current camera but that will *not* update
        // the target value nor handle world UP differences.  Therefore we need to also
        // update those values.
        var qOrientation = _deviceOrientationVR.update();
        if (!qOrientation)
            return false;
        //qOrientation.rotation.reorder( "YXZ" );

        // For Z-Up models we need to re-orient YZ values.
        if (_isZUp) {
            var t = qOrientation.z;
            qOrientation.z = qOrientation.y;
            qOrientation.y = -t;
        }

        // Models can have different up vectors.  Adjust for that.
        var lookAtDir = _isZUp ? new THREE.Vector3( 0, 1, 0 ) : new THREE.Vector3( 0, 0, -1 );

        // The LMV camera still uses the old target value which threejs no longer uses.
        // Therefore we need to set it so the view changes.
        var newTargetDir = lookAtDir.clone().applyQuaternion( qOrientation );

        // Distance to current target
        var dist = _camera.target.clone().sub(_camera.position).length();

        // then update the target
        _navapi.setTarget(_camera.position.clone().add(newTargetDir.multiplyScalar(dist)));

        // Handle screen orientation?
        //_deviceOrientationVR.screenOrientation == 90 // landscape 90

        // AUTO-MOVE support using video camera
        //
        // Check for a covered video camera.  That will toggle the movement.
        if (_videoHelper)
        {
            // Check if user has allowed video and video can be acquired.
            // NOTE: If the video helper fails to start then the user will
            // not be able to move the camera's position.
            if (_videoHelper.isStarted())
            {
                // Is it ok to check for a "button" press?
                if (_toggleAutoMoveStartTime <= 0)
                {
                    // Yes, so check for a "dark" image from camera.  Use this to
                    // toggle movement on/off
                    if ( _videoHelper.checkVideoThreshold(_darknessThresholdAutoMove) ) {
                        toggleAutoMove();
                    }
                }
                else
                {
                    // We get here if auto-move has been toggled.  Check if the
                    // camera image is still "dark"?
                    var isDark = _videoHelper.checkVideoThreshold(_darknessThresholdAutoMove);

                    // If not then it was uncovered.  Reset timer so toggle can occur again
                    if (!isDark) {
                        _toggleAutoMoveStartTime = -1;
                    }
                    // Else if still covererd and auto-move enabled then increase speed
                    else if (_autoMove)
                    {
                        var curTime = new Date().getTime();
                        var dTime = curTime - _toggleAutoMoveStartTime;

                        // Every 1/4sec increase by orginal speed
                        if (dTime > 250) { // milliseconds
                            _toggleAutoMoveStartTime = curTime; // restart counter

                            _movementSpeed += _autoMoveStartingSpeed;

                            // Reshow HUD so new speed is displayed
                            showHelpVRMove(true);
                        }
                    }
                }
            }
            //console.log("AUTO_MOVE = "+(_autoMove?"TRUE":"FALSE")+" Toggled(50) = "+ (toggled?"TRUE":"FALSE"));
        }
        else // Alternate move support if not using video camera
        {
            // Auto move support.  Tilt down increases speed.
            var lookDownDir = _isZUp ? new THREE.Vector3( 0, 0, -1 ) : new THREE.Vector3( 0, -1, 0 );
            var viewAngle = THREE.Math.radToDeg(newTargetDir.angleTo(lookDownDir));
            //console.log("View angle = "+viewAngle);

            if ( viewAngle < 30 ) {

                // Is this the first time tilting and the trigger hasn't been activated?
                if ( !_deviceAutoMoveTrigger )
                {
                    // Yes, toggle auto-move.
                    toggleAutoMove();

                    _deviceAutoMoveTrigger = true;  // Stays true until device tilted level.

                    // Beginning to move?
                    if (_autoMove) {
                        _firstAutoMoveSpeedChange = true;
                    }
                }
                else
                {
                    // If the user remains tilting device while auto-move
                    // is on then increase speed
                    if (_autoMove)
                    {
                        var curTime = new Date().getTime();
                        var dTime = curTime - _toggleAutoMoveStartTime;

                        // Every X seconds delay, increase by orginal speed.  But the first
                        // delay is longer so speed doesn't increase immediately.
                        var delay = _firstAutoMoveSpeedChange ? 1500 : 1000; // milliseconds

                        if (dTime >= delay)
                        {
                            _firstAutoMoveSpeedChange = false;
                            _toggleAutoMoveStartTime = curTime; // restart counter

                            _movementSpeed += _autoMoveStartingSpeed; // increase speed

                            // Reshow HUD so new speed is displayed
                            showHelpVRMove(true);
                        }
                    }
                }
            }
            // If device tilt is leveled then clear trigger
            else if ( viewAngle >= 30 ) {
                _deviceAutoMoveTrigger = false;
                _toggleAutoMoveStartTime = -1;
            }
        }

        _camera.dirty = true;
        return true;
    };

    var setOrientationControls = function(e)
    {
        if (!e.alpha) {
            return false;
        }

        window.removeEventListener('deviceorientation', setOrientationControls, true);

        _deviceOrientationVR = new THREE.DeviceOrientationControls();
        _deviceOrientationVR.connect();

        // turn on no-sleep mode.  This plays a hidden video that will cause the
        // phone to say awake.
        if (!_noSleepVR) {
            _noSleepVR = new window.NoSleep();
            _noSleepVR.enable();
        }

        // create the video helper.  note that this will enable the video
        // camera which the user will need to allow.  If the user disallows
        // then they may use the "tilt" mode for auto-move.
// cyrille
        //_videoHelper = new VideoHelper("videoVR","videoVR-canvas", 1/*camera index*/);  // change cam index for front vs. back
        //if (!_videoHelper.start()) {
        //    _videoHelper = null;    // failed.
        //    console.log("VideoHelper : Failed to start.");
        //}

        showUIElements(false);

        console.log("VR Supported (DeviceOrientation): Google Goggles, etc.");
        return true;
    };

    /////////////////////////////////////////////////////////////////////////
    // HUD helpers

    var showHUD = function(messageSpecs, showDelay)
    {
        Autodesk.Viewing.Private.HudMessage.dismiss();  // in case it's still visible
        Autodesk.Viewing.Private.HudMessage.displayMessage(_container, messageSpecs);
        _hudMessageStartShowTime = new Date().getTime();
        if (!showDelay || showDelay <= 0)
            showDelay = 5000;
        _hudMessageShowTime = showDelay;
    };

    var hideHUD = function()
    {
        Autodesk.Viewing.Private.HudMessage.dismiss();  // in case it's still visible
        _hudMessageStartShowTime = -1;
    };

    var showHelpHUD = function()
    {
        // TODO: Sadly, the HudMessage api doesn't support html formatted messages
        var messageSpecs = {
            "msgTitleKey"   : "Virtual Reality Tool",
            "messageKey"    : "Virtual Reality Tool",
            "messageDefaultValue"  : "This is the Virtual Reality tool."
        };

        //showHUD(messageSpecs, 3000);
    };

    var showHelpVRMove = function(enable, showDelay)
    {
        if (!showDelay || showDelay <= 0)
            showDelay = 250;

        var msg = (enable ? "START Auto Move ("+Math.floor(_movementSpeed)+")" : "STOP Auto Move");

        var messageSpecs = {
            "msgTitleKey"   : "VR Toggle Move",
            "messageKey"    : "VR Toggle Move",
            "messageDefaultValue"  : msg
        };

        //showHUD(messageSpecs, showDelay);
    };

    var showHelpVRDeviceOrientation = function()
    {
        var messageSpecs = {
            "msgTitleKey"   : "VR Device Orientation",
            "messageKey"    : "VR Device Orientation",
            "messageDefaultValue"  : "VR Mode Enabled (Device Orientation)"
        };

        //showHUD(messageSpecs, 2000);
    };

    var showHelpVRDeviceHMD = function()
    {
        var messageSpecs = {
            "msgTitleKey"   : "VR Head Mounted Display",
            "messageKey"    : "VR Head Mounted Display",
            "messageDefaultValue"  : "VR Mode Enabled (Head Mounted Display) - Use SPACE key to toggle move control."
        };

        //showHUD(messageSpecs, 2000);
    };
};


text:
#include "QtAV/VideoDecoder.h"
#include "QtAV/private/AVDecoder_p.h"
#include "QtAV/Packet.h"
#include "QtAV/private/AVCompat.h"
#include "QtAV/private/factory.h"
#include <libavcodec/avcodec.h>
extern "C" {
#include <libcedarv/libcedarv.h>
}
#include "utils/Logger.h"

// TODO: neon+nv12+opengl crash
#ifndef NO_NEON_OPT //Don't HAVE_NEON
extern "C" {
// from libvdpau-sunxi
void tiled_to_planar(void *src, void *dst, unsigned int dst_pitch,
                     unsigned int width, unsigned int height);

void tiled_deinterleave_to_planar(void *src, void *dst1, void *dst2,
                                  unsigned int dst_pitch,
                                  unsigned int width, unsigned int height);
}
#endif //NO_NEON_OPT
namespace QtAV {

class VideoDecoderCedarvPrivate;
class VideoDecoderCedarv : public VideoDecoder
{
    Q_OBJECT
    DPTR_DECLARE_PRIVATE(VideoDecoderCedarv)
#ifndef NO_NEON_OPT //Don't HAVE_NEON
    Q_PROPERTY(bool neon READ neon WRITE setNeon NOTIFY neonChanged)
#endif
    Q_PROPERTY(PixFmt outputPixelFormat READ outputPixelFormat WRITE setOutputPixelFormat NOTIFY outputPixelFormatChanged)
    Q_ENUMS(PixFmt)
public:
    enum PixFmt {
        YUV420p,
        NV12
    };
    VideoDecoderCedarv();
    VideoDecoderId id() const Q_DECL_OVERRIDE Q_DECL_FINAL;
    QString description() const Q_DECL_OVERRIDE Q_DECL_FINAL{
        return QStringLiteral("Allwinner A10 CedarX video hardware acceleration");
    }
    bool decode(const Packet& packet) Q_DECL_OVERRIDE Q_DECL_FINAL;
    VideoFrame frame() Q_DECL_OVERRIDE Q_DECL_FINAL;

    //properties
    void setNeon(bool value);
    bool neon() const;
    void setOutputPixelFormat(PixFmt value);
    PixFmt outputPixelFormat() const;
Q_SIGNALS:
    void neonChanged();
    void outputPixelFormatChanged();
};
extern VideoDecoderId VideoDecoderId_Cedarv;
FACTORY_REGISTER(VideoDecoder, Cedarv, "Cedarv")

// source data is colum major. every block is 32x32
static void map32x32_to_yuv_Y(void* srcY, void* tarY, unsigned int dst_pitch, unsigned int coded_width, unsigned int coded_height)
{
    unsigned long offset;
    unsigned char *ptr = (unsigned char *)srcY;
    const unsigned int mb_width = (coded_width+15) >> 4;
    const unsigned int mb_height = (coded_height+15) >> 4;
    const unsigned int twomb_line = (mb_height+1) >> 1;
    const unsigned int recon_width = (mb_width+1) & 0xfffffffe;

    for (unsigned int i = 0; i < twomb_line; i++) {
        const unsigned int M = 32*i;
        for (unsigned int j = 0; j < recon_width; j+=2) {
            const unsigned int n = j*16;
            offset = M*dst_pitch + n;
            for (unsigned int l = 0; l < 32; l++) {
                if (M+l < coded_height) {
                    if (n+16 < coded_width) {
                        //1st & 2nd mb
                        memcpy((unsigned char *)tarY+offset, ptr, 32);
                    } else if (n<coded_width) {
                        // 1st mb
                        memcpy((unsigned char *)tarY+offset, ptr, 16);
                    }
                    offset += dst_pitch;
                }
                ptr += 32;
            }
        }
    }
}

static void map32x32_to_yuv_C(void* srcC, void* tarCb, void* tarCr, unsigned int dst_pitch, unsigned int coded_width, unsigned int coded_height)
{
    coded_width /= 2; // libvdpau-sunxi compatible
    unsigned char line[32];
    unsigned long offset;
    unsigned char *ptr = (unsigned char *)srcC;
    const unsigned int mb_width = (coded_width+7) >> 3;
    const unsigned int mb_height = (coded_height+7) >> 3;
    const unsigned int fourmb_line = (mb_height+3) >> 2;
    const unsigned int recon_width = (mb_width+1) & 0xfffffffe;

    for (unsigned int i = 0; i < fourmb_line; i++) {
        const int M = i*32;
        for (unsigned int j = 0; j < recon_width; j+=2) {
            const unsigned int n = j*8;
            offset = M*dst_pitch + n;
            for (unsigned int l = 0; l < 32; l++) {
                if (M+l < coded_height) {
                    if (n+8 < coded_width) {
                        // 1st & 2nd mb
                        memcpy(line, ptr, 32);
                        //unsigned char *line = ptr;
                        for (int k = 0; k < 16; k++) {
                            *((unsigned char *)tarCb + offset + k) = line[2*k];
                            *((unsigned char *)tarCr + offset + k) = line[2*k+1];
                        }
                    } else if (n < coded_width) {
                        // 1st mb
                        memcpy(line, ptr, 16);
                        //unsigned char *line = ptr;
                        for (int k = 0; k < 8; k++) {
                            *((unsigned char *)tarCb + offset + k) = line[2*k];
                            *((unsigned char *)tarCr + offset + k) = line[2*k+1];
                        }
                    }
                    offset += dst_pitch;
                }
                ptr += 32;
            }
        }
    }
}

#if 0
static void map32x32_to_nv12_UV(void* srcC, void* tarUV, unsigned int dst_pitch, unsigned int coded_width, unsigned int coded_height)
{
    coded_width /= 2; // libvdpau-sunxi compatible
    unsigned long offset;
    unsigned char *ptr = (unsigned char *)srcC;
    const unsigned int mb_width = (coded_width+7) >> 3;
    const unsigned int mb_height = (coded_height+7) >> 3;
    const unsigned int fourmb_line = (mb_height+3) >> 2;
    const unsigned int recon_width = (mb_width+1) & 0xfffffffe;
    for (unsigned int i = 0; i < fourmb_line; i++) {
        const int M = i*32;
        for (unsigned int j = 0; j < recon_width; j+=2) {
            const unsigned int n = j*16; // 1 logical pixel 2 channel
            offset = M*dst_pitch + n;
            for (unsigned int l = 0; l < 32; l++) { // copy 16 logical pixels every time. 16/2*recon_width ~ coded_width
                if (M+l < coded_height) {
                    if (n+8 < coded_width) {
                        // 1st & 2nd mb
                        memcpy((unsigned char *)tarUV + offset, ptr, 32);
                    } else if (n < coded_width) {
                        // 1st mb
                        memcpy((unsigned char *)tarUV + offset, ptr, 16);
                    }
                    offset += dst_pitch;
                }
                ptr += 32;
            }
        }
    }
}
#endif

typedef struct {
    enum AVCodecID id;
    cedarv_stream_format_e format;
    cedarv_sub_format_e sub_format;
} avcodec_cedarv;

static const avcodec_cedarv avcodec_cedarv_map[] = {
    { QTAV_CODEC_ID(MPEG1VIDEO), CEDARV_STREAM_FORMAT_MPEG2, CEDARV_MPEG2_SUB_FORMAT_MPEG1 },
    { QTAV_CODEC_ID(MPEG2VIDEO), CEDARV_STREAM_FORMAT_MPEG2, CEDARV_MPEG2_SUB_FORMAT_MPEG2 },
    { QTAV_CODEC_ID(H263), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_H263 },
    { QTAV_CODEC_ID(H264), CEDARV_STREAM_FORMAT_H264, CEDARV_SUB_FORMAT_UNKNOW }, //CEDARV_CONTAINER_FORMAT_TS
    { QTAV_CODEC_ID(VP6F), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_VP6 },
    { QTAV_CODEC_ID(WMV1), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_WMV1 },
    { QTAV_CODEC_ID(WMV2), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_WMV2 },
    { QTAV_CODEC_ID(WMV3), CEDARV_STREAM_FORMAT_VC1, CEDARV_SUB_FORMAT_UNKNOW },
    { QTAV_CODEC_ID(VC1), CEDARV_STREAM_FORMAT_VC1, CEDARV_SUB_FORMAT_UNKNOW },
    { QTAV_CODEC_ID(MJPEG), CEDARV_STREAM_FORMAT_MJPEG, CEDARV_SUB_FORMAT_UNKNOW },
    { QTAV_CODEC_ID(VP8), CEDARV_STREAM_FORMAT_VP8, CEDARV_SUB_FORMAT_UNKNOW },
    { QTAV_CODEC_ID(MSMPEG4V1), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_DIVX1 },
    { QTAV_CODEC_ID(MSMPEG4V2), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_DIVX2 },
    { QTAV_CODEC_ID(MSMPEG4V3), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_DIVX3 },
    { QTAV_CODEC_ID(FLV1), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_SORENSSON_H263 },
    { QTAV_CODEC_ID(MPEG4), CEDARV_STREAM_FORMAT_MPEG4, CEDARV_MPEG4_SUB_FORMAT_XVID },
    { QTAV_CODEC_ID(RV10), CEDARV_STREAM_FORMAT_REALVIDEO, CEDARV_SUB_FORMAT_UNKNOW },
    { QTAV_CODEC_ID(RV20), CEDARV_STREAM_FORMAT_REALVIDEO, CEDARV_SUB_FORMAT_UNKNOW },
    { QTAV_CODEC_ID(RV30), CEDARV_STREAM_FORMAT_REALVIDEO, CEDARV_SUB_FORMAT_UNKNOW },
    { QTAV_CODEC_ID(RV40), CEDARV_STREAM_FORMAT_REALVIDEO, CEDARV_SUB_FORMAT_UNKNOW },
    { QTAV_CODEC_ID(NONE), CEDARV_STREAM_FORMAT_UNKNOW, CEDARV_SUB_FORMAT_UNKNOW }
};

typedef struct {
    enum AVPixelFormat fpf;
    cedarv_pixel_format_e cpf;
} ff_cedarv_pixfmt;

static const ff_cedarv_pixfmt pixel_format_map[] = {
    { QTAV_PIX_FMT_C(RGB565), CEDARV_PIXEL_FORMAT_RGB565 },
    { QTAV_PIX_FMT_C(RGB24), CEDARV_PIXEL_FORMAT_RGB888 },
    { QTAV_PIX_FMT_C(RGB32), CEDARV_PIXEL_FORMAT_ARGB8888 },
    { QTAV_PIX_FMT_C(YUV444P), CEDARV_PIXEL_FORMAT_YUV444 },
    { QTAV_PIX_FMT_C(YUV422P), CEDARV_PIXEL_FORMAT_YUV422 },
    { QTAV_PIX_FMT_C(YUV420P), CEDARV_PIXEL_FORMAT_YUV420 },
    { QTAV_PIX_FMT_C(YUV411P), CEDARV_PIXEL_FORMAT_YUV411 },
    //CEDARV_PIXEL_FORMAT_CSIRGB     = 0xf,
    { QTAV_PIX_FMT_C(NV12), CEDARV_PIXEL_FORMAT_AW_YUV420 },
    //{ QTAV_PIX_FMT_C(YUV422P), CEDARV_PIXEL_FORMAT_AW_YUV422 },
    //{ QTAV_PIX_FMT_C(YUV411P), CEDARV_PIXEL_FORMAT_AW_YUV411 },
};

void format_from_avcodec(enum AVCodecID id, cedarv_stream_format_e* format, cedarv_sub_format_e *sub_format)
{
    size_t i = 0;
    while (avcodec_cedarv_map[i].id != QTAV_CODEC_ID(NONE)) {
        if (avcodec_cedarv_map[i].id == id) {
            *format = avcodec_cedarv_map[i].format;
            *sub_format = avcodec_cedarv_map[i].sub_format;
            return;
        }
        ++i;
    }
    *format = CEDARV_STREAM_FORMAT_UNKNOW;
    *sub_format = CEDARV_SUB_FORMAT_UNKNOW;
}

enum AVPixelFormat pixel_format_from_cedarv(cedarv_pixel_format_e cpf)
{
    size_t i = 0;
    while (i < sizeof(pixel_format_map)/sizeof(pixel_format_map[0])) {
        if (pixel_format_map[i].cpf == cpf)
            return pixel_format_map[i].fpf;
        ++i;
    }
    return QTAV_PIX_FMT_C(NONE);
}

class VideoDecoderCedarvPrivate Q_DECL_FINAL: public VideoDecoderPrivate
{
public:
    VideoDecoderCedarvPrivate()
        : VideoDecoderPrivate()
        , cedarv(0)
        , map_y(map32x32_to_yuv_Y)
        , map_c(map32x32_to_yuv_C)
        , pixfmt(VideoDecoderCedarv::NV12)
    {}
    ~VideoDecoderCedarvPrivate() {
        if (!cedarv)
            return;
        cedarv->ioctrl(cedarv, CEDARV_COMMAND_STOP, 0);
        // FIXME: why crash?
        //cedarv->close(cedarv);
        //libcedarv_exit(cedarv);
        cedarv = NULL;
    }
    bool open()  Q_DECL_OVERRIDE;

    CEDARV_DECODER *cedarv;
    cedarv_picture_t cedarPicture;
    typedef void (*map_y_t)(void* src, void* dst, unsigned int dst_pitch, unsigned int w, unsigned int h);
    map_y_t map_y;
    typedef void (*map_c_t)(void* src, void* dst1, void* dst2, unsigned int dst_pitch, unsigned int w, unsigned int h);
    map_c_t map_c;
    VideoDecoderCedarv::PixFmt pixfmt;
};

VideoDecoderCedarv::VideoDecoderCedarv()
    : VideoDecoder(*new VideoDecoderCedarvPrivate())
{
}

VideoDecoderId VideoDecoderCedarv::id() const
{
    return VideoDecoderId_Cedarv;
}

void VideoDecoderCedarv::setNeon(bool value)
{
    if (value == neon())
        return;
    DPTR_D(VideoDecoderCedarv);
    if (value) {
#ifndef NO_NEON_OPT //Don't HAVE_NEON
        d.map_y = tiled_to_planar;
        d.map_c = tiled_deinterleave_to_planar;
#endif
    } else {
        d.map_y = map32x32_to_yuv_Y;
        d.map_c = map32x32_to_yuv_C;
    }
    emit neonChanged();
}

void VideoDecoderCedarv::setOutputPixelFormat(PixFmt value)
{
    if (outputPixelFormat() == value)
        return;
    d_func().pixfmt = value;
    emit outputPixelFormatChanged();
}

VideoDecoderCedarv::PixFmt VideoDecoderCedarv::outputPixelFormat() const
{
    return d_func().pixfmt;
}

bool VideoDecoderCedarv::neon() const
{
    return d_func().map_y != map32x32_to_yuv_Y;
}

bool VideoDecoderCedarvPrivate::open()
{
    cedarv_stream_format_e format;
    cedarv_sub_format_e sub_format;
    /* format check */
    format_from_avcodec(codec_ctx->codec_id, &format, &sub_format);
    if (format == CEDARV_STREAM_FORMAT_UNKNOW) {
        qWarning("CedarV: codec not supported '%s'", avcodec_get_name(codec_ctx->codec_id));
        return false;
    }
    if (!cedarv) {
        int ret;
        cedarv = libcedarv_init(&ret);
        if (ret < 0 || cedarv == NULL)
            return false;
    }

    cedarv_stream_info_t cedarStreamInfo;
    memset(&cedarStreamInfo, 0, sizeof cedarStreamInfo);
    cedarStreamInfo.format = format;
    cedarStreamInfo.sub_format = sub_format;
    cedarStreamInfo.video_width = codec_ctx->coded_width; //coded_width?
    cedarStreamInfo.video_height = codec_ctx->coded_height;
    if (codec_ctx->extradata_size) {
        cedarStreamInfo.init_data = codec_ctx->extradata;
        cedarStreamInfo.init_data_len = codec_ctx->extradata_size;
    }

    int cedarvRet;
    cedarvRet = cedarv->set_vstream_info(cedarv, &cedarStreamInfo);
    if (cedarvRet < 0) {
        qWarning("CedarV: set_vstream_info error: %d", cedarvRet);
        return false;
    }
    cedarvRet = cedarv->open(cedarv);
    if (cedarvRet < 0) {
        qWarning("CedarV: set_vstream_info error: %d", cedarvRet);
        return false;
    }
    cedarv->ioctrl(cedarv, CEDARV_COMMAND_RESET, 0);
    cedarv->ioctrl(cedarv, CEDARV_COMMAND_PLAY, 0);

    return true;
}

bool VideoDecoderCedarv::decode(const Packet &packet)
{
    DPTR_D(VideoDecoderCedarv);
    if (packet.data.isEmpty())
        return true;
    //d.cedarv->ioctrl(d.cedarv, CEDARV_COMMAND_JUMP, 0);
    u32 bufsize0, bufsize1;
    u8 *buf0, *buf1;
    int ret = d.cedarv->request_write(d.cedarv, packet.data.size(), &buf0, &bufsize0, &buf1, &bufsize1);
    if (ret < 0) {
        qWarning("CedarV: request_write failed (%d)", ret);
        return false;
    }
    memcpy(buf0, packet.data.constData(), bufsize0);
    if ((u32)packet.data.size() > bufsize0)
        memcpy(buf1, packet.data.constData() + bufsize0, bufsize1);
    cedarv_stream_data_info_t stream_data_info;
    stream_data_info.type = 0; // TODO
    stream_data_info.lengh = packet.data.size();
    stream_data_info.pts = packet.pts * 1000.0;
    stream_data_info.flags = CEDARV_FLAG_FIRST_PART | CEDARV_FLAG_LAST_PART | CEDARV_FLAG_PTS_VALID;
    if ((ret = d.cedarv->update_data(d.cedarv, &stream_data_info)) < 0) {
        qWarning("CedarV: update_data failed (%d)", ret);
        return false;
    }
    if ((ret = d.cedarv->decode(d.cedarv)) < 0) {
       qWarning("CedarV: decode failed (%d)", ret);
       return false;
    }
    ret = d.cedarv->display_request(d.cedarv, &d.cedarPicture);
    if (ret > 3 || ret < 0) {
       qWarning("CedarV: display_request failed (%d)", ret);
       if (d.cedarPicture.id) {
           d.cedarv->display_release(d.cedarv, d.cedarPicture.id);
           d.cedarPicture.id = 0;
       }
       return false;
    }
    return true;
}

VideoFrame VideoDecoderCedarv::frame()
{
    DPTR_D(VideoDecoderCedarv);
    if (!d.cedarPicture.id)
        return VideoFrame();
    d.cedarPicture.display_height = FFALIGN(d.cedarPicture.display_height, 8);
    const int display_h_align = FFALIGN(d.cedarPicture.display_height, 2); // already aligned to 8!
    const int display_w_align = FFALIGN(d.cedarPicture.display_width, 16);
    const int dst_y_stride = display_w_align;
    const int dst_y_size = dst_y_stride * display_h_align;
    const int dst_c_stride = FFALIGN(d.cedarPicture.display_width/2, 16);
    const int dst_c_size = dst_c_stride * (display_h_align/2);
    const int alloc_size = dst_y_size + dst_c_size * 2;
    const unsigned int offset_y = 0;
    const unsigned int offset_u = offset_y + dst_y_size;
    const unsigned int offset_v = offset_u + dst_c_size;

    const bool nv12 = outputPixelFormat() == NV12;
    QByteArray buf(alloc_size, 0);
    buf.reserve(alloc_size);
    quint8 *dst = reinterpret_cast<quint8*>(buf.data());
    quint8 *plane[] = {
        dst + offset_y,
        dst + offset_u,
        dst + offset_v
    };
    int pitch[] = {
        dst_y_stride,
        dst_c_stride,
        dst_c_stride
    };
    if (nv12)
        pitch[1] = dst_y_stride;

    d.map_y(d.cedarPicture.y, plane[0], display_w_align, pitch[0], display_h_align);
    if (nv12)
        d.map_y(d.cedarPicture.u, plane[1], pitch[1], display_w_align, display_h_align/2);
    else
        d.map_c(d.cedarPicture.u, plane[1], plane[2], pitch[1], display_w_align, display_h_align/2); //vdpau use w, h/2

    const VideoFormat fmt(nv12 ? VideoFormat::Format_NV12 : VideoFormat::Format_YUV420P);
    VideoFrame frame(display_w_align, display_h_align, fmt, buf);
    frame.setBits(plane);
    frame.setBytesPerLine(pitch);
    frame.setTimestamp(qreal(d.cedarPicture.pts)/1000.0);
    d.cedarv->display_release(d.cedarv, d.cedarPicture.id);
    d.cedarPicture.id = 0;
    return frame;
}

} // namespace QtAV
#include "VideoDecoderCedarv.moc"


text:
package com.gs.collections.impl.block.procedure;

import java.util.List;

import com.gs.collections.api.block.predicate.Predicate;
import com.gs.collections.api.block.procedure.Procedure;
import com.gs.collections.api.tuple.Pair;
import com.gs.collections.impl.factory.Lists;
import com.gs.collections.impl.tuple.Tuples;

/**
 * CaseProcedure allows developers to create an object form of a case statement, which instead of being based on
 * a single switch value is based on a list of predicate / procedure combinations.  For the first predicate
 * that returns true for a given value in the case statement, the corresponding procedure will be executed.
 */
public final class CaseProcedure<T> implements Procedure<T>
{
    private static final long serialVersionUID = 1L;

    private final List<Pair<Predicate<? super T>, Procedure<? super T>>> predicateProcedures = Lists.mutable.empty();
    private Procedure<? super T> defaultProcedure;

    public CaseProcedure(Procedure<? super T> defaultProcedure)
    {
        this.defaultProcedure = defaultProcedure;
    }

    public CaseProcedure()
    {
    }

    public CaseProcedure<T> addCase(Predicate<? super T> predicate, Procedure<? super T> procedure)
    {
        this.predicateProcedures.add(Tuples.<Predicate<? super T>, Procedure<? super T>>pair(predicate, procedure));
        return this;
    }

    public CaseProcedure<T> setDefault(Procedure<? super T> procedure)
    {
        this.defaultProcedure = procedure;
        return this;
    }

    public void value(T argument)
    {
        for (Pair<Predicate<? super T>, Procedure<? super T>> pair : this.predicateProcedures)
        {
            if (pair.getOne().accept(argument))
            {
                pair.getTwo().value(argument);
                return;
            }
        }
        if (this.defaultProcedure != null)
        {
            this.defaultProcedure.value(argument);
        }
    }

    @Override
    public String toString()
    {
        return "new CaseProcedure(" + this.predicateProcedures + ')';
    }
}


text:
""" High-Level Data Link Control (HDLC) module. """

import binascii

from struct import pack

import spinel.config as CONFIG
from spinel.stream import IStream

HDLC_FLAG = 0x7e
HDLC_ESCAPE = 0x7d

# RFC 1662 Appendix C

HDLC_FCS_INIT = 0xFFFF
HDLC_FCS_POLY = 0x8408
HDLC_FCS_GOOD = 0xF0B8

class Hdlc(IStream):
    """ Utility class for HDLC encoding and decoding. """

    def __init__(self, stream):
        self.stream = stream
        self.fcstab = self.mkfcstab()

    @classmethod
    def mkfcstab(cls):
        """ Make a static lookup table for byte value to FCS16 result. """
        polynomial = HDLC_FCS_POLY

        def valiter():
            """ Helper to yield FCS16 table entries for each byte value. """
            for byte in range(256):
                fcs = byte
                i = 8
                while i:
                    fcs = (fcs >> 1) ^ polynomial if fcs & 1 else fcs >> 1
                    i -= 1

                yield fcs & 0xFFFF

        return tuple(valiter())

    def fcs16(self, byte, fcs):
        """
        Return the next iteration of an fcs16 calculation
        given the next data byte and current fcs accumulator.
        """
        fcs = (fcs >> 8) ^ self.fcstab[(fcs ^ byte) & 0xff]
        return fcs

    def collect(self):
        """ Return the next valid packet to pass HDLC decoding on the stream. """
        fcs = HDLC_FCS_INIT
        packet = []
        raw = []

        # Synchronize
        while 1:
            byte = self.stream.read()
            if CONFIG.DEBUG_HDLC:
                raw.append(byte)
            if byte == HDLC_FLAG:
                break

        # Read packet, updating fcs, and escaping bytes as needed
        while 1:
            byte = self.stream.read()
            if CONFIG.DEBUG_HDLC:
                raw.append(byte)
            if byte == HDLC_FLAG:
                if len(packet) != 0:
                    break
                else:
                    # If multiple FLAG bytes in a row, keep looking for data.
                    continue
            if byte == HDLC_ESCAPE:
                byte = self.stream.read()
                if CONFIG.DEBUG_HDLC:
                    raw.append(byte)
                byte ^= 0x20
            packet.append(byte)
            fcs = self.fcs16(byte, fcs)

        if CONFIG.DEBUG_HDLC:
            CONFIG.LOGGER.debug(
                "RX Hdlc: " + binascii.hexlify(bytearray(raw)).decode('utf-8'))

        if fcs != HDLC_FCS_GOOD:
            packet = None
        else:
            packet = packet[:-2]  # remove FCS16 from end
            packet = pack("%dB" % len(packet), *packet)

        return packet

    @classmethod
    def encode_byte(cls, byte, packet=[]):
        """ HDLC encode and append a single byte to the given packet. """
        if (byte == HDLC_ESCAPE) or (byte == HDLC_FLAG):
            packet.append(HDLC_ESCAPE)
            packet.append(byte ^ 0x20)
        else:
            packet.append(byte)
        return packet

    def encode(self, payload=""):
        """ Return the HDLC encoding of the given packet. """
        fcs = HDLC_FCS_INIT
        packet = []
        packet.append(HDLC_FLAG)
        for byte in payload:
            fcs = self.fcs16(byte, fcs)
            packet = self.encode_byte(byte, packet)

        fcs ^= 0xffff
        byte = fcs & 0xFF
        packet = self.encode_byte(byte, packet)
        byte = fcs >> 8
        packet = self.encode_byte(byte, packet)
        packet.append(HDLC_FLAG)
        packet = pack("%dB" % len(packet), *packet)

        if CONFIG.DEBUG_HDLC:
            CONFIG.LOGGER.debug(
                "TX Hdlc: " +
                binascii.hexlify(bytearray(packet)).decode('utf-8'))
        return packet

    def write(self, data):
        """ HDLC encode and write the given data to this stream. """
        pkt = self.encode(data)
        self.stream.write(pkt)

    def read(self, _size=None):
        """ Read and HDLC decode the next packet from this stream. """
        pkt = self.collect()
        return pkt


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace DotNetNuke.Wiki.Views.SharedControls {

    public partial class WikiButton {

        /// <summary>
        /// cmdAdd control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink cmdAdd;

        /// <summary>
        /// lnkEdit control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink lnkEdit;

        /// <summary>
        /// txtViewHistory control.
        /// </summary>
        /// <remarks>
        /// Auto-generated field.
        /// To modify move field declaration from designer file to code-behind file.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HyperLink txtViewHistory;
    }
}


text:
<!DOCTYPE html>

    <title>EME playback test application</title>

    Clearkey works only with content encrypted using bear key.

      Encrypted video URL:
      <input id='mediaFile' type='text' size='64'>

      License sever URL:
      <input id='licenseServer' type='text' size='64'>

      Key system:
      <select id='keySystemList'></select>

      Media type:
      <select id='mediaTypeList'></select>

      EME API version:
      <select id='usePrefixedEME'></select>

      Load media by:

        <select id='useMSE'>
          <option value='true' selected='selected'>MSE</option>
          <option value='false'>src</option>
        </select>

    <button onclick='Play();'>Play</button>

    Decoded fps:

    Dropped fps:

    Total dropped frames:

        Click to toggle logs visibility (newest at top).


text:
package com.cse3345.f13.martin;

import android.graphics.Canvas;
import android.graphics.Paint;

public class Ball {
	private int radius = 20;
	private int strokeRadius = 25;
	private final double gravity = .2;
	private int startX;
	private int startY;
	private double yacc = gravity;
	private double xacc = 0;
	private double xspeed = 0;
	private double yspeed = 0;
	private int xpos;
	private int ypos;
	private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
	private Paint strokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

	public Ball(int x , int y){
		xpos = startX = x;
		ypos = startY = y;
		mPaint.setColor(0xFF66BD4A);
		strokePaint.setColor(0xFFF2642F);
	}

	public void draw(Canvas can){
		can.drawCircle(xpos, ypos, strokeRadius, strokePaint);
		can.drawCircle(xpos, ypos, radius, mPaint);
		xacc = 0;
		yacc = gravity;
	}

	public boolean update(){
		//update the speeed based on the velocity
		xspeed += xacc;
		yspeed += yacc;

		//update the position based on the velocity
		xpos += xspeed;
		ypos += yspeed;

		/*//setting terminal velocity in the x and y planes
		if (xspeed > 20){
			xspeed = 20;
		}else if(xspeed < -20){
			xspeed = -10;
		}

		if (yspeed > 20){
			yspeed = 20;
		}else if(yspeed < -20){
			yspeed = -20;
		}*/

		return true;
	}

	public void wallBounce(){
		xspeed = -xspeed;
	}

	//how to ball moves when it is touched
	public void onTouch(int x){
		if(x == -1){
			xacc = -.05;
		}else if(x == -2){
			xacc = -.1;
		}else if(x == 1){
			xacc = .05;
		}else if(x == 2){
			xacc = .1;
		}else{
			xacc = 0;
		}
	}

	public void restart(){
		xpos = startX;
		ypos = startY;
		yspeed = 0;
		xspeed = 0;
		yacc = 0;
		xacc = 0;
	}

	public void setAcc(double xAdd, double yAdd){
		xacc += xAdd;
		yacc += yAdd;
	}

	public void setSize(int size){
		radius = size;
		strokeRadius = radius + (radius/4);
	}

	public int getX(){
		return xpos;
	}

	public int getY(){
		return ypos;
	}

	public int getRadius(){
		return radius;
	}
}


text:
package org.apache.commons.text.lookup;

import static org.junit.jupiter.api.Assertions.assertThrows;

import javax.script.ScriptEngineManager;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

/**
 * Tests {@link ScriptStringLookup}.
 */
public class ScriptStringLookupTest {

    private static final String JS_NAME = "JavaScript";

    @Test
    public void testBadEngineName() {
        assertThrows(IllegalArgumentException.class, () -> ScriptStringLookup.INSTANCE.lookup("BAD_ENGINE_NAME:\"Hello World!\""));
    }

    @Test
    public void testBadScript() {
        assertThrows(IllegalArgumentException.class, () -> ScriptStringLookup.INSTANCE.lookup(JS_NAME + ":X"));
    }

    @Test
    public void testNoScript() {
        assertThrows(IllegalArgumentException.class, () -> ScriptStringLookup.INSTANCE.lookup("ENGINE_NAME:"));
    }

    @Test
    public void testNull() {
        Assertions.assertNull(ScriptStringLookup.INSTANCE.lookup(null));
    }

    @Test
    public void testOne() {
        Assertions.assertEquals("Hello World!", ScriptStringLookup.INSTANCE.lookup(JS_NAME + ":\"Hello World!\""));
    }

    @Test
    public void testSanityCheck() {
        Assertions.assertNotNull(new ScriptEngineManager().getEngineByName(JS_NAME), JS_NAME);
    }

    @Test
    public void testScriptMissingColon() {
        assertThrows(IllegalArgumentException.class, () -> ScriptStringLookup.INSTANCE.lookup("JavaScript=\"test\""));
    }

    @Test
    public void testScriptUsingMultipleColons() {
        Assertions.assertEquals("It Works",
            ScriptStringLookup.INSTANCE.lookup(JS_NAME + ":true ? \"It Works\" : \"It Does Not Work\" "));
    }

    @Test
    public void testToString() {
        // does not blow up and gives some kind of string.
        Assertions.assertFalse(ScriptStringLookup.INSTANCE.toString().isEmpty());
    }

}


text:
var MultiSelectService;
(function ($, _, Backbone, Marionette, EntityService, App, MultiSelectListView, MultiSelectEntityView) {
    MultiSelectService = Marionette.EntityService.extend({
        getData: function (page) {
            var data = {
                conditions: [],
                page: page,
                pageSize: App.pageSize
            };

            data.conditions = data.conditions.concat(this.conditions);
            return data;
        },
        initialize: function (options) {
            this.model = null;
            this.listView = MultiSelectListView.extend({
                displayField: _.isUndefined(options.displayField) ? 'name' : options.displayField
            });

            this.formView = null;
            this.entityLayoutViewType = MultiSelectEntityView;
            options.allowableOperations = [];
            Marionette.EntityService.prototype.initialize.call(this, options);
        },
        getBtnClass: function () {
            return 'tiny round';
        }
    });
})(jQuery, _, Backbone, Marionette, EntityService, App, MultiSelectListView, MultiSelectEntityView);


text:
CREATE TABLE MB_QUEUE_MAPPING (
    QUEUE_ID SERIAL,
    QUEUE_NAME VARCHAR(512) UNIQUE,
    CONSTRAINT PK_MB_QUEUE_MAPPING PRIMARY KEY (QUEUE_ID)
);

CREATE TABLE MB_METADATA (
    MESSAGE_ID NUMERIC(19),
    QUEUE_ID INT,
    DLC_QUEUE_ID INT NOT NULL,
    MESSAGE_METADATA BYTEA NOT NULL,
    CONSTRAINT PK_MB_METADATA PRIMARY KEY (MESSAGE_ID),
    CONSTRAINT FK_MB_METADATA_QUEUE_MAPPING FOREIGN KEY (QUEUE_ID) REFERENCES MB_QUEUE_MAPPING (QUEUE_ID)
);

CREATE INDEX MB_METADATA_QUEUE_ID_INDEX ON MB_METADATA (QUEUE_ID);

CREATE TABLE MB_CONTENT (
    MESSAGE_ID NUMERIC(19),
    CONTENT_OFFSET INT,
    MESSAGE_CONTENT BYTEA NOT NULL,
    CONSTRAINT pk_messages PRIMARY KEY (MESSAGE_ID,CONTENT_OFFSET),
    CONSTRAINT FK_CONTENT FOREIGN KEY (MESSAGE_ID) REFERENCES MB_METADATA
    ON DELETE CASCADE
);

CREATE TABLE MB_EXPIRATION_DATA (
    MESSAGE_ID NUMERIC(19) UNIQUE,
    EXPIRATION_TIME NUMERIC(19),
    MESSAGE_DESTINATION VARCHAR(512) NOT NULL,
    CONSTRAINT FK_EXPIRATION_DATA FOREIGN KEY (MESSAGE_ID) REFERENCES MB_METADATA (MESSAGE_ID)
);

CREATE TABLE MB_RETAINED_METADATA (
  TOPIC_ID INT,
  TOPIC_NAME VARCHAR(512) NOT NULL,
  MESSAGE_ID NUMERIC(19) NOT NULL,
  MESSAGE_METADATA BYTEA NOT NULL,
  CONSTRAINT PK_MB_RETAINED_METADATA PRIMARY KEY (TOPIC_ID)
);

-- End of Message Store Tables --

-- Start of Andes Context Store Tables --

CREATE TABLE MB_DURABLE_SUBSCRIPTION (
    SUBSCRIPTION_ID VARCHAR(512) NOT NULL,
    DESTINATION_IDENTIFIER VARCHAR(512) NOT NULL,
    SUBSCRIPTION_DATA VARCHAR(2048) NOT NULL
);

CREATE TABLE MB_NODE (
    NODE_ID VARCHAR(512) NOT NULL,
    NODE_DATA VARCHAR(2048) NOT NULL,
        CONSTRAINT PK_MB_NODE PRIMARY KEY (NODE_ID)
);

CREATE TABLE MB_EXCHANGE (
    EXCHANGE_NAME VARCHAR(512) NOT NULL,
    EXCHANGE_DATA VARCHAR(2048) NOT NULL,
    CONSTRAINT PK_MB_EXCHANGE PRIMARY KEY (EXCHANGE_NAME)
);

CREATE TABLE MB_QUEUE (
    QUEUE_NAME VARCHAR(512) NOT NULL,
    QUEUE_DATA VARCHAR(2048) NOT NULL,
    CONSTRAINT PK_MB_QUEUE PRIMARY KEY (QUEUE_NAME)
);

CREATE TABLE MB_BINDING (
    EXCHANGE_NAME VARCHAR(512) NOT NULL,
    QUEUE_NAME VARCHAR(512) NOT NULL,
    BINDING_DETAILS VARCHAR(2048) NOT NULL,
    CONSTRAINT FK_MB_BINDING_EXCHANGE FOREIGN KEY (EXCHANGE_NAME) REFERENCES MB_EXCHANGE (EXCHANGE_NAME),
    CONSTRAINT FK_MB_BINDING_QUEUE FOREIGN KEY (QUEUE_NAME) REFERENCES MB_QUEUE (QUEUE_NAME)
    ON DELETE CASCADE
);

CREATE TABLE MB_QUEUE_COUNTER (
    QUEUE_NAME VARCHAR(512) NOT NULL,
    MESSAGE_COUNT NUMERIC(19),
    CONSTRAINT PK_QUEUE_COUNTER PRIMARY KEY (QUEUE_NAME)
);

CREATE TABLE MB_SLOT (
    SLOT_ID BIGSERIAL NOT NULL,
    START_MESSAGE_ID NUMERIC(19) NOT NULL,
    END_MESSAGE_ID NUMERIC(19) NOT NULL,
    STORAGE_QUEUE_NAME VARCHAR(512) NOT NULL,
    SLOT_STATE NUMERIC(3) NOT NULL,
    ASSIGNED_NODE_ID VARCHAR(512),
    ASSIGNED_QUEUE_NAME VARCHAR(512),
    CONSTRAINT PK_MB_SLOT PRIMARY KEY (SLOT_ID)
);

CREATE INDEX MB_SLOT_MESSAGE_ID_INDEX ON MB_SLOT (START_MESSAGE_ID, END_MESSAGE_ID);

CREATE INDEX MB_SLOT_QUEUE_INDEX ON MB_SLOT (STORAGE_QUEUE_NAME);

CREATE TABLE MB_SLOT_MESSAGE_ID (
    QUEUE_NAME VARCHAR(512) NOT NULL,
    MESSAGE_ID NUMERIC(19) NOT NULL,
    CONSTRAINT PK_MB_SLOT_MESSAGE_ID PRIMARY KEY (QUEUE_NAME,MESSAGE_ID)
);

CREATE TABLE MB_NODE_TO_LAST_PUBLISHED_ID (
    NODE_ID VARCHAR(512) NOT NULL,
    MESSAGE_ID NUMERIC(19) NOT NULL,
    CONSTRAINT PK_MB_LAST_PUBLISHED_ID PRIMARY KEY (NODE_ID)
);

CREATE TABLE MB_QUEUE_TO_LAST_ASSIGNED_ID (
    QUEUE_NAME VARCHAR(512) NOT NULL,
    MESSAGE_ID NUMERIC(19) NOT NULL,
    CONSTRAINT PK_MB_LAST_ASSIGNED_ID PRIMARY KEY (QUEUE_NAME)
);

CREATE TABLE MB_RETAINED_CONTENT (
  MESSAGE_ID NUMERIC(19),
  CONTENT_OFFSET INT,
  MESSAGE_CONTENT BYTEA NOT NULL,
  CONSTRAINT PK_MB_RETAINED_CONTENT PRIMARY KEY (MESSAGE_ID,CONTENT_OFFSET)
);

CREATE TABLE MB_MSG_STORE_STATUS (
    NODE_ID VARCHAR(512) NOT NULL,
    TIME_STAMP NUMERIC(19),
    CONSTRAINT PK_MSG_STORE_STATUS PRIMARY KEY (NODE_ID, TIME_STAMP)
);


text:
package test.java.framework;

public enum Client {FF, IE, GC, IOS, ANDROID}


text:
//
// This file is part of nuBASIC
// Copyright (c) Antonino Calderone (antonino.calderone@gmail.com)
// All rights reserved.
// Licensed under the MIT License.
// See COPYING file in the project root for full license information.
//

/* -------------------------------------------------------------------------- */

#ifndef TINY_NUBASIC_VER
#include "nu_stb_image.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

/* -------------------------------------------------------------------------- */

namespace nu {

/* -------------------------------------------------------------------------- */

unsigned char* image_load(char const* filename, int& x, int& y)
{
    int comp = 0;
    stbi_uc* image = stbi_load(filename, &x, &y, &comp, 4);

    return image;
}

/* -------------------------------------------------------------------------- */

void image_free(unsigned char* image)
{
    if (image) {
        stbi_image_free(image);
    }
}

/* -------------------------------------------------------------------------- */

} // namespace nu

#endif // !TINY_NUBASIC_VER