text:
package net.lag.kestrel

import java.io._
import java.nio.{ByteBuffer, ByteOrder}
import java.nio.channels.FileChannel
import com.twitter.actors.Actor._
import com.twitter.logging.Logger
import com.twitter.util.Time

case class BrokenItemException(lastValidPosition: Long, cause: Throwable) extends IOException(cause)

// returned from journal replay
abstract class JournalItem()
object JournalItem {
  case class Add(item: QItem) extends JournalItem
  case object Remove extends JournalItem
  case object RemoveTentative extends JournalItem
  case class SavedXid(xid: Int) extends JournalItem
  case class Unremove(xid: Int) extends JournalItem
  case class ConfirmRemove(xid: Int) extends JournalItem
  case class Continue(item: QItem, xid: Int) extends JournalItem
  case object EndOfFile extends JournalItem
}

/**
 * Codes for working with the journal file for a PersistentQueue.
 */
class Journal(queuePath: String, queueName: String, syncJournal: => Boolean, multifile: => Boolean) {
  private val log = Logger.get

  private val queueFile = new File(queuePath, queueName)

  private var writer: FileChannel = null
  private var reader: Option[FileChannel] = None
  private var readerFilename: Option[String] = None
  private var replayer: Option[FileChannel] = None

  var size: Long = 0

  // small temporary buffer for formatting operations into the journal:
  private val buffer = new Array[Byte](16)
  private val byteBuffer = ByteBuffer.wrap(buffer)
  byteBuffer.order(ByteOrder.LITTLE_ENDIAN)

  private val CMD_ADD = 0
  private val CMD_REMOVE = 1
  private val CMD_ADDX = 2
  private val CMD_REMOVE_TENTATIVE = 3
  private val CMD_SAVE_XID = 4
  private val CMD_UNREMOVE = 5
  private val CMD_CONFIRM_REMOVE = 6
  private val CMD_ADD_XID = 7
  private val CMD_CONTINUE = 8

  checkIfQueuePathExists

  def this(fullPath: String, syncJournal: => Boolean) =
    this(new File(fullPath).getParent(), new File(fullPath).getName(), syncJournal, false)

  private def open(file: File): Unit = {
    writer = new FileOutputStream(file, true).getChannel
  }

  private def checkIfQueuePathExists {
    if (!new File(queuePath).exists()) throw new FileNotFoundException(queuePath + " does not exist.")
  }

  def open(): Unit = {
    open(queueFile)
  }

  def totalSize: Long = {
    (queueFile :: Journal.orderedFilesForQueue(new File(queuePath), queueName).map {
      new File(queuePath, _)
    }).foldLeft(0L) { (sum, f) => sum + f.length() }
  }

  def roll(xid: Int, openItems: Seq[QItem], queue: Iterable[QItem]) {
    writer.close
    val tmpFile = new File(queuePath, queueName + "~~" + Time.now.inMilliseconds)
    open(tmpFile)
    dump(xid, openItems, queue)
    writer.close
    tmpFile.renameTo(queueFile)
    open
  }

  def continue(xid: Int, item: QItem): Unit = {
    item.xid = xid
    addWithXidAndCommand(CMD_CONTINUE, item)
  }

  def dump(xid: Int, openItems: Seq[QItem], queue: Iterable[QItem]) {
    size = 0
    for (item <- openItems) {
      addWithXidAndCommand(CMD_ADD_XID, item)
      removeTentative(false)
    }
    saveXid(xid)
    for (item <- queue) {
      add(false, item)
    }
    if (syncJournal) writer.force(false)
  }

  def close(): Unit = {
    writer.close
    reader.foreach { _.close }
    reader = None
    readerFilename = None
  }

  def erase(): Unit = {
    try {
      close()
      queueFile.delete
    } catch {
      case _ =>
    }
  }

  def inReadBehind(): Boolean = reader.isDefined

  def isReplaying(): Boolean = replayer.isDefined

  private def add(allowSync: Boolean, item: QItem): Unit = {
    val blob = item.pack(CMD_ADDX.toByte, false)
    do {
      writer.write(blob)
    } while (blob.position < blob.limit)
    if (allowSync && syncJournal) writer.force(false)
    size += blob.limit
  }

  def add(item: QItem): Unit = add(true, item)

  // used only to list pending transactions when recreating the journal.
  private def addWithXidAndCommand(command: Int, item: QItem) = {
    val blob = item.pack(command.toByte, true)
    do {
      writer.write(blob)
    } while (blob.position < blob.limit)
    // only called from roll(), so the journal does not need to be synced after a write.
    size += blob.limit
  }

  def remove() = {
    size += write(true, CMD_REMOVE.toByte)
  }

  private def removeTentative(allowSync: Boolean): Unit = {
    size += write(allowSync, CMD_REMOVE_TENTATIVE.toByte)
  }

  def removeTentative(): Unit = removeTentative(true)

  private def saveXid(xid: Int) = {
    // only called from roll(), so the journal does not need to be synced after a write.
    size += write(false, CMD_SAVE_XID.toByte, xid)
  }

  def unremove(xid: Int) = {
    size += write(true, CMD_UNREMOVE.toByte, xid)
  }

  def confirmRemove(xid: Int) = {
    size += write(true, CMD_CONFIRM_REMOVE.toByte, xid)
  }

  def startReadBehind(): Unit = {
    val pos = if (replayer.isDefined) replayer.get.position else writer.position
    val rj = new FileInputStream(queueFile).getChannel
    rj.position(pos)
    reader = Some(rj)
    readerFilename = Some(queueName)
  }

  // not tail recursive, but should only recurse once.
  def fillReadBehind(f: QItem => Unit): Unit = {
    val pos = if (replayer.isDefined) replayer.get.position else writer.position
    reader.foreach { rj =>
      if (rj.position == pos && readerFilename.get == queueName) {
        // we've caught up.
        rj.close
        reader = None
        readerFilename = None
      } else {
        readJournalEntry(rj) match {
          case (JournalItem.Add(item), _) =>
            f(item)
          case (JournalItem.Continue(item, xid), _) =>
            f(item)
          case (JournalItem.EndOfFile, _) =>
            // move to next file and try again.
            rj.close
            readerFilename = Journal.journalAfter(new File(queuePath), queueName, readerFilename.get)
            reader = Some(new FileInputStream(new File(queuePath, readerFilename.get)).getChannel)
            fillReadBehind(f)
            // FIXME: send actor signal to pack queue files!
          case (_, _) =>
        }
      }
    }
  }

  def replay(name: String)(f: JournalItem => Unit): Unit = {
    Journal.journalsForQueue(new File(queuePath), queueName).foreach { filename =>
      replayFile(name, new File(queuePath, filename).getCanonicalPath)(f)
    }
  }

  def replayFile(name: String, filename: String)(f: JournalItem => Unit): Unit = {
    size = 0
    var lastUpdate = 0L
    val TEN_MB = 10L * 1024 * 1024
    try {
      val in = new FileInputStream(filename).getChannel
      try {
        replayer = Some(in)
        var done = false
        do {
          readJournalEntry(in) match {
            case (JournalItem.EndOfFile, _) => done = true
            case (x, itemsize) =>
              size += itemsize
              f(x)
              if (size / TEN_MB > lastUpdate) {
                lastUpdate = size / TEN_MB
                log.info("Continuing to read '%s' journal (%s); %d MB so far...", name, filename, lastUpdate * 10)
              }
          }
        } while (!done)
      } catch {
        case e: BrokenItemException =>
          log.error(e, "Exception replaying journal for '%s': %s", name, filename)
          log.error("DATA MAY HAVE BEEN LOST! Truncated entry will be deleted.")
          truncateJournal(e.lastValidPosition)
      }
    } catch {
      case e: FileNotFoundException =>
        log.info("No transaction journal for '%s'; starting with empty queue.", name)
      case e: IOException =>
        log.error(e, "Exception replaying journal for '%s': %s", name, filename)
        log.error("DATA MAY HAVE BEEN LOST!")
        // this can happen if the server hardware died abruptly in the middle
        // of writing a journal. not awesome but we should recover.
    }
    replayer = None
  }

  private def truncateJournal(position: Long) {
    val trancateWriter = new FileOutputStream(queueFile, true).getChannel
    try {
      trancateWriter.truncate(position)
    } finally {
      trancateWriter.close()
    }
  }

  def readJournalEntry(in: FileChannel): (JournalItem, Int) = {
    byteBuffer.rewind
    byteBuffer.limit(1)
    val lastPosition = in.position
    var x: Int = 0
    do {
      x = in.read(byteBuffer)
    } while (byteBuffer.position < byteBuffer.limit && x >= 0)

    if (x < 0) {
      (JournalItem.EndOfFile, 0)
    } else {
      try {
        buffer(0) match {
          case CMD_ADD =>
            val data = readBlock(in)
            (JournalItem.Add(QItem.unpackOldAdd(data)), 5 + data.length)
          case CMD_REMOVE =>
            (JournalItem.Remove, 1)
          case CMD_ADDX =>
            val data = readBlock(in)
            (JournalItem.Add(QItem.unpack(data)), 5 + data.length)
          case CMD_REMOVE_TENTATIVE =>
            (JournalItem.RemoveTentative, 1)
          case CMD_SAVE_XID =>
            val xid = readInt(in)
            (JournalItem.SavedXid(xid), 5)
          case CMD_UNREMOVE =>
            val xid = readInt(in)
            (JournalItem.Unremove(xid), 5)
          case CMD_CONFIRM_REMOVE =>
            val xid = readInt(in)
            (JournalItem.ConfirmRemove(xid), 5)
          case CMD_ADD_XID =>
            val xid = readInt(in)
            val data = readBlock(in)
            val item = QItem.unpack(data)
            item.xid = xid
            (JournalItem.Add(item), 9 + data.length)
          case CMD_CONTINUE =>
            val xid = readInt(in)
            val data = readBlock(in)
            val item = QItem.unpack(data)
            (JournalItem.Continue(item, xid), 9 + data.length)
          case n =>
            throw new BrokenItemException(lastPosition, new IOException("invalid opcode in journal: " + n.toInt + " at position " + (in.position - 1)))
        }
      } catch {
        case ex: IOException =>
          throw new BrokenItemException(lastPosition, ex)
      }
    }
  }

  def walk() = new tools.PythonIterator[(JournalItem, Int)] {
// FIXME
    val in = new FileInputStream(new File(queuePath, queueName)).getChannel
    def apply() = {
      readJournalEntry(in) match {
        case (JournalItem.EndOfFile, _) =>
          in.close()
          None
        case x =>
          Some(x)
      }
    }
  }

  private def readBlock(in: FileChannel): Array[Byte] = {
    val size = readInt(in)
    val data = new Array[Byte](size)
    val dataBuffer = ByteBuffer.wrap(data)
    var x: Int = 0
    do {
      x = in.read(dataBuffer)
    } while (dataBuffer.position < dataBuffer.limit && x >= 0)
    if (x < 0) {
      // we never expect EOF when reading a block.
      throw new IOException("Unexpected EOF")
    }
    data
  }

  private def readInt(in: FileChannel): Int = {
    byteBuffer.rewind
    byteBuffer.limit(4)
    var x: Int = 0
    do {
      x = in.read(byteBuffer)
    } while (byteBuffer.position < byteBuffer.limit && x >= 0)
    if (x < 0) {
      // we never expect EOF when reading an int.
      throw new IOException("Unexpected EOF")
    }
    byteBuffer.rewind
    byteBuffer.getInt()
  }

  private def write(allowSync: Boolean, items: Any*): Int = {
    byteBuffer.clear
    for (item <- items) item match {
      case b: Byte => byteBuffer.put(b)
      case i: Int => byteBuffer.putInt(i)
    }
    byteBuffer.flip
    while (byteBuffer.position < byteBuffer.limit) {
      writer.write(byteBuffer)
    }
    if (allowSync && syncJournal) writer.force(false)
    byteBuffer.limit
  }

  def rotate() {
    writer.close
    val rotatedFile = queueName + "." + Time.now.inMilliseconds
    new File(queuePath, queueName).renameTo(new File(queuePath, rotatedFile))
    size = 0
    open

    if (readerFilename == Some(queueName)) {
      readerFilename = Some(rotatedFile)
    }
    packer ! "pack"
  }

  val packer = actor {
    loop {
      react {
        case "pack" =>
          pack()
      }
    }
  }
  packer.start()

  private def pack() {
    val filenames = Journal.journalsBefore(new File(queuePath), queueName, readerFilename.getOrElse(queueName))
    if (filenames.size > 1) {
      log.info("Packing journals for '%s' ...", queueName)
      val tmpFile = new File(queuePath, queueName + "~~" + Time.now.inMilliseconds)
      val packer = new JournalPacker(filenames.map { new File(queuePath, _).getAbsolutePath },
                                     tmpFile.getAbsolutePath)

      val journal = packer { (bytes1, bytes2) =>
        if (bytes1 == 0 && bytes2 == 0) {
          log.info("Packing '%s' into new journal.", queueName)
        } else {
          log.info("Packing '%s' -> %d / %d", queueName, bytes1, bytes2)
        }
      }

      log.info("Packing '%s' -- erasing old files.", queueName)
      val packFile = new File(queuePath, queueName + ".0.pack")
      tmpFile.renameTo(packFile)
      Journal.cleanUpFinishedPack(new File(queuePath), filenames, packFile.getAbsolutePath)
      log.info("Packing '%s' done.", queueName)
    }
  }
}

object Journal {
  def getQueueNamesFromFolder(path: File): Seq[String] = {
    path.list().filter { name =>
      !(name contains "~~")
    }.map { name =>
      name.split('.')(0)
    }
  }

  def orderedFilesForQueue(path: File, queueName: String): List[String] = {
    val totalFiles = path.list()
    totalFiles.filter { _ startsWith (queueName + ".") }.sortBy { name =>
      name.split('.')(1).toLong
    }.toList
  }

  def cleanUpFinishedPack(path: File, oldFiles: Seq[String], packedFile: String) = {
    oldFiles.foreach { f => new File(path, f).delete() }
    val postPackedFile = packedFile.substring(0, packedFile.length - 5)
    new File(path, packedFile) renameTo new File(path, postPackedFile)
    postPackedFile
  }

  def journalsForQueue(path: File, queueName: String): List[String] = {
    val timedFiles = orderedFilesForQueue(path, queueName)
    val fixedTimedFiles: List[String] = if (timedFiles.exists { _ endsWith ".pack" }) {
      // incomplete packing job died after creating the combined file, before erasing the others.
      // finish the job.
      val doomed = timedFiles.takeWhile { f => !(f endsWith ".pack") }
      val packedFile = timedFiles.find { _ endsWith ".pack" }.get
      val postPackedFile = cleanUpFinishedPack(path, doomed, packedFile)
      List(postPackedFile) ++ (timedFiles.dropWhile { f => !(f endsWith ".pack") }.drop(1))
    } else {
      timedFiles
    }
    val currentFile = path.list().filter { _ == queueName }
    val rv = fixedTimedFiles ++ currentFile
    if (rv.size == 0) {
      List(queueName)
    } else {
      rv
    }
  }

  def journalsBefore(path: File, queueName: String, filename: String): Seq[String] = {
    journalsForQueue(path, queueName).takeWhile { _ != filename }
  }

  def journalAfter(path: File, queueName: String, filename: String): Option[String] = {
    journalsForQueue(path, queueName).dropWhile { _ != filename }.drop(1).headOption
  }
}

redpajama_set_name: RedPajamaGithub


text:
package sagex.phoenix.vfs.sources;

import java.util.Set;

import sagex.phoenix.factory.ConfigurableOption;
import sagex.phoenix.factory.ConfigurableOption.DataType;
import sagex.phoenix.factory.ConfigurableOption.ListSelection;
import sagex.phoenix.factory.Factory;
import sagex.phoenix.vfs.IMediaFolder;

/**
 * Simple factory to create a source using a sage media mask
 *
 * @author seans
 */
public class SageMediaFilesFactory extends Factory<IMediaFolder> {
    public SageMediaFilesFactory() {
        this(null);
    }

    public SageMediaFilesFactory(String mediaMask) {
        super();
        addOption(new ConfigurableOption("mediamask", "Sage Media Mask", mediaMask, DataType.string, true, ListSelection.multi,
                "T:TV,D:DVD,B:BluRay,V:Video,M:Music,P:Pictures"));
    }

    public IMediaFolder create(Set<ConfigurableOption> opts) {
        String mask = getOption("mediamask", opts).getString(null);
        log.info("Creating Source Folder: " + getLabel() + " For Sage Media Files: " + mask);
        IMediaFolder folder = phoenix.umb.GetSageMediaFiles(mask, getLabel());
        if (folder == null || folder.getChildren().size() == 0) {
            log.warn("Sage Source didn't return any media items for mask: " + mask);
        } else {
            log.info("Returned " + folder.getChildren().size() + " items for " + getLabel() + "; mask: " + mask);
        }
        return folder;
    }
}


text:
* cmsisdsp
  * Require to build the CMSIS-DSP PythonWrapper for the Python repository
  * It contains all Python packages
* ComputeLibrary:
  * Some kernels required when building CMSIS-DSP with Neon acceleration
* Examples:
  * Examples of use of CMSIS-DSP
* Include:
  * Include files for CMSIS-DSP
* Platforms:
  * Used for running the CMSIS-DSP test framework on Arm IPSS
* PrivateInclude:
  * Some include needed to build CMSIS-DSP
* PythonWrapper:
  * C code for the CMSIS-DSP PythonWrapper
  * Examples for the PythonWrapper
* Scripts:
  * Debugging scripts
  * Script to generate some coefficient tables used by CMSIS-DSP
* SDFTools:
  * Examples for the Synchronous Data Flow
  * C++ templates for the Synchronous Data Flow
* Source:
  * CMSIS-DSP source
* Testing:
  * CMSIS-DSP Test frameworks
* Toolchain:
  * cmake files for building with gcc or Arm clang

### Files

Some files are needed to generate the PythonWrapper:

* PythonWrapper_README.md
* LICENSE.txt
* MANIFEST.in
* pyproject.toml
* setup.py

cmake files are useful to build CMSIS-DSP and the Test framework.

filterLinkScript.py is used by the cmake build.

cmsisdspconfig.py:

* Web browser UI to generate build configurations

## How to use

This document is explaining how to use cmake with CMSIS-DSP.
(It is not official so not supported. The official way to build is to use the CMSIS-Pack).

The example arm_variance_f32 in folder Examples/ARM/arm_variance_f32 has been modified to also
support cmake and is used as an example in this document.

### Generating the Makefiles

To build example arm_variance_f32 with cmake, you need to create a build folder where the build will take place. Don't build in your source directory.

You can create a build folder in Examples/ARM/arm_variance_f32

Once you are in the build folder, you can use cmake to generate the Makefiles.

The cmake command is requiring several arguments. For instance, to build for m7 with AC6 compiler:

    cmake -DCMAKE_PREFIX_PATH="path to compiler (folder containing the bin folder)" \
    -DCMAKE_TOOLCHAIN_FILE="../../../../armac6.cmake" \
    -DARM_CPU="cortex-m7" \
    -DROOT="../../../../../.." \
    -DPLATFORM="FVP" \
    -G "Unix Makefiles" ..

DCMAKE_PREFIX_PATH is the path to the compiler toolchain. This folder should contain the bin folder where are the compiler executables.

ROOT is pointing to the root CMSIS folder (the one containing CMSIS and Device).

PLATFORM is used to select the boot code for the example. In example below, Fast Model (FVP) is selected and the boot code for fast model will be used.

CMAKE_TOOLCHAIN_FILE is selecting the toolchain (ac6, ac5 or gcc). The files are in CMSIS/DSP.

ARM_CPU is selecting the core. The syntax must be the one recognized by the compiler.
(So for instance different between AC5 and AC6).

The final .. is the path to the directory containing the CMakeLists.txt of the variance example.
Since the build folder is assumed to be created in arm_variance_examples then the path to CMakeLists.txt from the build folder is ..

To build for A5, you need to change DCMAKE_TOOLCHAIN_FILE and ARM_CPU:

    -DCMAKE_TOOLCHAIN_FILE=../../../../armac5.cmake
    -DARM_CPU="cortex-a5"

To build for A5 with Neon acceleration, you need to add:

    -DNEON=ON

### Building

Once cmake has generated the makefiles, you can use a GNU Make to build.

    make VERBOSE=1

### Running

The generated executable can be run on a fast model.
For instance, if you built for m7, you could just do:

    FVP_MPS2_Cortex-M7.exe -a arm_variance_example

The final executable has no extension in the filename.

## Building only the CMSIS-DSP library

If you want to build only the CMSIS-DSP library and don't link with any boot code then you'll need to write a specific cmake.

Create a folder BuildCMSISOnly.

Inside the folder, create a CMakeLists.txt with the following content:

```cmake
cmake_minimum_required (VERSION 3.14)

# Define the project
project (testcmsisdsp VERSION 0.1)

# Define the path to CMSIS-DSP (ROOT is defined on command line when using cmake)
set(DSP ${ROOT}/CMSIS/DSP)

# Add DSP folder to module path
list(APPEND CMAKE_MODULE_PATH ${DSP})

###########
#
# CMSIS DSP
#

# Load CMSIS-DSP definitions. Libraries will be built in bin_dsp
add_subdirectory(${DSP}/Source bin_dsp)
```

Create a build folder inside the BuildCMSISOnly folder.

Inside the build folder, type following cmake command

    cmake -DROOT="path to CMSIS Root" \
      -DCMAKE_PREFIX_PATH="path to compiler (folder containing the bin folder)" \
      -DCMAKE_TOOLCHAIN_FILE="../../CMSIS_ROOT/CMSIS/DSP/armac6.cmake" \
      -DARM_CPU="cortex-m7" \
      -G "Unix Makefiles" ..

Now you can make:

    make VERBOSE=1

When the build has finished, you'll have a bin_dsp folder inside your build folder.
Inside bin_dsp, you'll have a folder per CMSIS-DSP Folder : BasicMathFunctions ...

Inside each of those folders, you'll  have a library : libCMSISDSPBasicMath.a ...

## Compilation symbols for tables

Some new compilations symbols have been introduced to avoid including all the tables if they are not needed.

If no new symbol is defined, everything will behave as usual. If ARM_DSP_CONFIG_TABLES is defined then the new symbols will be taken into account.

It is strongly suggested to use the new Python script cmsisdspconfig.py to generate the -D options to use on the compiler command line.

    pip install streamlit
    streamlit run cmsisdspconfig.py

If you use cmake, it is also easy since high level options are defined and they will select the right compilation symbols.

For instance, if you want to use the arm_rfft_fast_f32, in fft.cmake you'll see an option RFFT_FAST_F32_32.

If you don't use cmake nor the Python script, you can just look at fft.cmake or interpol.cmake in Source to see which compilation symbols are needed.

We see, for arm_rfft_fast_f32, that the following symbols need to be enabled :

* ARM_TABLE_TWIDDLECOEF_F32_16
* ARM_TABLE_BITREVIDX_FLT_16
* ARM_TABLE_TWIDDLECOEF_RFFT_F32_32
* ARM_TABLE_TWIDDLECOEF_F32_16

In addition to that, ARM_DSP_CONFIG_TABLES must be enabled and finally ARM_FFT_ALLOW_TABLES must also be defined.

This last symbol is required because if no transform functions are included in the build, then by default all flags related to FFT tables are ignored.

## Bit Reverse Tables CMSIS DSP

It is a question coming often.

It is now detailed [in this github issue](https://github.com/ARM-software/CMSIS_5/issues/858)

Someone from the community has written a [Python script to help](https://gist.github.com/rosek86/d0d709852fddf36193071d7f61987bae)


text:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Valve.VR;

namespace Valve.VR
{
    [ExecuteInEditMode]
    public class SteamVR_RenderModel : MonoBehaviour
    {
        public SteamVR_TrackedObject.EIndex index = SteamVR_TrackedObject.EIndex.None;
        protected SteamVR_Input_Sources inputSource;

        public const string modelOverrideWarning = "Model override is really only meant to be used in " +
            "the scene view for lining things up; using it at runtime is discouraged.  Use tracked device " +
            "index instead to ensure the correct model is displayed for all users.";

        [Tooltip(modelOverrideWarning)]
        public string modelOverride;

        [Tooltip("Shader to apply to model.")]
        public Shader shader;

        [Tooltip("Enable to print out when render models are loaded.")]
        public bool verbose = false;

        [Tooltip("If available, break down into separate components instead of loading as a single mesh.")]
        public bool createComponents = true;

        [Tooltip("Update transforms of components at runtime to reflect user action.")]
        public bool updateDynamically = true;

        // Additional controller settings for showing scrollwheel, etc.
        public RenderModel_ControllerMode_State_t controllerModeState;

        // Name of the sub-object which represents the "local" coordinate space for each component.
        public const string k_localTransformName = "attach";

        // Cached name of this render model for updating component transforms at runtime.
        public string renderModelName { get; private set; }

        public bool initializedAttachPoints { get; set; }

        private Dictionary<string, Transform> componentAttachPoints = new Dictionary<string, Transform>();

        private List<MeshRenderer> meshRenderers = new List<MeshRenderer>();

        // If someone knows how to keep these from getting cleaned up every time
        // you exit play mode, let me know.  I've tried marking the RenderModel
        // class below as [System.Serializable] and switching to normal public
        // variables for mesh and material to get them to serialize properly,
        // as well as tried marking the mesh and material objects as
        // DontUnloadUnusedAsset, but Unity was still unloading them.
        // The hashtable is preserving its entries, but the mesh and material
        // variables are going null.

        public class RenderModel
        {
            public RenderModel(Mesh mesh, Material material)
            {
                this.mesh = mesh;
                this.material = material;
            }
            public Mesh mesh { get; private set; }
            public Material material { get; private set; }
        }

        public static Hashtable models = new Hashtable();
        public static Hashtable materials = new Hashtable();

        // Helper class to load render models interface on demand and clean up when done.
        public sealed class RenderModelInterfaceHolder : System.IDisposable
        {
            private bool needsShutdown, failedLoadInterface;
            private CVRRenderModels _instance;
            public CVRRenderModels instance
            {
                get
                {
                    if (_instance == null && !failedLoadInterface)
                    {
                        if (Application.isEditor && Application.isPlaying == false)
                            needsShutdown = SteamVR.InitializeTemporarySession();

                        _instance = OpenVR.RenderModels;
                        if (_instance == null)
                        {
                            Debug.LogError("[SteamVR] Failed to load IVRRenderModels interface version " + OpenVR.IVRRenderModels_Version);
                            failedLoadInterface = true;
                        }
                    }
                    return _instance;
                }
            }
            public void Dispose()
            {
                if (needsShutdown)
                    SteamVR.ExitTemporarySession();
            }
        }

        private void OnModelSkinSettingsHaveChanged(VREvent_t vrEvent)
        {
            if (!string.IsNullOrEmpty(renderModelName))
            {
                renderModelName = "";
                UpdateModel();
            }
        }

        public void SetMeshRendererState(bool state)
        {
            for (int rendererIndex = 0; rendererIndex < meshRenderers.Count; rendererIndex++)
            {
                MeshRenderer renderer = meshRenderers[rendererIndex];

                if (renderer != null)
                    renderer.enabled = state;
            }
        }

        private void OnHideRenderModels(bool hidden)
        {
            SetMeshRendererState(!hidden);
        }

        private void OnDeviceConnected(int i, bool connected)
        {
            if (i != (int)index)
                return;

            if (connected)
            {
                UpdateModel();
            }
        }

        public void UpdateModel()
        {
            var system = OpenVR.System;
            if (system == null || index == SteamVR_TrackedObject.EIndex.None)
                return;

            var error = ETrackedPropertyError.TrackedProp_Success;
            var capacity = system.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_RenderModelName_String, null, 0, ref error);
            if (capacity <= 1)
            {
                Debug.LogError("[SteamVR] Failed to get render model name for tracked object " + index);
                return;
            }

            var buffer = new System.Text.StringBuilder((int)capacity);
            system.GetStringTrackedDeviceProperty((uint)index, ETrackedDeviceProperty.Prop_RenderModelName_String, buffer, capacity, ref error);

            var s = buffer.ToString();
            if (renderModelName != s)
            {
                StartCoroutine(SetModelAsync(s));
            }
        }

        IEnumerator SetModelAsync(string newRenderModelName)
        {
            meshRenderers.Clear();

            if (string.IsNullOrEmpty(newRenderModelName))
                yield break;

            // Preload all render models before asking for the data to create meshes.
            using (RenderModelInterfaceHolder holder = new RenderModelInterfaceHolder())
            {
                CVRRenderModels renderModels = holder.instance;
                if (renderModels == null)
                    yield break;

                // Gather names of render models to preload.
                string[] renderModelNames;

                uint count = renderModels.GetComponentCount(newRenderModelName);
                if (count > 0)
                {
                    renderModelNames = new string[count];

                    for (int componentIndex = 0; componentIndex < count; componentIndex++)
                    {
                        uint capacity = renderModels.GetComponentName(newRenderModelName, (uint)componentIndex, null, 0);
                        if (capacity == 0)
                            continue;

                        var componentNameStringBuilder = new System.Text.StringBuilder((int)capacity);
                        if (renderModels.GetComponentName(newRenderModelName, (uint)componentIndex, componentNameStringBuilder, capacity) == 0)
                            continue;

                        string componentName = componentNameStringBuilder.ToString();

                        capacity = renderModels.GetComponentRenderModelName(newRenderModelName, componentName, null, 0);
                        if (capacity == 0)
                            continue;

                        var nameStringBuilder = new System.Text.StringBuilder((int)capacity);
                        if (renderModels.GetComponentRenderModelName(newRenderModelName, componentName, nameStringBuilder, capacity) == 0)
                            continue;

                        var s = nameStringBuilder.ToString();

                        // Only need to preload if not already cached.
                        RenderModel model = models[s] as RenderModel;
                        if (model == null || model.mesh == null)
                        {
                            renderModelNames[componentIndex] = s;
                        }
                    }
                }
                else
                {
                    // Only need to preload if not already cached.
                    RenderModel model = models[newRenderModelName] as RenderModel;
                    if (model == null || model.mesh == null)
                    {
                        renderModelNames = new string[] { newRenderModelName };
                    }
                    else
                    {
                        renderModelNames = new string[0];
                    }
                }

                // Keep trying every 100ms until all components finish loading.
                while (true)
                {
                    var loading = false;
                    for (int renderModelNameIndex = 0; renderModelNameIndex < renderModelNames.Length; renderModelNameIndex++)
                    {
                        if (string.IsNullOrEmpty(renderModelNames[renderModelNameIndex]))
                            continue;

                        var pRenderModel = System.IntPtr.Zero;

                        var error = renderModels.LoadRenderModel_Async(renderModelNames[renderModelNameIndex], ref pRenderModel);
                        //Debug.Log("[SteamVR] renderModels.LoadRenderModel_Async(" + renderModelNames[renderModelNameIndex] + ": " + error.ToString());

                        if (error == EVRRenderModelError.Loading)
                        {
                            loading = true;
                        }
                        else if (error == EVRRenderModelError.None)
                        {
                            // Preload textures as well.
                            var renderModel = MarshalRenderModel(pRenderModel);

                            // Check the cache first.
                            var material = materials[renderModel.diffuseTextureId] as Material;
                            if (material == null || material.mainTexture == null)
                            {
                                var pDiffuseTexture = System.IntPtr.Zero;

                                error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
                                //Debug.Log("[SteamVR] renderModels.LoadRenderModel_Async(" + renderModelNames[renderModelNameIndex] + ": " + error.ToString());

                                if (error == EVRRenderModelError.Loading)
                                {
                                    loading = true;
                                }
                            }
                        }
                    }

                    if (loading)
                    {
                        yield return new WaitForSecondsRealtime(0.1f);
                    }
                    else
                    {
                        break;
                    }
                }
            }

            bool success = SetModel(newRenderModelName);
            this.renderModelName = newRenderModelName;
            SteamVR_Events.RenderModelLoaded.Send(this, success);
        }

        private bool SetModel(string renderModelName)
        {
            StripMesh(gameObject);

            using (var holder = new RenderModelInterfaceHolder())
            {
                if (createComponents)
                {
                    componentAttachPoints.Clear();

                    if (LoadComponents(holder, renderModelName))
                    {
                        UpdateComponents(holder.instance);
                        return true;
                    }

                    Debug.Log("[SteamVR] [" + gameObject.name + "] Render model does not support components, falling back to single mesh.");
                }

                if (!string.IsNullOrEmpty(renderModelName))
                {
                    var model = models[renderModelName] as RenderModel;
                    if (model == null || model.mesh == null)
                    {
                        var renderModels = holder.instance;
                        if (renderModels == null)
                            return false;

                        if (verbose)
                            Debug.Log("[SteamVR] Loading render model " + renderModelName);

                        model = LoadRenderModel(renderModels, renderModelName, renderModelName);
                        if (model == null)
                            return false;

                        models[renderModelName] = model;
                    }

                    gameObject.AddComponent<MeshFilter>().mesh = model.mesh;
                    MeshRenderer newRenderer = gameObject.AddComponent<MeshRenderer>();
                    newRenderer.sharedMaterial = model.material;
                    meshRenderers.Add(newRenderer);
                    return true;
                }
            }

            return false;
        }

        RenderModel LoadRenderModel(CVRRenderModels renderModels, string renderModelName, string baseName)
        {
            var pRenderModel = System.IntPtr.Zero;

            EVRRenderModelError error;
            while (true)
            {
                error = renderModels.LoadRenderModel_Async(renderModelName, ref pRenderModel);
                if (error != EVRRenderModelError.Loading)
                    break;

                Sleep();
            }

            if (error != EVRRenderModelError.None)
            {
                Debug.LogError(string.Format("[SteamVR] Failed to load render model {0} - {1}", renderModelName, error.ToString()));
                return null;
            }

            var renderModel = MarshalRenderModel(pRenderModel);

            var vertices = new Vector3[renderModel.unVertexCount];
            var normals = new Vector3[renderModel.unVertexCount];
            var uv = new Vector2[renderModel.unVertexCount];

            var type = typeof(RenderModel_Vertex_t);
            for (int iVert = 0; iVert < renderModel.unVertexCount; iVert++)
            {
                var ptr = new System.IntPtr(renderModel.rVertexData.ToInt64() + iVert * Marshal.SizeOf(type));
                var vert = (RenderModel_Vertex_t)Marshal.PtrToStructure(ptr, type);

                vertices[iVert] = new Vector3(vert.vPosition.v0, vert.vPosition.v1, -vert.vPosition.v2);
                normals[iVert] = new Vector3(vert.vNormal.v0, vert.vNormal.v1, -vert.vNormal.v2);
                uv[iVert] = new Vector2(vert.rfTextureCoord0, vert.rfTextureCoord1);
            }

            int indexCount = (int)renderModel.unTriangleCount * 3;
            var indices = new short[indexCount];
            Marshal.Copy(renderModel.rIndexData, indices, 0, indices.Length);

            var triangles = new int[indexCount];
            for (int iTri = 0; iTri < renderModel.unTriangleCount; iTri++)
            {
                triangles[iTri * 3 + 0] = (int)indices[iTri * 3 + 2];
                triangles[iTri * 3 + 1] = (int)indices[iTri * 3 + 1];
                triangles[iTri * 3 + 2] = (int)indices[iTri * 3 + 0];
            }

            var mesh = new Mesh();
            mesh.vertices = vertices;
            mesh.normals = normals;
            mesh.uv = uv;
            mesh.triangles = triangles;

#if (UNITY_5_4 || UNITY_5_3 || UNITY_5_2 || UNITY_5_1 || UNITY_5_0)
            mesh.Optimize();
#endif
            //mesh.hideFlags = HideFlags.DontUnloadUnusedAsset;

            // Check cache before loading texture.
            var material = materials[renderModel.diffuseTextureId] as Material;
            if (material == null || material.mainTexture == null)
            {
                var pDiffuseTexture = System.IntPtr.Zero;

                while (true)
                {
                    error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);
                    if (error != EVRRenderModelError.Loading)
                        break;

                    Sleep();
                }

                if (error == EVRRenderModelError.None)
                {
                    var diffuseTexture = MarshalRenderModel_TextureMap(pDiffuseTexture);
                    var texture = new Texture2D(diffuseTexture.unWidth, diffuseTexture.unHeight, TextureFormat.RGBA32, false);
                    if (SystemInfo.graphicsDeviceType == UnityEngine.Rendering.GraphicsDeviceType.Direct3D11)
                    {
                        texture.Apply();
                        System.IntPtr texturePointer = texture.GetNativeTexturePtr();
                        while (true)
                        {
                            error = renderModels.LoadIntoTextureD3D11_Async(renderModel.diffuseTextureId, texturePointer);
                            if (error != EVRRenderModelError.Loading)
                                break;

                            Sleep();
                        }
                    }
                    else
                    {
                        var textureMapData = new byte[diffuseTexture.unWidth * diffuseTexture.unHeight * 4]; // RGBA
                        Marshal.Copy(diffuseTexture.rubTextureMapData, textureMapData, 0, textureMapData.Length);

                        var colors = new Color32[diffuseTexture.unWidth * diffuseTexture.unHeight];
                        int iColor = 0;
                        for (int iHeight = 0; iHeight < diffuseTexture.unHeight; iHeight++)
                        {
                            for (int iWidth = 0; iWidth < diffuseTexture.unWidth; iWidth++)
                            {
                                var r = textureMapData[iColor++];
                                var g = textureMapData[iColor++];
                                var b = textureMapData[iColor++];
                                var a = textureMapData[iColor++];
                                colors[iHeight * diffuseTexture.unWidth + iWidth] = new Color32(r, g, b, a);
                            }
                        }

                        texture.SetPixels32(colors);
                        texture.Apply();
                    }

                    material = new Material(shader != null ? shader : Shader.Find("Standard"));
                    material.mainTexture = texture;
                    //material.hideFlags = HideFlags.DontUnloadUnusedAsset;

                    materials[renderModel.diffuseTextureId] = material;

                    renderModels.FreeTexture(pDiffuseTexture);
                }
                else
                {
                    Debug.Log("[SteamVR] Failed to load render model texture for render model " + renderModelName + ". Error: " + error.ToString());
                }
            }

            // Delay freeing when we can since we'll often get multiple requests for the same model right
            // after another (e.g. two controllers or two basestations).
#if UNITY_EDITOR
            if (!Application.isPlaying)
                renderModels.FreeRenderModel(pRenderModel);
            else
#endif
                StartCoroutine(FreeRenderModel(pRenderModel));

            return new RenderModel(mesh, material);
        }

        IEnumerator FreeRenderModel(System.IntPtr pRenderModel)
        {
            yield return new WaitForSeconds(1.0f);

            using (var holder = new RenderModelInterfaceHolder())
            {
                var renderModels = holder.instance;
                renderModels.FreeRenderModel(pRenderModel);
            }
        }

        public Transform FindTransformByName(string componentName, Transform inTransform = null)
        {
            if (inTransform == null)
                inTransform = this.transform;

            for (int childIndex = 0; childIndex < inTransform.childCount; childIndex++)
            {
                Transform child = inTransform.GetChild(childIndex);
                if (child.name == componentName)
                    return child;
            }

            return null;
        }

        public Transform GetComponentTransform(string componentName)
        {
            if (componentName == null)
                return this.transform;

            if (componentAttachPoints.ContainsKey(componentName))
                return componentAttachPoints[componentName];

            return null;
        }

        private void StripMesh(GameObject go)
        {
            var meshRenderer = go.GetComponent<MeshRenderer>();
            if (meshRenderer != null)
                DestroyImmediate(meshRenderer);

            var meshFilter = go.GetComponent<MeshFilter>();
            if (meshFilter != null)
                DestroyImmediate(meshFilter);
        }

        private bool LoadComponents(RenderModelInterfaceHolder holder, string renderModelName)
        {
            // Disable existing components (we will re-enable them if referenced by this new model).
            // Also strip mesh filter and renderer since these will get re-added if the new component needs them.
            var t = transform;
            for (int childIndex = 0; childIndex < t.childCount; childIndex++)
            {
                var child = t.GetChild(childIndex);
                child.gameObject.SetActive(false);
                StripMesh(child.gameObject);
            }

            // If no model specified, we're done; return success.
            if (string.IsNullOrEmpty(renderModelName))
                return true;

            var renderModels = holder.instance;
            if (renderModels == null)
                return false;

            var count = renderModels.GetComponentCount(renderModelName);
            if (count == 0)
                return false;

            for (int i = 0; i < count; i++)
            {
                var capacity = renderModels.GetComponentName(renderModelName, (uint)i, null, 0);
                if (capacity == 0)
                    continue;

                System.Text.StringBuilder componentNameStringBuilder = new System.Text.StringBuilder((int)capacity);
                if (renderModels.GetComponentName(renderModelName, (uint)i, componentNameStringBuilder, capacity) == 0)
                    continue;

                string componentName = componentNameStringBuilder.ToString();

                // Create (or reuse) a child object for this component (some components are dynamic and don't have meshes).
                t = FindTransformByName(componentName);
                if (t != null)
                {
                    t.gameObject.SetActive(true);
                    componentAttachPoints[componentName] = FindTransformByName(k_localTransformName, t);
                }
                else
                {
                    t = new GameObject(componentName).transform;
                    t.parent = transform;
                    t.gameObject.layer = gameObject.layer;

                    // Also create a child 'attach' object for attaching things.
                    var attach = new GameObject(k_localTransformName).transform;
                    attach.parent = t;
                    attach.localPosition = Vector3.zero;
                    attach.localRotation = Quaternion.identity;
                    attach.localScale = Vector3.one;
                    attach.gameObject.layer = gameObject.layer;

                    componentAttachPoints[componentName] = attach;
                }

                // Reset transform.
                t.localPosition = Vector3.zero;
                t.localRotation = Quaternion.identity;
                t.localScale = Vector3.one;

                capacity = renderModels.GetComponentRenderModelName(renderModelName, componentName, null, 0);
                if (capacity == 0)
                    continue;

                var componentRenderModelNameStringBuilder = new System.Text.StringBuilder((int)capacity);
                if (renderModels.GetComponentRenderModelName(renderModelName, componentName, componentRenderModelNameStringBuilder, capacity) == 0)
                    continue;

                string componentRenderModelName = componentRenderModelNameStringBuilder.ToString();

                // Check the cache or load into memory.
                var model = models[componentRenderModelName] as RenderModel;
                if (model == null || model.mesh == null)
                {
                    if (verbose)
                        Debug.Log("[SteamVR] Loading render model " + componentRenderModelName);

                    model = LoadRenderModel(renderModels, componentRenderModelName, renderModelName);
                    if (model == null)
                        continue;

                    models[componentRenderModelName] = model;
                }

                t.gameObject.AddComponent<MeshFilter>().mesh = model.mesh;
                MeshRenderer newRenderer = t.gameObject.AddComponent<MeshRenderer>();
                newRenderer.sharedMaterial = model.material;
                meshRenderers.Add(newRenderer);
            }

            return true;
        }

        SteamVR_Events.Action deviceConnectedAction, hideRenderModelsAction, modelSkinSettingsHaveChangedAction;

        SteamVR_RenderModel()
        {
            deviceConnectedAction = SteamVR_Events.DeviceConnectedAction(OnDeviceConnected);
            hideRenderModelsAction = SteamVR_Events.HideRenderModelsAction(OnHideRenderModels);
            modelSkinSettingsHaveChangedAction = SteamVR_Events.SystemAction(EVREventType.VREvent_ModelSkinSettingsHaveChanged, OnModelSkinSettingsHaveChanged);
        }

        void OnEnable()
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
                return;
#endif
            if (!string.IsNullOrEmpty(modelOverride))
            {
                Debug.Log("[SteamVR] " + modelOverrideWarning);
                enabled = false;
                return;
            }

            var system = OpenVR.System;
            if (system != null && system.IsTrackedDeviceConnected((uint)index))
            {
                UpdateModel();
            }

            deviceConnectedAction.enabled = true;
            hideRenderModelsAction.enabled = true;
            modelSkinSettingsHaveChangedAction.enabled = true;
        }

        void OnDisable()
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
                return;
#endif
            deviceConnectedAction.enabled = false;
            hideRenderModelsAction.enabled = false;
            modelSkinSettingsHaveChangedAction.enabled = false;
        }

#if UNITY_EDITOR
        Hashtable values;
#endif
        void Update()
        {
#if UNITY_EDITOR
            if (!Application.isPlaying)
            {
                // See if anything has changed since this gets called whenever anything gets touched.
                var fields = GetType().GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);

                bool modified = false;

                if (values == null)
                {
                    modified = true;
                }
                else
                {
                    foreach (var f in fields)
                    {
                        if (!values.Contains(f))
                        {
                            modified = true;
                            break;
                        }

                        var v0 = values[f];
                        var v1 = f.GetValue(this);
                        if (v1 != null)
                        {
                            if (!v1.Equals(v0))
                            {
                                modified = true;
                                break;
                            }
                        }
                        else if (v0 != null)
                        {
                            modified = true;
                            break;
                        }
                    }
                }

                if (modified)
                {
                    if (renderModelName != modelOverride)
                    {
                        renderModelName = modelOverride;
                        SetModel(modelOverride);
                    }

                    values = new Hashtable();
                    foreach (var f in fields)
                        values[f] = f.GetValue(this);
                }

                return; // Do not update transforms (below) when not playing in Editor (to avoid keeping OpenVR running all the time).
            }
#endif
            // Update component transforms dynamically.
            if (updateDynamically)
                UpdateComponents(OpenVR.RenderModels);
        }

        Dictionary<int, string> nameCache;

        public void UpdateComponents(CVRRenderModels renderModels)
        {
            if (renderModels == null)
                return;

            if (transform.childCount == 0)
                return;

            if (nameCache == null)
                nameCache = new Dictionary<int, string>();

            for (int childIndex = 0; childIndex < transform.childCount; childIndex++)
            {
                Transform child = transform.GetChild(childIndex);

                // Cache names since accessing an object's name allocate memory.
                string componentName;
                if (!nameCache.TryGetValue(child.GetInstanceID(), out componentName))
                {
                    componentName = child.name;
                    nameCache.Add(child.GetInstanceID(), componentName);
                }

                var componentState = new RenderModel_ComponentState_t();
                if (!renderModels.GetComponentStateForDevicePath(renderModelName, componentName, SteamVR_Input_Source.GetHandle(inputSource), ref controllerModeState, ref componentState))
                    continue;

                child.localPosition = SteamVR_Utils.GetPosition(componentState.mTrackingToComponentRenderModel);
                child.localRotation = SteamVR_Utils.GetRotation(componentState.mTrackingToComponentRenderModel);

                Transform attach = null;
                for (int childChildIndex = 0; childChildIndex < child.childCount; childChildIndex++)
                {
                    Transform childChild = child.GetChild(childChildIndex);
                    int childInstanceID = childChild.GetInstanceID();
                    string childName;
                    if (!nameCache.TryGetValue(childInstanceID, out childName))
                    {
                        childName = childChild.name;
                        nameCache.Add(childInstanceID, componentName);
                    }

                    if (childName == SteamVR_RenderModel.k_localTransformName)
                        attach = childChild;
                }

                if (attach != null)
                {
                    attach.position = transform.TransformPoint(SteamVR_Utils.GetPosition(componentState.mTrackingToComponentLocal));
                    attach.rotation = transform.rotation * SteamVR_Utils.GetRotation(componentState.mTrackingToComponentLocal);

                    initializedAttachPoints = true;
                }

                bool visible = (componentState.uProperties & (uint)EVRComponentProperty.IsVisible) != 0;
                if (visible != child.gameObject.activeSelf)
                {
                    child.gameObject.SetActive(visible);
                }
            }
        }

        public void SetDeviceIndex(int newIndex)
        {
            this.index = (SteamVR_TrackedObject.EIndex)newIndex;

            modelOverride = "";

            if (enabled)
            {
                UpdateModel();
            }
        }

        public void SetInputSource(SteamVR_Input_Sources newInputSource)
        {
            inputSource = newInputSource;
        }

        private static void Sleep()
        {
#if !UNITY_METRO
            //System.Threading.Thread.SpinWait(1); //faster napping
            System.Threading.Thread.Sleep(1);
#endif
        }

        ///
        /// Helper function to handle the inconvenient fact that the packing for RenderModel_t is
        /// different on Linux/OSX (4) than it is on Windows (8)
        ///
        /// <param name="pRenderModel">native pointer to the RenderModel_t</param>
        /// <returns></returns>
        private RenderModel_t MarshalRenderModel(System.IntPtr pRenderModel)
        {
            if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
                (System.Environment.OSVersion.Platform == System.PlatformID.Unix))
            {
                var packedModel = (RenderModel_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t_Packed));
                RenderModel_t model = new RenderModel_t();
                packedModel.Unpack(ref model);
                return model;
            }
            else
            {
                return (RenderModel_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_t));
            }
        }

        ///
        /// Helper function to handle the inconvenient fact that the packing for RenderModel_TextureMap_t is
        /// different on Linux/OSX (4) than it is on Windows (8)
        ///
        /// <param name="pRenderModel">native pointer to the RenderModel_TextureMap_t</param>
        /// <returns></returns>
        private RenderModel_TextureMap_t MarshalRenderModel_TextureMap(System.IntPtr pRenderModel)
        {
            if ((System.Environment.OSVersion.Platform == System.PlatformID.MacOSX) ||
                (System.Environment.OSVersion.Platform == System.PlatformID.Unix))
            {
                var packedModel = (RenderModel_TextureMap_t_Packed)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t_Packed));
                RenderModel_TextureMap_t model = new RenderModel_TextureMap_t();
                packedModel.Unpack(ref model);
                return model;
            }
            else
            {
                return (RenderModel_TextureMap_t)Marshal.PtrToStructure(pRenderModel, typeof(RenderModel_TextureMap_t));
            }
        }
    }
}


text:
package status

import (
	"reflect"
	"sync"

	"k8s.io/apimachinery/pkg/api/errors"
	"k8s.io/apimachinery/pkg/api/meta"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/types"

	v1 "kubevirt.io/client-go/api/v1"
	"kubevirt.io/client-go/kubecli"
)

// updater transparently switches for status updates between /status and the main entrypoint for resource,
// allowing CRDs to enable or disable the status subresource support anytime.
type updater struct {
	lock        sync.Mutex
	subresource bool
	cli         kubecli.KubevirtClient
}

func (u *updater) update(obj runtime.Object) (err error) {
	if u.getSubresource() {
		return u.updateWithSubresource(obj)
	} else {
		return u.updateWithoutSubresource(obj)
	}
}

func (u *updater) patch(obj runtime.Object, pt types.PatchType, data []byte) (err error) {
	if u.getSubresource() {
		return u.patchWithSubresource(obj, pt, data)
	} else {
		return u.patchWithoutSubresource(obj, pt, data)
	}
}

// updateWithoutSubresource will try to update the  status via PUT sent to the main REST endpoint.
// If status of the returned object did not change, it knows that it should have used the /status subresource
// and will switch the updater itself over to permanently use the /status subresource.
func (u *updater) updateWithoutSubresource(obj runtime.Object) (err error) {
	oldStatus, newStatus, err := u.updateUnstructured(obj)
	if err != nil {
		return err
	}
	if !reflect.DeepEqual(oldStatus, newStatus) {
		u.setSubresource(true)
		return u.updateStatusUnstructured(obj)
	}
	return nil
}

// updateWithSubresource will try to update the  status via PUT sent to the /status subresource.
// If a 404 error is returned, it will try the main rest entrypoint instead. In case that this
// call succeeds, it will switch the updater to permanently use the main entrypoint.
func (u *updater) updateWithSubresource(obj runtime.Object) (updateStatusErr error) {
	updateStatusErr = u.updateStatusUnstructured(obj)
	if updateStatusErr != nil && !errors.IsNotFound(updateStatusErr) {
		return updateStatusErr
	}
	if errors.IsNotFound(updateStatusErr) {
		oldStatus, newStatus, err := u.updateUnstructured(obj)
		if errors.IsNotFound(err) {
			// object does not exist
			return err
		}
		if err == nil && reflect.DeepEqual(oldStatus, newStatus) {
			u.setSubresource(false)
		} else if err == nil {
			return updateStatusErr
		}
		return err
	} else {
		return updateStatusErr
	}
}

// patchWithoutSubresource will try to update the  status via PATCH sent to the main REST endpoint.
// If the resource version of the returned object did not change, it knows that it should have used the /status subresource
// and will switch the updater itself over to permanently use the /status subresource.
func (u *updater) patchWithoutSubresource(obj runtime.Object, patchType types.PatchType, data []byte) (err error) {
	oldResourceVersion, newResourceVersion, err := u.patchUnstructured(obj, patchType, data)
	if err != nil {
		return err
	}
	if oldResourceVersion == newResourceVersion {
		u.setSubresource(true)
		return u.patchStatusUnstructured(obj, patchType, data)
	}
	return nil
}

// patchWithSubresource will try to update the  status via PATCH sent to the /status subresource.
// If a 404 error is returned, it will try the main rest entrypoint instead. In case that this
// call succeeds, it will switch the updater to permanently use the main entrypoint.
func (u *updater) patchWithSubresource(obj runtime.Object, patchType types.PatchType, data []byte) (patchStatusErr error) {
	patchStatusErr = u.patchStatusUnstructured(obj, patchType, data)
	if patchStatusErr != nil && !errors.IsNotFound(patchStatusErr) {
		return patchStatusErr
	}
	if errors.IsNotFound(patchStatusErr) {
		oldResourceVersion, newResourceVersions, err := u.patchUnstructured(obj, patchType, data)
		if errors.IsNotFound(err) {
			// object does not exist
			return err
		}
		if err == nil && oldResourceVersion != newResourceVersions {
			u.setSubresource(false)
		} else if err == nil {
			return patchStatusErr
		}
		return err
	} else {
		return patchStatusErr
	}
}

func (u *updater) patchUnstructured(obj runtime.Object, patchType types.PatchType, data []byte) (oldResourceVersion, newResourceVerions string, err error) {
	a, err := meta.Accessor(obj)
	if err != nil {
		return "", "", err
	}
	switch obj.(type) {
	case *v1.VirtualMachine:
		oldObj := obj.(*v1.VirtualMachine)
		newObj, err := u.cli.VirtualMachine(a.GetNamespace()).Patch(a.GetName(), patchType, data)
		if err != nil {
			return "", "", err
		}
		return oldObj.ResourceVersion, newObj.ResourceVersion, nil
	case *v1.KubeVirt:
		oldObj := obj.(*v1.KubeVirt)
		newObj, err := u.cli.KubeVirt(a.GetNamespace()).Patch(a.GetName(), patchType, data)
		if err != nil {
			return "", "", err
		}
		return oldObj.ResourceVersion, newObj.ResourceVersion, nil
	default:
		panic("Unknown object")
	}
}

func (u *updater) patchStatusUnstructured(obj runtime.Object, patchType types.PatchType, data []byte) (err error) {
	a, err := meta.Accessor(obj)
	if err != nil {
		return err
	}
	switch obj.(type) {
	case *v1.VirtualMachine:
		_, err = u.cli.VirtualMachine(a.GetNamespace()).PatchStatus(a.GetName(), patchType, data)
		return err
	case *v1.KubeVirt:
		_, err = u.cli.KubeVirt(a.GetNamespace()).PatchStatus(a.GetName(), patchType, data)
		return err
	default:
		panic("Unknown object")
	}
}

func (u *updater) updateUnstructured(obj runtime.Object) (oldStatus interface{}, newStatus interface{}, err error) {
	a, err := meta.Accessor(obj)
	if err != nil {
		return nil, nil, err
	}
	switch obj.(type) {
	case *v1.VirtualMachine:
		oldObj := obj.(*v1.VirtualMachine)
		newObj, err := u.cli.VirtualMachine(a.GetNamespace()).Update(oldObj)
		if err != nil {
			return nil, nil, err
		}
		return oldObj.Status, newObj.Status, nil
	case *v1.VirtualMachineInstanceReplicaSet:
		oldObj := obj.(*v1.VirtualMachineInstanceReplicaSet)
		newObj, err := u.cli.ReplicaSet(a.GetNamespace()).Update(oldObj)
		if err != nil {
			return nil, nil, err
		}
		return oldObj.Status, newObj.Status, nil
	case *v1.VirtualMachineInstanceMigration:
		oldObj := obj.(*v1.VirtualMachineInstanceMigration)
		newObj, err := u.cli.VirtualMachineInstanceMigration(a.GetNamespace()).Update(oldObj)
		if err != nil {
			return nil, nil, err
		}
		return oldObj.Status, newObj.Status, nil
	case *v1.KubeVirt:
		oldObj := obj.(*v1.KubeVirt)
		newObj, err := u.cli.KubeVirt(a.GetNamespace()).Update(oldObj)
		if err != nil {
			return nil, nil, err
		}
		return oldObj.Status, newObj.Status, nil
	default:
		panic("Unknown object")
	}
}

func (u *updater) updateStatusUnstructured(obj runtime.Object) (err error) {
	a, err := meta.Accessor(obj)
	if err != nil {
		return err
	}
	switch obj.(type) {
	case *v1.VirtualMachine:
		oldObj := obj.(*v1.VirtualMachine)
		_, err = u.cli.VirtualMachine(a.GetNamespace()).UpdateStatus(oldObj)
		return err
	case *v1.VirtualMachineInstanceReplicaSet:
		oldObj := obj.(*v1.VirtualMachineInstanceReplicaSet)
		_, err = u.cli.ReplicaSet(a.GetNamespace()).UpdateStatus(oldObj)
		return err
	case *v1.VirtualMachineInstanceMigration:
		oldObj := obj.(*v1.VirtualMachineInstanceMigration)
		_, err = u.cli.VirtualMachineInstanceMigration(a.GetNamespace()).UpdateStatus(oldObj)
		return err
	case *v1.KubeVirt:
		oldObj := obj.(*v1.KubeVirt)
		_, err = u.cli.KubeVirt(a.GetNamespace()).UpdateStatus(oldObj)
		return err
	default:
		panic("Unknown object")
	}
}

func (u *updater) setSubresource(exists bool) {
	u.lock.Lock()
	defer u.lock.Unlock()
	u.subresource = exists
}

func (u *updater) getSubresource() bool {
	u.lock.Lock()
	defer u.lock.Unlock()
	return u.subresource
}

type VMStatusUpdater struct {
	updater updater
}

func (v *VMStatusUpdater) UpdateStatus(vm *v1.VirtualMachine) error {
	return v.updater.update(vm)
}

func (v *VMStatusUpdater) PatchStatus(vm *v1.VirtualMachine, pt types.PatchType, data []byte) error {
	return v.updater.patch(vm, pt, data)
}

func NewVMStatusUpdater(cli kubecli.KubevirtClient) *VMStatusUpdater {
	return &VMStatusUpdater{
		updater: updater{
			lock:        sync.Mutex{},
			subresource: true,
			cli:         cli,
		},
	}
}

type VMIRSStatusUpdater struct {
	updater updater
}

func (v *VMIRSStatusUpdater) UpdateStatus(vmirs *v1.VirtualMachineInstanceReplicaSet) error {
	return v.updater.update(vmirs)
}

func NewVMIRSStatusUpdater(cli kubecli.KubevirtClient) *VMIRSStatusUpdater {
	return &VMIRSStatusUpdater{
		updater: updater{
			lock:        sync.Mutex{},
			subresource: true,
			cli:         cli,
		},
	}
}

type KVStatusUpdater struct {
	updater updater
}

func (v *KVStatusUpdater) UpdateStatus(kv *v1.KubeVirt) error {
	return v.updater.update(kv)
}

func (v *KVStatusUpdater) PatchStatus(kv *v1.KubeVirt, pt types.PatchType, data []byte) error {
	return v.updater.patch(kv, pt, data)
}

func NewKubeVirtStatusUpdater(cli kubecli.KubevirtClient) *KVStatusUpdater {
	return &KVStatusUpdater{
		updater: updater{
			lock:        sync.Mutex{},
			subresource: true,
			cli:         cli,
		},
	}
}

type MigrationStatusUpdater struct {
	updater updater
}

func (v *MigrationStatusUpdater) UpdateStatus(migration *v1.VirtualMachineInstanceMigration) error {
	return v.updater.update(migration)
}

func NewMigrationStatusUpdater(cli kubecli.KubevirtClient) *MigrationStatusUpdater {
	return &MigrationStatusUpdater{
		updater: updater{
			lock:        sync.Mutex{},
			subresource: true,
			cli:         cli,
		},
	}
}


text:
class SkBitmap;

namespace gpu {
namespace gles2 {
class GLES2Interface;
}
}

namespace cc {

class GLRendererShaderTest;
class OutputSurface;
class PictureDrawQuad;
class ScopedResource;
class StreamVideoDrawQuad;
class TextureDrawQuad;
class TextureMailboxDeleter;
class GeometryBinding;
class ScopedEnsureFramebufferAllocation;

// Class that handles drawing of composited render layers using GL.
class CC_EXPORT GLRenderer : public DirectRenderer {
 public:
  static scoped_ptr<GLRenderer> Create(
      RendererClient* client,
      const LayerTreeSettings* settings,
      OutputSurface* output_surface,
      ResourceProvider* resource_provider,
      TextureMailboxDeleter* texture_mailbox_deleter,
      int highp_threshold_min);

  virtual ~GLRenderer();

  virtual const RendererCapabilitiesImpl& Capabilities() const OVERRIDE;

  // Waits for rendering to finish.
  virtual void Finish() OVERRIDE;

  virtual void DoNoOp() OVERRIDE;
  virtual void SwapBuffers(const CompositorFrameMetadata& metadata) OVERRIDE;

  virtual void GetFramebufferPixels(void* pixels,
                                    const gfx::Rect& rect) OVERRIDE;

  virtual bool IsContextLost() OVERRIDE;

  virtual void SetVisible(bool visible) OVERRIDE;

  virtual void SendManagedMemoryStats(size_t bytes_visible,
                                      size_t bytes_visible_and_nearby,
                                      size_t bytes_allocated) OVERRIDE;

  static void DebugGLCall(gpu::gles2::GLES2Interface* gl,
                          const char* command,
                          const char* file,
                          int line);

 protected:
  GLRenderer(RendererClient* client,
             const LayerTreeSettings* settings,
             OutputSurface* output_surface,
             ResourceProvider* resource_provider,
             TextureMailboxDeleter* texture_mailbox_deleter,
             int highp_threshold_min);

  bool IsBackbufferDiscarded() const { return is_backbuffer_discarded_; }
  void InitializeGrContext();

  const gfx::QuadF& SharedGeometryQuad() const { return shared_geometry_quad_; }
  const GeometryBinding* SharedGeometry() const {
    return shared_geometry_.get();
  }

  void GetFramebufferPixelsAsync(const gfx::Rect& rect,
                                 scoped_ptr<CopyOutputRequest> request);
  void GetFramebufferTexture(unsigned texture_id,
                             ResourceFormat texture_format,
                             const gfx::Rect& device_rect);
  void ReleaseRenderPassTextures();

  void SetStencilEnabled(bool enabled);
  bool stencil_enabled() const { return stencil_shadow_; }
  void SetBlendEnabled(bool enabled);
  bool blend_enabled() const { return blend_shadow_; }

  virtual void BindFramebufferToOutputSurface(DrawingFrame* frame) OVERRIDE;
  virtual bool BindFramebufferToTexture(DrawingFrame* frame,
                                        const ScopedResource* resource,
                                        const gfx::Rect& target_rect) OVERRIDE;
  virtual void SetDrawViewport(const gfx::Rect& window_space_viewport) OVERRIDE;
  virtual void SetScissorTestRect(const gfx::Rect& scissor_rect) OVERRIDE;
  virtual void DiscardPixels(bool has_external_stencil_test,
                             bool draw_rect_covers_full_surface) OVERRIDE;
  virtual void ClearFramebuffer(DrawingFrame* frame,
                                bool has_external_stencil_test) OVERRIDE;
  virtual void DoDrawQuad(DrawingFrame* frame, const class DrawQuad*) OVERRIDE;
  virtual void BeginDrawingFrame(DrawingFrame* frame) OVERRIDE;
  virtual void FinishDrawingFrame(DrawingFrame* frame) OVERRIDE;
  virtual bool FlippedFramebuffer() const OVERRIDE;
  virtual void EnsureScissorTestEnabled() OVERRIDE;
  virtual void EnsureScissorTestDisabled() OVERRIDE;
  virtual void CopyCurrentRenderPassToBitmap(
      DrawingFrame* frame,
      scoped_ptr<CopyOutputRequest> request) OVERRIDE;
  virtual void FinishDrawingQuadList() OVERRIDE;

  // Check if quad needs antialiasing and if so, inflate the quad and
  // fill edge array for fragment shader.  local_quad is set to
  // inflated quad if antialiasing is required, otherwise it is left
  // unchanged.  edge array is filled with inflated quad's edge data
  // if antialiasing is required, otherwise it is left unchanged.
  // Returns true if quad requires antialiasing and false otherwise.
  static bool SetupQuadForAntialiasing(const gfx::Transform& device_transform,
                                       const DrawQuad* quad,
                                       gfx::QuadF* local_quad,
                                       float edge[24]);

 private:
  friend class GLRendererShaderPixelTest;
  friend class GLRendererShaderTest;

  static void ToGLMatrix(float* gl_matrix, const gfx::Transform& transform);

  void DrawCheckerboardQuad(const DrawingFrame* frame,
                            const CheckerboardDrawQuad* quad);
  void DrawDebugBorderQuad(const DrawingFrame* frame,
                           const DebugBorderDrawQuad* quad);
  scoped_ptr<ScopedResource> GetBackgroundWithFilters(
      DrawingFrame* frame,
      const RenderPassDrawQuad* quad,
      const gfx::Transform& contents_device_transform,
      const gfx::Transform& contents_device_transformInverse,
      bool* background_changed);
  void DrawRenderPassQuad(DrawingFrame* frame, const RenderPassDrawQuad* quad);
  void DrawSolidColorQuad(const DrawingFrame* frame,
                          const SolidColorDrawQuad* quad);
  void DrawStreamVideoQuad(const DrawingFrame* frame,
                           const StreamVideoDrawQuad* quad);
  void EnqueueTextureQuad(const DrawingFrame* frame,
                          const TextureDrawQuad* quad);
  void FlushTextureQuadCache();
  void DrawIOSurfaceQuad(const DrawingFrame* frame,
                         const IOSurfaceDrawQuad* quad);
  void DrawTileQuad(const DrawingFrame* frame, const TileDrawQuad* quad);
  void DrawContentQuad(const DrawingFrame* frame,
                       const ContentDrawQuadBase* quad,
                       ResourceProvider::ResourceId resource_id);
  void DrawYUVVideoQuad(const DrawingFrame* frame,
                        const YUVVideoDrawQuad* quad);
  void DrawPictureQuad(const DrawingFrame* frame,
                       const PictureDrawQuad* quad);

  void SetShaderOpacity(float opacity, int alpha_location);
  void SetShaderQuadF(const gfx::QuadF& quad, int quad_location);
  void DrawQuadGeometry(const DrawingFrame* frame,
                        const gfx::Transform& draw_transform,
                        const gfx::RectF& quad_rect,
                        int matrix_location);
  void SetUseProgram(unsigned program);

  void CopyTextureToFramebuffer(const DrawingFrame* frame,
                                int texture_id,
                                const gfx::Rect& rect,
                                const gfx::Transform& draw_matrix,
                                bool flip_vertically);

  bool UseScopedTexture(DrawingFrame* frame,
                        const ScopedResource* resource,
                        const gfx::Rect& viewport_rect);

  bool MakeContextCurrent();

  void InitializeSharedObjects();
  void CleanupSharedObjects();

  typedef base::Callback<void(scoped_ptr<CopyOutputRequest> copy_request,
                              bool success)>
      AsyncGetFramebufferPixelsCleanupCallback;
  void DoGetFramebufferPixels(
      uint8* pixels,
      const gfx::Rect& window_rect,
      const AsyncGetFramebufferPixelsCleanupCallback& cleanup_callback);
  void FinishedReadback(
      const AsyncGetFramebufferPixelsCleanupCallback& cleanup_callback,
      unsigned source_buffer,
      unsigned query,
      uint8_t* dest_pixels,
      const gfx::Size& size);
  void PassOnSkBitmap(scoped_ptr<SkBitmap> bitmap,
                      scoped_ptr<SkAutoLockPixels> lock,
                      scoped_ptr<CopyOutputRequest> request,
                      bool success);

  void ReinitializeGLState();

  virtual void DiscardBackbuffer() OVERRIDE;
  virtual void EnsureBackbuffer() OVERRIDE;
  void EnforceMemoryPolicy();

  RendererCapabilitiesImpl capabilities_;

  unsigned offscreen_framebuffer_id_;

  scoped_ptr<GeometryBinding> shared_geometry_;
  gfx::QuadF shared_geometry_quad_;

  // This block of bindings defines all of the programs used by the compositor
  // itself.  Add any new programs here to GLRendererShaderTest.

  // Tiled layer shaders.
  typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexAlpha>
      TileProgram;
  typedef ProgramBinding<VertexShaderTileAA, FragmentShaderRGBATexClampAlphaAA>
      TileProgramAA;
  typedef ProgramBinding<VertexShaderTileAA,
                         FragmentShaderRGBATexClampSwizzleAlphaAA>
      TileProgramSwizzleAA;
  typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexOpaque>
      TileProgramOpaque;
  typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexSwizzleAlpha>
      TileProgramSwizzle;
  typedef ProgramBinding<VertexShaderTile, FragmentShaderRGBATexSwizzleOpaque>
      TileProgramSwizzleOpaque;
  typedef ProgramBinding<VertexShaderPosTex, FragmentShaderCheckerboard>
      TileCheckerboardProgram;

  // Texture shaders.
  typedef ProgramBinding<VertexShaderPosTexTransform,
                         FragmentShaderRGBATexVaryingAlpha> TextureProgram;
  typedef ProgramBinding<VertexShaderPosTexTransform,
                         FragmentShaderRGBATexPremultiplyAlpha>
      NonPremultipliedTextureProgram;
  typedef ProgramBinding<VertexShaderPosTexTransform,
                         FragmentShaderTexBackgroundVaryingAlpha>
      TextureBackgroundProgram;
  typedef ProgramBinding<VertexShaderPosTexTransform,
                         FragmentShaderTexBackgroundPremultiplyAlpha>
      NonPremultipliedTextureBackgroundProgram;

  // Render surface shaders.
  typedef ProgramBinding<VertexShaderPosTexTransform,
                         FragmentShaderRGBATexAlpha> RenderPassProgram;
  typedef ProgramBinding<VertexShaderPosTexTransform,
                         FragmentShaderRGBATexAlphaMask> RenderPassMaskProgram;
  typedef ProgramBinding<VertexShaderQuadTexTransformAA,
                         FragmentShaderRGBATexAlphaAA> RenderPassProgramAA;
  typedef ProgramBinding<VertexShaderQuadTexTransformAA,
                         FragmentShaderRGBATexAlphaMaskAA>
      RenderPassMaskProgramAA;
  typedef ProgramBinding<VertexShaderPosTexTransform,
                         FragmentShaderRGBATexColorMatrixAlpha>
      RenderPassColorMatrixProgram;
  typedef ProgramBinding<VertexShaderQuadTexTransformAA,
                         FragmentShaderRGBATexAlphaMaskColorMatrixAA>
      RenderPassMaskColorMatrixProgramAA;
  typedef ProgramBinding<VertexShaderQuadTexTransformAA,
                         FragmentShaderRGBATexAlphaColorMatrixAA>
      RenderPassColorMatrixProgramAA;
  typedef ProgramBinding<VertexShaderPosTexTransform,
                         FragmentShaderRGBATexAlphaMaskColorMatrix>
      RenderPassMaskColorMatrixProgram;

  // Video shaders.
  typedef ProgramBinding<VertexShaderVideoTransform, FragmentShaderRGBATex>
      VideoStreamTextureProgram;
  typedef ProgramBinding<VertexShaderPosTexYUVStretch, FragmentShaderYUVVideo>
      VideoYUVProgram;
  typedef ProgramBinding<VertexShaderPosTexYUVStretch, FragmentShaderYUVAVideo>
      VideoYUVAProgram;

  // Special purpose / effects shaders.
  typedef ProgramBinding<VertexShaderPos, FragmentShaderColor>
      DebugBorderProgram;
  typedef ProgramBinding<VertexShaderQuad, FragmentShaderColor>
      SolidColorProgram;
  typedef ProgramBinding<VertexShaderQuadAA, FragmentShaderColorAA>
      SolidColorProgramAA;

  const TileProgram* GetTileProgram(
      TexCoordPrecision precision, SamplerType sampler);
  const TileProgramOpaque* GetTileProgramOpaque(
      TexCoordPrecision precision, SamplerType sampler);
  const TileProgramAA* GetTileProgramAA(
      TexCoordPrecision precision, SamplerType sampler);
  const TileProgramSwizzle* GetTileProgramSwizzle(
      TexCoordPrecision precision, SamplerType sampler);
  const TileProgramSwizzleOpaque* GetTileProgramSwizzleOpaque(
      TexCoordPrecision precision, SamplerType sampler);
  const TileProgramSwizzleAA* GetTileProgramSwizzleAA(
      TexCoordPrecision precision, SamplerType sampler);

  const TileCheckerboardProgram* GetTileCheckerboardProgram();

  const RenderPassProgram* GetRenderPassProgram(
      TexCoordPrecision precision);
  const RenderPassProgramAA* GetRenderPassProgramAA(
      TexCoordPrecision precision);
  const RenderPassMaskProgram* GetRenderPassMaskProgram(
      TexCoordPrecision precision);
  const RenderPassMaskProgramAA* GetRenderPassMaskProgramAA(
      TexCoordPrecision precision);
  const RenderPassColorMatrixProgram* GetRenderPassColorMatrixProgram(
      TexCoordPrecision precision);
  const RenderPassColorMatrixProgramAA* GetRenderPassColorMatrixProgramAA(
      TexCoordPrecision precision);
  const RenderPassMaskColorMatrixProgram* GetRenderPassMaskColorMatrixProgram(
      TexCoordPrecision precision);
  const RenderPassMaskColorMatrixProgramAA*
      GetRenderPassMaskColorMatrixProgramAA(TexCoordPrecision precision);

  const TextureProgram* GetTextureProgram(
      TexCoordPrecision precision);
  const NonPremultipliedTextureProgram* GetNonPremultipliedTextureProgram(
      TexCoordPrecision precision);
  const TextureBackgroundProgram* GetTextureBackgroundProgram(
      TexCoordPrecision precision);
  const NonPremultipliedTextureBackgroundProgram*
      GetNonPremultipliedTextureBackgroundProgram(TexCoordPrecision precision);
  const TextureProgram* GetTextureIOSurfaceProgram(
      TexCoordPrecision precision);

  const VideoYUVProgram* GetVideoYUVProgram(
      TexCoordPrecision precision);
  const VideoYUVAProgram* GetVideoYUVAProgram(
      TexCoordPrecision precision);
  const VideoStreamTextureProgram* GetVideoStreamTextureProgram(
      TexCoordPrecision precision);

  const DebugBorderProgram* GetDebugBorderProgram();
  const SolidColorProgram* GetSolidColorProgram();
  const SolidColorProgramAA* GetSolidColorProgramAA();

  TileProgram tile_program_[NumTexCoordPrecisions][NumSamplerTypes];
  TileProgramOpaque
      tile_program_opaque_[NumTexCoordPrecisions][NumSamplerTypes];
  TileProgramAA tile_program_aa_[NumTexCoordPrecisions][NumSamplerTypes];
  TileProgramSwizzle
      tile_program_swizzle_[NumTexCoordPrecisions][NumSamplerTypes];
  TileProgramSwizzleOpaque
      tile_program_swizzle_opaque_[NumTexCoordPrecisions][NumSamplerTypes];
  TileProgramSwizzleAA
      tile_program_swizzle_aa_[NumTexCoordPrecisions][NumSamplerTypes];

  TileCheckerboardProgram tile_checkerboard_program_;

  TextureProgram texture_program_[NumTexCoordPrecisions];
  NonPremultipliedTextureProgram
      nonpremultiplied_texture_program_[NumTexCoordPrecisions];
  TextureBackgroundProgram texture_background_program_[NumTexCoordPrecisions];
  NonPremultipliedTextureBackgroundProgram
      nonpremultiplied_texture_background_program_[NumTexCoordPrecisions];
  TextureProgram texture_io_surface_program_[NumTexCoordPrecisions];

  RenderPassProgram render_pass_program_[NumTexCoordPrecisions];
  RenderPassProgramAA render_pass_program_aa_[NumTexCoordPrecisions];
  RenderPassMaskProgram render_pass_mask_program_[NumTexCoordPrecisions];
  RenderPassMaskProgramAA render_pass_mask_program_aa_[NumTexCoordPrecisions];
  RenderPassColorMatrixProgram
      render_pass_color_matrix_program_[NumTexCoordPrecisions];
  RenderPassColorMatrixProgramAA
      render_pass_color_matrix_program_aa_[NumTexCoordPrecisions];
  RenderPassMaskColorMatrixProgram
      render_pass_mask_color_matrix_program_[NumTexCoordPrecisions];
  RenderPassMaskColorMatrixProgramAA
      render_pass_mask_color_matrix_program_aa_[NumTexCoordPrecisions];

  VideoYUVProgram video_yuv_program_[NumTexCoordPrecisions];
  VideoYUVAProgram video_yuva_program_[NumTexCoordPrecisions];
  VideoStreamTextureProgram
      video_stream_texture_program_[NumTexCoordPrecisions];

  DebugBorderProgram debug_border_program_;
  SolidColorProgram solid_color_program_;
  SolidColorProgramAA solid_color_program_aa_;

  gpu::gles2::GLES2Interface* gl_;
  gpu::ContextSupport* context_support_;

  skia::RefPtr<GrContext> gr_context_;
  skia::RefPtr<SkCanvas> sk_canvas_;

  TextureMailboxDeleter* texture_mailbox_deleter_;

  gfx::Rect swap_buffer_rect_;
  gfx::Rect scissor_rect_;
  gfx::Rect viewport_;
  bool is_backbuffer_discarded_;
  bool is_using_bind_uniform_;
  bool visible_;
  bool is_scissor_enabled_;
  bool scissor_rect_needs_reset_;
  bool stencil_shadow_;
  bool blend_shadow_;
  unsigned program_shadow_;
  TexturedQuadDrawCache draw_cache_;
  int highp_threshold_min_;
  int highp_threshold_cache_;

  struct PendingAsyncReadPixels;
  ScopedPtrVector<PendingAsyncReadPixels> pending_async_read_pixels_;

  scoped_ptr<ResourceProvider::ScopedWriteLockGL> current_framebuffer_lock_;

  scoped_refptr<ResourceProvider::Fence> last_swap_fence_;

  SkBitmap on_demand_tile_raster_bitmap_;
  ResourceProvider::ResourceId on_demand_tile_raster_resource_id_;

  DISALLOW_COPY_AND_ASSIGN(GLRenderer);
};

// Setting DEBUG_GL_CALLS to 1 will call glGetError() after almost every GL
// call made by the compositor. Useful for debugging rendering issues but
// will significantly degrade performance.
#define DEBUG_GL_CALLS 0

#if DEBUG_GL_CALLS && !defined(NDEBUG)
#define GLC(context, x)                                                        \
  (x, GLRenderer::DebugGLCall(&* context, #x, __FILE__, __LINE__))
#else
#define GLC(context, x) (x)
#endif

}  // namespace cc

#endif  // CC_OUTPUT_GL_RENDERER_H_


text:
//     Data Access is a Java library to store data
//     Copyright (C) 2016-2019 Adrián Romero Corchado.
//
//     This file is part of Data Access
//
//     Licensed under the Apache License, Version 2.0 (the "License");
//     you may not use this file except in compliance with the License.
//     You may obtain a copy of the License at
//
//         http://www.apache.org/licenses/LICENSE-2.0
//
//     Unless required by applicable law or agreed to in writing, software
//     distributed under the License is distributed on an "AS IS" BASIS,
//     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//     See the License for the specific language governing permissions and
//     limitations under the License.

package com.adr.data.sql;

import com.adr.data.DataException;
import java.util.ArrayList;
import com.adr.data.record.Record;
import com.adr.data.record.Records;

/**
 *
 * @author adrian
 */
public class SentenceUpdate extends SentenceDML {

    @Override
    public String getName() {
        return "UPDATE";
    }

    @Override
    protected final CommandSQL build(SQLEngine engine, Record record) throws DataException {

        StringBuilder sentencefields = new StringBuilder();
        StringBuilder sentencefilters = new StringBuilder();
        ArrayList<String> namefields = new ArrayList<>();
        ArrayList<String> namefilters = new ArrayList<>();

        sentencefields.append("UPDATE ");
        sentencefields.append(Records.getCollection(record));

        boolean fields = false;
        boolean filters = false;
        String realname;
        for (String f : record.keySet()) {
            if (!f.equals("COLLECTION.KEY") && !f.contains("..")) {
                if (f.endsWith(".KEY")) {
                    realname = f.substring(0, f.length() - 4);
                    sentencefilters.append(filters ? " AND " : " WHERE ");
                    sentencefilters.append(realname);
                    sentencefilters.append(" = ?");
                    namefilters.add(f);
                    filters = true;
                } else {
                    sentencefields.append(fields ? ", " : " SET ");
                    sentencefields.append(f);
                    sentencefields.append(" = ?");
                    namefields.add(f);
                    fields = true;
                }
            }
        }

        sentencefields.append(sentencefilters);
        namefields.addAll(namefilters);

        return new CommandSQL(sentencefields.toString(), namefields.toArray(new String[namefields.size()]));
    }
}


text:
SAMPLES="samples.txt"
TRINITY_FASTA="../../test_DATA/Trinity.fasta"

test: test_RSEM test_eXpress test_kallisto test_salmon
	../../../Analysis/DifferentialExpression/merge_matrices.pl RSEM-trans.TPM.not_cross_norm express-trans.TPM.not_cross_norm kallisto-trans.TPM.not_cross_norm salmon-quasi-trans.TPM.not_cross_norm salmon-fmd-trans.TPM.not_cross_norm > combined.TPM.not_cross_norm.matrix
	../plot_paired_comparisons.Rscript
	touch test

test_RSEM:
ifeq ("", "$(shell which rsem-calculate-expression)")
	echo WARNING: skipping RSEM test, cannot locate rsem-calculate-expression tool in PATH
else
	../align_and_estimate_tester.pl RSEM ${SAMPLES} ${TRINITY_FASTA}
	touch test_RSEM
endif

test_eXpress:
ifeq ("", "$(shell which express)")
	echo WARNING: skipping express test, cant locate express tool in PATH
else
	../align_and_estimate_tester.pl express ${SAMPLES} ${TRINITY_FASTA}
	touch test_eXpress
endif

test_kallisto:
ifeq ("", "$(shell which kallisto)")
	echo WARNING: cannot find kallisto installed in PATH, skipping kallisto test
else
	../align_and_estimate_tester.pl kallisto ${SAMPLES} ${TRINITY_FASTA}
	touch test_kallisto
endif

test_salmon:
ifeq ("", "$(shell which salmon)")
	echo WARNING: cannot find salmon installed in PATH, skipping salmon test
else
	../align_and_estimate_tester.pl salmon-quasi ${SAMPLES} ${TRINITY_FASTA}
	../align_and_estimate_tester.pl salmon-fmd ${SAMPLES} ${TRINITY_FASTA}
	touch test_salmon
endif

clean:
	./cleanme.pl


text:
(function(doc, win) {
  'use strict'
  if (typeof doc.createEvent !== 'function') return false // no tap events here
  // helpers
  var useJquery = typeof jQuery !== 'undefined',
    msEventType = function(type) {
      var lo = type.toLowerCase(),
        ms = 'MS' + type
      return navigator.msPointerEnabled ? ms : lo
    },
    isTouch = function() {
      return 'ontouchstart' in window ||
        window.DocumentTouch && document instanceof DocumentTouch ||
        !!navigator.pointerEnabled || navigator.msPointerEnabled
    },
    isValid = function(e) {
      var _isTouch = isTouch(),
        isMouse = /mouse/.test(e.type)
      return !isMouse && _isTouch || isMouse && !_isTouch
    },
    touchevents = {
      touchstart: msEventType('PointerDown') + ' touchstart',
      touchend: msEventType('PointerUp') + ' touchend',
      touchmove: msEventType('PointerMove') + ' touchmove'
    },
    setListener = function(elm, events, callback) {
      var eventsArray = events.split(' '),
        i = eventsArray.length

      while (i--) {
        elm.addEventListener(eventsArray[i], callback, false)
      }
    },
    getPointerEvent = function(event) {
      return event.targetTouches ? event.targetTouches[0] : event
    },
    getTimestamp = function () {
      return new Date().getTime()
    },
    sendEvent = function(elm, eventName, originalEvent, data) {
      var customEvent = doc.createEvent('Event')
      customEvent.originalEvent = originalEvent
      data = data || {}
      data.x = currX
      data.y = currY
      data.distance = data.distance

      // jquery
      if (useJquery) {
        customEvent = $.Event(eventName, {originalEvent: originalEvent})
        jQuery(elm).trigger(customEvent, data)
      }

      // addEventListener
      if (customEvent.initEvent) {
        for (var key in data) {
          customEvent[key] = data[key]
        }
        customEvent.initEvent(eventName, true, true)
        elm.dispatchEvent(customEvent)
      }

      // inline
      if (elm['on' + eventName])
        elm['on' + eventName](customEvent)
    },

    onTouchStart = function(e) {
      if (!isValid(e)) return
      var pointer = getPointerEvent(e)

      // caching the current x
      cachedX = currX = pointer.pageX
      // caching the current y
      cachedY = currY = pointer.pageY

      longtapTimer = setTimeout(function() {
        sendEvent(e.target, 'longtap', e)
        target = e.target
      }, longtapThreshold)

      // we will use these variables on the touchend events
      timestamp = getTimestamp()
      tapNum++

    },
    onTouchEnd = function(e) {
      if (!isValid(e)) return
      var eventsArr = [],
        now = getTimestamp(),
        deltaY = cachedY - currY,
        deltaX = cachedX - currX

      // clear the previous timer in case it was set
      clearTimeout(dblTapTimer)
      clearTimeout(longtapTimer)

      if (deltaX <= -swipeThreshold)
        eventsArr.push('swiperight')

      if (deltaX >= swipeThreshold)
        eventsArr.push('swipeleft')

      if (deltaY <= -swipeThreshold)
        eventsArr.push('swipedown')

      if (deltaY >= swipeThreshold)
        eventsArr.push('swipeup')

      if (eventsArr.length) {
        for (var i = 0; i < eventsArr.length; i++) {
          var eventName = eventsArr[i]
          sendEvent(e.target, eventName, e, {
            distance: {
              x: Math.abs(deltaX),
              y: Math.abs(deltaY)
            }
          })
        }
      } else {

        if (
          cachedX >= currX - tapPrecision &&
          cachedX <= currX + tapPrecision &&
          cachedY >= currY - tapPrecision &&
          cachedY <= currY + tapPrecision
        ) {
          if (timestamp + tapThreshold - now >= 0)
          {
            // Here you get the Tap event
            sendEvent(e.target, tapNum === 2 && target === e.target ? 'dbltap' : 'tap', e)
            target= e.target
          }
        }

        // reset the tap counter
        dblTapTimer = setTimeout(function() {
          tapNum = 0
        }, dbltapThreshold)

      }
    },
    onTouchMove = function(e) {
      if (!isValid(e)) return
      var pointer = getPointerEvent(e)
      currX = pointer.pageX
      currY = pointer.pageY
    },
    swipeThreshold = win.SWIPE_THRESHOLD || 100,
    tapThreshold = win.TAP_THRESHOLD || 150, // range of time where a tap event could be detected
    dbltapThreshold = win.DBL_TAP_THRESHOLD || 200, // delay needed to detect a double tap
    longtapThreshold = win.LONG_TAP_THRESHOLD || 1000, // delay needed to detect a long tap
    tapPrecision = win.TAP_PRECISION / 2 || 60 / 2, // touch events boundaries ( 60px by default )
    justTouchEvents = win.JUST_ON_TOUCH_DEVICES,
    tapNum = 0,
    currX, currY, cachedX, cachedY, timestamp, target, dblTapTimer, longtapTimer

  //setting the events listeners
  setListener(doc, touchevents.touchstart + (justTouchEvents ? '' : ' mousedown'), onTouchStart)
  setListener(doc, touchevents.touchend + (justTouchEvents ? '' : ' mouseup'), onTouchEnd)
  setListener(doc, touchevents.touchmove + (justTouchEvents ? '' : ' mousemove'), onTouchMove)
}(document, window));


text:
package mods.alice.championglove.item;

public final class ItemImpersonater
{
}


text:
var crawlPage = require('../biz').crawlPage;
var model = require('../model');
var co = require('co');
var cheerio = require('cheerio');
var _ = require('underscore');
var _s = require('underscore.string');
var resolve = require('url').resolve;
var getRootURL = require('../../modules/other/pathUtils').getRootURL;

/*
 热门商圈
 * */
module.exports = Houses;
function Houses(url) {
    this.url = url;
    this.rootURL = getRootURL(this.url);
}

/*
 crawl houses list
 * */
Houses.prototype.getHouses = function () {
    var boundParse = parse.bind(this);
    return crawlPage(this.url, boundParse);
};

function parse(fn) {
    var url = this.rootURL;
    return function (err, res, html) {
        var $ = cheerio.load(html, {
            normalizeWhitespace: true,
            xmlMode: true
        });
        var locations = $('meta[name="location"]').attr('content');
        if (locations) {
            var province = locations.match('province=([^;]+)')[1];
            var city = locations.match('city=([^;]+)')[1];
        }
        var listPage = new model.listPage({url: url, houses: [], pages: []});
        $('div.fanye a').each(function(idx, ele){
            if(idx > 0) {
                var pageHref = $(ele).attr('href');
                if (pageHref) {
                    var pageUrl = resolve(url, pageHref);
                    if(pageUrl && !_.contains(listPage.pages, pageUrl)) {
                        listPage.pages.push(pageUrl);
                    }
                }
            }
        });
        $('div.houseList dl.list').each(function () {
            var $elements = $(this).children();

            if($elements[1]) {
                var $href = $($elements[1]).find('p.title a');
                if ($href) {
                    var href = $href.attr('href');
                    if(!_.contains(listPage.houses, href)) {
                        var house = new model.House({province: province, city: city});
                        if (!_s.startsWith(href, 'http'))
                            href = resolve(url, href);
                        house.href = href;
                        listPage.houses.push(house);
                    }
                }
            }
        });
        fn(err, listPage);
    }
}

//co(function*() {
//    var h = new Houses('http://zu.fang.com/house/list/');
//    var houses = yield h.getHouses();
//    console.log(houses);
//});


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

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>punchcards: example-date-circle-n3-custom</title>

    <link rel="stylesheet" type="text/css" href="punchcards.min.css">

View source.


text:
using System;
using System.Security.Cryptography;

namespace SafeChat
{
    public class EncryptorRSA : Encryptor
    {
        private RSACryptoServiceProvider rsa;
        private int KEY_SIZE = 2048;

        public void GenerateRSAKeyPair()
        {
            RSACryptoServiceProvider.UseMachineKeyStore = false;
            rsa = new RSACryptoServiceProvider(KEY_SIZE);
            rsa.PersistKeyInCsp = false;
        }

        public string GetRSAPublicKey()
        {
            return rsa.ToXmlString(false);
        }

        public EncryptorRSA(AsymmetricAlgorithm privateKey)
        {
            if (privateKey == null)
                throw new ArgumentNullException("privateKey");

            GenerateRSAKeyPair();
            string ckey = privateKey.ToXmlString(true);
            rsa.FromXmlString(privateKey.ToXmlString(true));
        }

        public EncryptorRSA()
        {
            GenerateRSAKeyPair();
        }

        public EncryptorRSA(string publicKeyXml)
        {
            if (publicKeyXml == null)
                throw new ArgumentNullException("publicKeyXml");

            GenerateRSAKeyPair();
            rsa.FromXmlString(publicKeyXml);
        }

        public override byte[] Encrypt(byte[] bytes)
        {
            return rsa.Encrypt(bytes, false);
        }

        public override byte[] Decrypt(byte[] bytes)
        {
            return rsa.Decrypt(bytes, false);
        }
    }
}