text:
package com.tito.sampleapp.enigma;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import com.tito.easyyarn.appmaster.ApplicationMaster;
import com.tito.easyyarn.phase.FixedTasksPhaseManager;
import com.tito.easyyarn.phase.Phase;
import com.tito.easyyarn.task.Task;
import com.tito.easyyarn.task.TaskContext;

public class EnigmaAppMaster extends ApplicationMaster {
	private static final Log LOG = LogFactory.getLog(EnigmaAppMaster.class);

	private int enigmaCount;
	private String plainTextPath;
	private String cipherTextPath;
	private String enigmaTempDir;
	private String keyPath;
	private boolean isEncrypt;
	private boolean skipKeyGeneration;

	private List<String> machineIdList = new ArrayList<>();

	@Override
	public boolean init(CommandLine commandLine) {
		if (!commandLine.hasOption("operation")) {
			LOG.error("Missing operation <E|D>");
			return false;
		}
		String operation = commandLine.getOptionValue("operation");
		if (!operation.equalsIgnoreCase("e") && !operation.equalsIgnoreCase("d")) {
			LOG.error("Invalid operation, please specify E or D");
			return false;
		}
		if (operation.toLowerCase().startsWith("e")) {
			isEncrypt = true;
		}

		if (isEncrypt) {
			if (!commandLine.hasOption("enigmaCount")) {
				LOG.error("Missing enigmaCount");
				return false;
			} else {
				enigmaCount = Integer.parseInt(commandLine.getOptionValue("enigmaCount"));
			}

		}

		if (!commandLine.hasOption("plainTextPath")) {
			LOG.error("Missing plainTextPath");
			return false;
		} else {
			plainTextPath = commandLine.getOptionValue("plainTextPath");
		}

		if (!commandLine.hasOption("cipherTextPath")) {
			LOG.error("Missing cipherTextPath");
			return false;
		} else {
			cipherTextPath = commandLine.getOptionValue("cipherTextPath");
		}
		if (!commandLine.hasOption("enigmaTempDir")) {
			LOG.error("Missing enigmaTempDir");
			return false;
		} else {
			enigmaTempDir = commandLine.getOptionValue("enigmaTempDir");
		}

		if (!commandLine.hasOption("keyPath")) {
			LOG.error("Missing keyPath");
			return false;
		} else {
			keyPath = commandLine.getOptionValue("keyPath");
		}
		if (commandLine.hasOption("usingKey") && commandLine.getOptionValue("usingKey").equalsIgnoreCase("true")) {
			skipKeyGeneration = true;
		}
		return true;
	}

	@Override
	public void setupOptions(Options opts) {
		opts.addOption("operation", true, "E|D for Encrypt or Decrypt");
		opts.addOption("plainTextPath", true, "File to encrypt");
		opts.addOption("cipherTextPath", true, "Path to write encrypted file to");
		opts.addOption("keyPath", true, "Path to EnigmaKey.key file");
		opts.addOption("usingKey", true,
				"true|false :Force Engima to encrypt using the provided key , instead of generating new key");
		opts.addOption("enigmaTempDir", true, "Directory to write internal machine streams and generated Key");
		opts.addOption("enigmaCount", true, "Number of Engima Machines to encrypt with");

	}

	@Override
	protected void registerPhases() {
		if (isEncrypt) {
			registerEncryptPhases();
		} else {
			registerDecryptPhase();
		}

	}

	private long getInputLength(String filePath) {

		try {
			Configuration conf = getConf();

			FileSystem fs = FileSystem.get(conf);
			Path input = new Path(filePath);
			if (!fs.exists(input)) {
				LOG.error("File doesn't exist:" + filePath);
				throw new RuntimeException("File doesn't exist:" + filePath);
			}
			FileStatus fileStatus = fs.getFileStatus(input);
			return fileStatus.getLen();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		}
	}

	private Phase createKeyGeneratorPhase(int machineCount, String keyPath) {

		List<Task> taskList = new ArrayList<>();
		for (int i = 0; i < machineCount; i++) {
			String machineId = "machine_" + i;
			machineIdList.add(machineId);
			TaskContext taskContext = new TaskContext(EnigmaKeyGeneratorTasklet.class);
			taskContext.addArg("enigmaTempDir", enigmaTempDir);
			taskContext.addArg("machineId", machineId);
			Task genTask = new Task("gen_" + i, taskContext);
			taskList.add(genTask);
		}
		FixedTasksPhaseManager phaseManager = new FixedTasksPhaseManager(this, taskList,
				new KeyGeneratorPhaseListener(this, keyPath));
		Phase keyGeneratorPhase = new Phase("Generate Phase", phaseManager);
		return keyGeneratorPhase;
	}

	private Phase createStreamGeneratorPhase(String keyPath, String tmpDir, long length) {

		StreamPhaseManager phaseManager = new StreamPhaseManager(this, keyPath, tmpDir, length, null);
		Phase streamPhase = new Phase("Stream Phase", phaseManager);
		return streamPhase;

	}

	private Phase createCombinerPhase(String keyPath, String inputPath, String outputPath, String tmpDir,
			boolean reversed) {
		List<Task> combineTasks = new ArrayList<>();
		TaskContext combineTaskContext = new TaskContext(EnigmaCombinerTasklet.class);
		combineTaskContext.addArg("keyPath", keyPath);
		combineTaskContext.addArg("enigmaTempDir", tmpDir);
		combineTaskContext.addArg("inputPath", inputPath);
		combineTaskContext.addArg("outputPath", outputPath);
		combineTaskContext.addArg("reversed", String.valueOf(reversed));
		Task combineTask = new Task("CombineTask", combineTaskContext);
		combineTasks.add(combineTask);
		FixedTasksPhaseManager combinePhaseManager = new FixedTasksPhaseManager(this, combineTasks, null);
		Phase combinePhase = new Phase("Combine", combinePhaseManager);
		return combinePhase;

	}

	private void registerEncryptPhases() {
		LOG.info("Registering Encryption Phases");
		if (!skipKeyGeneration) {
			LOG.info("Registering generate new key phase");
			Phase keyGenPhase = createKeyGeneratorPhase(enigmaCount, keyPath);
			if (keyGenPhase == null) {
				LOG.error("Failed to create Key Generator phase");
				throw new RuntimeException("Failed to create Key Generator phase");
			}
			registerPhase(keyGenPhase);
		}

		long length = getInputLength(plainTextPath);
		if (length == -1) {
			LOG.error("Failed to determine input length");
			throw new RuntimeException("Failed to determine input length");
		}
		Phase streamPhase = createStreamGeneratorPhase(keyPath, enigmaTempDir, length);
		if (streamPhase == null) {
			LOG.error("Failed to create Stream phase");
			throw new RuntimeException("Failed to create Stream phase");
		}
		registerPhase(streamPhase);

		Phase combinePhase = createCombinerPhase(keyPath, plainTextPath, cipherTextPath, enigmaTempDir, false);
		if (combinePhase == null) {
			LOG.error("Failed to create Combine phase");
			throw new RuntimeException("Failed to create Combine phase");
		}
		registerPhase(combinePhase);

	}

	private void registerDecryptPhase() {
		LOG.info("Registering Decryption Phases");

		long length = getInputLength(cipherTextPath);
		if (length == -1) {
			LOG.error("Failed to determine input length");
			throw new RuntimeException("Failed to determine input length");
		}
		Phase streamPhase = createStreamGeneratorPhase(keyPath, enigmaTempDir, length);
		if (streamPhase == null) {
			LOG.error("Failed to create Stream phase");
			throw new RuntimeException("Failed to create Stream phase");
		}
		registerPhase(streamPhase);

		Phase combinePhase = createCombinerPhase(keyPath, cipherTextPath, plainTextPath, enigmaTempDir, true);
		if (combinePhase == null) {
			LOG.error("Failed to create Combine phase");
			throw new RuntimeException("Failed to create Combine phase");
		}
		registerPhase(combinePhase);

	}

	public int getEnigmaCount() {
		return enigmaCount;
	}

	public void setEnigmaCount(int enigmaCount) {
		this.enigmaCount = enigmaCount;
	}

	public String getEnigmaTempDir() {
		return enigmaTempDir;
	}

	public void setEnigmaTempDir(String enigmaTempDir) {
		this.enigmaTempDir = enigmaTempDir;
	}

	public String getPlainTextPath() {
		return plainTextPath;
	}

	public void setPlainTextPath(String plainTextPath) {
		this.plainTextPath = plainTextPath;
	}

	public String getCipherTextPath() {
		return cipherTextPath;
	}

	public void setCipherTextPath(String cipherTextPath) {
		this.cipherTextPath = cipherTextPath;
	}

	public List<String> getMachineIdList() {
		return machineIdList;
	}

	public void setMachineIdList(List<String> machineIdList) {
		this.machineIdList = machineIdList;
	}

}


text:
package io.quarkus.hibernate.orm.rest.data.panache.deployment.entity;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.is;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.hibernate.orm.rest.data.panache.deployment.AbstractGetMethodTest;
import io.quarkus.test.QuarkusUnitTest;

class PanacheEntityResourceGetMethodTest extends AbstractGetMethodTest {

    @RegisterExtension
    static final QuarkusUnitTest TEST = new QuarkusUnitTest()
            .withApplicationRoot((jar) -> jar
                    .addClasses(Collection.class, CollectionsResource.class, AbstractEntity.class, AbstractItem.class,
                            Item.class, ItemsResource.class,
                            EmptyListItem.class, EmptyListItemsResource.class)
                    .addAsResource("application.properties")
                    .addAsResource("import.sql"));

    @Test
    void shouldCopyAdditionalMethodsAsResources() {
        given().accept("application/json")
                .when().get("/collections/name/full collection")
                .then().statusCode(200)
                .and().body("id", is("full"))
                .and().body("name", is("full collection"));
    }

}

redpajama_set_name: RedPajamaGithub


text:
Description
-----------
This transform plugin can detect and transcribe text from small(up to 5 pages) PDF and TIFF files stored in Cloud
Storage in an online manner.

Credentials
-----------
If the plugin is run on a Google Cloud Dataproc cluster, the service account key does not need to be
provided and can be set to 'auto-detect'.
Credentials will be automatically read from the cluster environment.

If the plugin is not run on a Dataproc cluster, the path to a service account key must be provided.
The service account key can be found on the Dashboard in the Cloud Platform Console.
Make sure the account key has permission to access Google Cloud Vision.
The service account key file needs to be available on every node in your cluster and
must be readable by all users running the job.

Properties
----------

**Service Account File Path**: Path on the local file system of the service account key used for
authorization. Can be set to 'auto-detect' when running on a Dataproc cluster.
When running on other clusters, the file must be present on every node in the cluster.

**Project ID**: Google Cloud Project ID, which uniquely identifies a project. It can be found on the Dashboard in the
Google Cloud Platform Console.

**Path Field**: Field in the input schema containing the path to the image.

**Output Field**: Field to store the extracted image features. If the specified output field name already exists in the
input record, it will be overwritten.

**Content Field**: Field in the input schema containing the file content, represented as a stream of bytes.

**Mime Type**: The type of the file. Currently only 'application/pdf', 'image/tiff' and 'image/gif' are supported.
Wildcards are not supported.

**Pages**: The pages in the file to perform image annotation.

**Features**: Features to extract from images.

**Language Hints**: Hints to detect the language of the text in the images.

**Aspect Ratios**: Ratio of the width to the height of the image. If not specified, the best possible crop is returned.

**Include Geo Results**: Whether to include results derived from the geo information in the image.


text:
package spatwork.domain;

/**
 * Possible game results.
 */
public enum GameResult {
    TEAM_A_WON, TEAM_B_WON, DRAW
}


text:
<?php
namespace Application\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Sql\Sql;
//use Zend\Db\Sql\Select;
//use Zend\Db\ResultSet\ResultSet;
use Zend\Db\ResultSet\ResultSet;

class PruebaModel extends TableGateway
{
    private $dbAdapter;

    public function __construct(Adapter $adapter = null, $databaseSchema = null, ResultSet $selectResultPrototype = null){

        $this->dbAdapter=$adapter;

        return parent::__construct('usuarios', $this->dbAdapter, $databaseSchema,$selectResultPrototype);
    }

     public function getUsuarios(){

        $select=$this->select();
        $datos=$select->toArray();
        return $datos;
    }

    public function getUnUsuario(){

        $sql = new Sql($this->dbAdapter);

        $select = $sql->select();

        $select->columns(array('nombre','apellido','direccion','telefono'))

               ->from('usuarios');

        $selectString = $sql->getSqlStringForSqlObject($select);

        $execute = $this->dbAdapter->query($selectString, Adapter::QUERY_MODE_EXECUTE);

        $result=$execute->toArray();

        return $result[0];

        }

        public function addUsuario($nombre,$apellido,$direccion,$telefono){

        $consulta=$this->dbAdapter->query("SELECT count(idusuarios) as count FROM usuarios",Adapter::QUERY_MODE_EXECUTE);
        $datos=$consulta->toArray();
        if($datos[0]["count"]!=0){

         $insert=$this->insert(array(
                            "nombre"    => $nombre,
                            "apellido" => $apellido,
                            "direccion" => $direccion,
                            "telefono" => $telefono,
                            "estado"   => 1
                       ));

        }else{

            $insert=false;

        }

         return $insert;

     }

}


text:
#import <SalesforceRestAPI/SFRestAPI+Blocks.h>
#import <SalesforceRestAPI/SFRestAPI+Files.h>
#import <SalesforceRestAPI/SFRestAPI+QueryBuilder.h>
#import <SalesforceRestAPI/SFRestAPI.h>
#import <SalesforceRestAPI/SFRestAPISalesforceAction.h>
#import <SalesforceRestAPI/SFRestRequest.h>


text:
<?php

namespace CEOFESABundle\Entity;

use CEOFESABundle\Validator\Constraints as CeofesaAssert;
use Doctrine\ORM\Mapping as ORM;

/**
 * Presence
 *
 * @ORM\Table(name="tb_Presence", uniqueConstraints={@ORM\UniqueConstraint(name="unq_presence", columns={"psc_Session", "psc_Parcours"})})
 * @ORM\Entity(repositoryClass="CEOFESABundle\Repository\PresenceRepository")
 *
 * @CeofesaAssert\Presence
 */
class Presence
{
    /**
     * @var integer
     *
     * @ORM\Column(name="psc_ID", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $pscId;

    /**
     * @var \Session
     *
     * @ORM\ManyToOne(
     *     targetEntity = "Session",
     *     inversedBy = "presences"
     * )
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="psc_Session", referencedColumnName="ses_ID", nullable=false)
     * })
     */
    private $pscSession;

    /**
     * @var \Parcours
     *
     * @ORM\ManyToOne(targetEntity="Parcours", inversedBy="prcPresence")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="psc_Parcours", referencedColumnName="prc_ID", nullable=false)
     * })
     */
    private $pscParcours;

    /**
     * @var string
     *
     * @ORM\Column(name="psc_Duree", type="decimal", precision=5, scale=2, nullable=false)
     */
    private $pscDuree;

    /**
     * @var boolean
     *
     * @ORM\Column(name="psc_Facture", type="boolean", nullable=false, options={"default" = 0})
     */
    private $pscFacture;

    /**
     * @var boolean
     *
     * @ORM\Column(name="psc_Validate", type="boolean", nullable=false, options={"default" = 0})
     */
    private $pscValidate;

    /**
     * Presence constructor.
     */
    public function __construct()
    {
        $this->pscValidate = false;
    }

    /**
     * Get pscId
     *
     * @return integer
     */
    public function getPscId()
    {
        return $this->pscId;
    }

    /**
     * Set pscDuree
     *
     * @param string $pscDuree
     * @return Presence
     */
    public function setPscDuree($pscDuree)
    {
        $this->pscDuree = $pscDuree;

        return $this;
    }

    /**
     * Get pscDuree
     *
     * @return float
     */
    public function getPscDuree()
    {
        return $this->pscDuree;
    }

    /**
     * Set pscFacture
     *
     * @param boolean $pscFacture
     * @return Presence
     */
    public function setPscFacture($pscFacture)
    {
        $this->pscFacture = $pscFacture;

        return $this;
    }

    /**
     * Get pscFacture
     *
     * @return boolean
     */
    public function getPscFacture()
    {
        return $this->pscFacture;
    }

    /**
     * Set pscParcours
     *
     * @param \CEOFESABundle\Entity\Parcours $pscParcours
     * @return Presence
     */
    public function setPscParcours(\CEOFESABundle\Entity\Parcours $pscParcours = null)
    {
        $this->pscParcours = $pscParcours;

        return $this;
    }

    /**
     * Get pscParcours
     *
     * @return \CEOFESABundle\Entity\Parcours
     */
    public function getPscParcours()
    {
        return $this->pscParcours;
    }

    /**
     * Set pscSession
     *
     * @param \CEOFESABundle\Entity\Session $pscSession
     * @return Presence
     */
    public function setPscSession(\CEOFESABundle\Entity\Session $pscSession = null)
    {
        $this->pscSession = $pscSession;

        return $this;
    }

    /**
     * Get pscSession
     *
     * @return \CEOFESABundle\Entity\Session
     */
    public function getPscSession()
    {
        return $this->pscSession;
    }

    /**
     * @return boolean
     */
    public function isPscValidate()
    {
        return $this->pscValidate;
    }

    /**
     * @param boolean $sesValidate
     */
    public function setPscValidate($pscValidate)
    {
        $this->pscValidate = $pscValidate;
    }
}


text:
package com.banane.dbtest2.common;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.database.Cursor;
import android.util.Log;

import com.banane.dbtest2.common.DatabaseHelper;
import com.banane.dbtest2.common.Utils;
import com.banane.dbtest2.model.Word;

/**
 * Created by banane on 6/3/15.
 */
public class CursorLoader extends AsyncTaskLoader<Cursor> {

    private Context context;
    private DatabaseHelper dbHelper;

    public CursorLoader(Context context, DatabaseHelper dbHelper) {
        super(context);
        this.context = context;
        this.dbHelper = dbHelper;
    }

    @Override
    protected void onStartLoading() {
        Log.e(Utils.TAG,getClass().getSimpleName() + "onStartLoading");

        super.onStartLoading();
    }

    @Override
    public Cursor loadInBackground() {
        Log.e(Utils.TAG,getClass().getSimpleName() + ":::: loadInBackground");

        //Cursor c = dbHelper.getAllWords();
        Cursor c = context.getContentResolver().query(Word.CONTENT_URI, dbHelper.ALL_COLUMN_NAMES, null, null, dbHelper.KEY_LOCAL_WORD + " asc ", null);
        return c;
    }

    @Override
    public void deliverResult(Cursor data) {
        Log.e(Utils.TAG,getClass().getSimpleName() + ":::: deliverResult");

        super.deliverResult(data);
    }

    @Override
    protected void onStopLoading() {
        Log.e(Utils.TAG,getClass().getSimpleName() + ":::: onStopLoading");

        super.onStopLoading();
    }
}


text:
'use strict';

var createOrder = function (params) {
    var payloadType = this.protocol.getPayloadTypeByName('ProtoOACreateOrderReq');
    return this.sendGuaranteedCommand(payloadType, {
        accountId: params.accountId,
        accessToken: params.accessToken,
        symbolName: params.symbolName,
        orderType: params.orderType,
        tradeSide: params.tradeSide,
        volume: params.volume,
        clientOrderId: params.clientOrderId,
        comment: params.comment
    });
};

module.exports = createOrder;


text:
package pl.touk.nussknacker.engine.management.periodic.db

import com.typesafe.config.Config
import com.typesafe.scalalogging.LazyLogging
import net.ceedubs.ficus.readers.ValueReader
import org.flywaydb.core.Flyway
import org.flywaydb.core.api.configuration.FluentConfiguration
import org.flywaydb.core.internal.jdbc.DriverDataSource.DriverType
import slick.jdbc.{HsqldbProfile, JdbcBackend, JdbcProfile, PostgresProfile}

object DbInitializer extends LazyLogging {

  def init(configDb: Config): (JdbcBackend.DatabaseDef, JdbcProfile) = {
    import net.ceedubs.ficus.Ficus._
    val url =  configDb.as[String]("url")
    val profile = chooseDbProfile(url)
    logger.info("Applying db migrations")

    //we want to set property on FluentConfiguration only if there is property in config
    implicit class OptionalConfig(config: FluentConfiguration) {
      def setOptional[A](name: String, setAction: (FluentConfiguration, A) => FluentConfiguration)
                        (implicit reader: ValueReader[Option[A]]): FluentConfiguration = {
        configDb.getAs[A](name).fold(config)(setAction(config, _))
      }
    }

    Flyway
      .configure()
      .locations(
        ( profile match {
          case HsqldbProfile => Array("db/batch_periodic/migration/hsql", "db/batch_periodic/migration/common")
          case PostgresProfile => Array("db/batch_periodic/migration/postgres", "db/batch_periodic/migration/common")
          case _ => throw new IllegalArgumentException(s"Unsuported database url: $url . Use either PostgreSQL or HSQLDB.")
        }): _*
      )
      .dataSource(url, configDb.as[String]("user"), configDb.as[String]("password"))
      .setOptional[String]("schema", _.schemas(_))
      .setOptional[String]("table", _.table(_))
      .baselineOnMigrate(true)
      .load().migrate()

    (JdbcBackend.Database.forConfig(path = "", configDb), profile)
  }

  private def chooseDbProfile(dbUrl: String): JdbcProfile = {
    dbUrl match {
      case url if DriverType.POSTGRESQL.matches(url) => PostgresProfile
      case _ => HsqldbProfile
    }
  }

}


text:
/**
 * @file MessageTable.c
 * @author biko
 * @date 2016-07-30
 *
 * MessageTable module implementation.
 */

/** Headers *************************************************************/
#include <ntifs.h>
#include <ntstrsafe.h>
#include <ntintsafe.h>

#include <Common.h>

#include "Util.h"

#include "MessageTable.h"

/** Typedefs ************************************************************/

/**
 * Contains the state of the message table.
 */
typedef struct _MESSAGE_TABLE
{
	ERESOURCE		tLock;
	BOOLEAN			bLockInitialized;

	_Guarded_by_(tLock)
	RTL_AVL_TABLE	tTable;
	BOOLEAN			bTableInitialized;
} MESSAGE_TABLE, *PMESSAGE_TABLE;
typedef CONST MESSAGE_TABLE *PCMESSAGE_TABLE;

/**
 * Contains the error message or message box display text
 * for a message table resource.
 */
typedef struct _MESSAGE_RESOURCE_ENTRY
{
	USHORT	cbLength;
	USHORT	fFlags;
	UCHAR	acText[ANYSIZE_ARRAY];
} MESSAGE_RESOURCE_ENTRY, *PMESSAGE_RESOURCE_ENTRY;
typedef CONST MESSAGE_RESOURCE_ENTRY *PCMESSAGE_RESOURCE_ENTRY;
C_ASSERT(0 == UFIELD_OFFSET(MESSAGE_RESOURCE_ENTRY, acText) % __alignof(WCHAR));

/**
 * Contains information about message strings with identifiers
 * in the range indicated by the nLowId and nHighId members.
 */
typedef struct _MESSAGE_RESOURCE_BLOCK
{
	ULONG	nLowId;
	ULONG	nHighId;
	ULONG	cbOffsetToEntries;
} MESSAGE_RESOURCE_BLOCK, *PMESSAGE_RESOURCE_BLOCK;
typedef CONST MESSAGE_RESOURCE_BLOCK *PCMESSAGE_RESOURCE_BLOCK;

/**
 * Contains information about formatted text for display as an
 * error message or in a message box in a message table resource.
 */
typedef struct _MESSAGE_RESOURCE_DATA
{
	ULONG					nBlocks;
	MESSAGE_RESOURCE_BLOCK	atBlocks[ANYSIZE_ARRAY];
} MESSAGE_RESOURCE_DATA, *PMESSAGE_RESOURCE_DATA;
typedef CONST MESSAGE_RESOURCE_DATA *PCMESSAGE_RESOURCE_DATA;
C_ASSERT(__alignof(MESSAGE_RESOURCE_DATA) >= __alignof(MESSAGE_RESOURCE_ENTRY));

/**
 * Context for the counting callback.
 *
 * @see messagetable_CountingCallback.
 */
typedef struct _COUNTING_CALLBACK_CONTEXT
{
	// Total blocks required to serialize the table.
	ULONG	nBlocks;

	// Total bytes required to serialize the strings in the table.
	SIZE_T	cbTotalStrings;
} COUNTING_CALLBACK_CONTEXT, *PCOUNTING_CALLBACK_CONTEXT;
typedef CONST COUNTING_CALLBACK_CONTEXT *PCCOUNTING_CALLBACK_CONTEXT;

/**
 * Context for the serializing callback.
 *
 * @see messagetable_SerializingCallback.
 */
typedef struct _SERIALIZING_CALLBACK_CONTEXT
{
	PMESSAGE_RESOURCE_DATA	ptMessageData;

	ULONG					nCurrentBlock;

	PUCHAR					pcCurrentStringPosition;
} SERIALIZING_CALLBACK_CONTEXT, *PSERIALIZING_CALLBACK_CONTEXT;
typedef CONST SERIALIZING_CALLBACK_CONTEXT *PCSERIALIZING_CALLBACK_CONTEXT;

/** Constants ***********************************************************/

/**
 * Pool tag for allocations made by this module.
 */
#define MESSAGE_TABLE_POOL_TAG (RtlUlongByteSwap('MsgT'))

/**
 * Maximum size, in bytes, of a MESSAGE_RESOURCE_ENTRY,
 * including the string data.
 *
 * @remark	This definition assumes that the size field in
 *			the MESSAGE_RESOURCE_ENTRY structure is a USHORT
 *			or larger.
 */
#define MESSAGE_RESOURCE_ENTRY_MAX_SIZE \
	(ALIGN_DOWN_BY(MAXUSHORT, __alignof(MESSAGE_RESOURCE_ENTRY)))

/**
 * Maximum size, in bytes, of a string that
 * can be stored in a message table. The size is
 * constrained by the ability to serialize the string
 * into a MESSAGE_RESOURCE_ENTRY.
 *
 * @see MESSAGE_RESOURCE_ENTRY.
 */
#define MESSAGE_TABLE_STRING_MAX_SIZE \
	(MESSAGE_RESOURCE_ENTRY_MAX_SIZE - UFIELD_OFFSET(MESSAGE_RESOURCE_ENTRY, acText))
C_ASSERT(MESSAGE_TABLE_STRING_MAX_SIZE > 0);

/** Functions ***********************************************************/

/**
 * Comparison routine for the AVL tree.
 *
 * @param[in]	ptTable			The tree structure.
 * @param[in]	pvFirstStruct	First structure to compare.
 * @param[in]	pvSecondStruct	Second structure to compare.
 *
 * @returns RTL_GENERIC_COMPARE_RESULTS
 */
_IRQL_requires_max_(APC_LEVEL)
STATIC
PAGEABLE
RTL_GENERIC_COMPARE_RESULTS
messagetable_CompareRoutine(
	_In_	PRTL_AVL_TABLE	ptTable,
	_In_	PVOID			pvFirstStruct,
	_In_	PVOID			pvSecondStruct
)
{
	RTL_GENERIC_COMPARE_RESULTS	eResult			= GenericLessThan;
	PCMESSAGE_TABLE_ENTRY		ptFirstEntry	= (PCMESSAGE_TABLE_ENTRY)pvFirstStruct;
	PCMESSAGE_TABLE_ENTRY		ptSecondEntry	= (PCMESSAGE_TABLE_ENTRY)pvSecondStruct;

	PAGED_CODE();

#ifndef DBG
	UNREFERENCED_PARAMETER(ptTable);
#endif // !DBG

	ASSERT(NULL != ptTable);
	ASSERT(NULL != pvFirstStruct);
	ASSERT(NULL != pvSecondStruct);

	if (ptFirstEntry->nEntryId < ptSecondEntry->nEntryId)
	{
		eResult = GenericLessThan;
	}
	else if (ptFirstEntry->nEntryId > ptSecondEntry->nEntryId)
	{
		eResult = GenericGreaterThan;
	}
	else
	{
		eResult = GenericEqual;
	}

	return eResult;
}

/**
 * Memory allocation routine for the AVL tree.
 *
 * @param[in]	ptTable	The tree structure.
 * @param[in]	cbSize	Size to allocate.
 *
 * @returns PVOID
 */
_IRQL_requires_max_(APC_LEVEL)
STATIC
PAGEABLE
PVOID
messagetable_AllocateRoutine(
	_In_	PRTL_AVL_TABLE	ptTable,
	_In_	CLONG			cbSize
)
{
	PAGED_CODE();

#ifndef DBG
	UNREFERENCED_PARAMETER(ptTable);
#endif // !DBG

	ASSERT(NULL != ptTable);
	ASSERT(0 != cbSize);

	return ExAllocatePoolWithTag(PagedPool,
								 cbSize,
								 MESSAGE_TABLE_POOL_TAG);
}

/**
 * Memory deallocation routine for the AVL tree.
 *
 * @param[in]	ptTable		The tree structure.
 * @param[in]	pvBuffer	The buffer to free.
 */
_IRQL_requires_max_(APC_LEVEL)
STATIC
PAGEABLE
VOID
messagetable_FreeRoutine(
	_In_	PRTL_AVL_TABLE	ptTable,
	_In_	PVOID			pvBuffer
)
{
	PAGED_CODE();

#ifndef DBG
	UNREFERENCED_PARAMETER(ptTable);
#endif // !DBG

	ASSERT(NULL != ptTable);
	ASSERT(NULL != pvBuffer);

	CLOSE(pvBuffer, ExFreePool);
}

/**
 * Clears a message table entry.
 *
 * @param[in]	ptEntry	Entry to clear.
 *
 * @remark	This does not actually free the entry
 *			itself, only the pointers within.
 */
_IRQL_requires_max_(APC_LEVEL)
STATIC
PAGEABLE
VOID
messagetable_ClearEntry(
	_In_	PMESSAGE_TABLE_ENTRY	ptEntry
)
{
	PAGED_CODE();

	if (NULL == ptEntry)
	{
		goto lblCleanup;
	}

	if (ptEntry->bUnicode)
	{
		CLOSE(ptEntry->tData.tUnicode.Buffer, ExFreePool);
	}
	else
	{
		CLOSE(ptEntry->tData.tAnsi.Buffer, ExFreePool);
	}

	//
	// NOTE: DO NOT ZERO THE STRUCTURE!
	// This function is called before element removal,
	// and so the rest of the structure's members
	// are used by the comparison routine
	// to find the entry to remove.
	//

lblCleanup:
	return;
}

/**
 * Determines whether an ANSI_STRING structure
 * is valid for use in a message table.
 *
 * @param[in]	psString	String to check.
 * @param[in]	bCompact	Indicates whether the string
 *							will be compacted on insertion
 *							into the table.
 *
 * @returns BOOLEAN
 */
STATIC
BOOLEAN
messagetable_IsValidAnsiString(
	_In_opt_	PCANSI_STRING	psString,
	_In_		BOOLEAN			bCompact
)
{
	BOOLEAN	bIsValid	= FALSE;

	if (NULL == psString)
	{
		goto lblCleanup;
	}

	if (NULL == psString->Buffer)
	{
		goto lblCleanup;
	}

	if ((0 == psString->Length) ||
		(0 == psString->MaximumLength))
	{
		goto lblCleanup;
	}

	if (psString->MaximumLength < psString->Length)
	{
		goto lblCleanup;
	}

	if (bCompact)
	{
		C_ASSERT(MESSAGE_TABLE_STRING_MAX_SIZE - sizeof(ANSI_NULL) > 0);

		if (psString->Length > MESSAGE_TABLE_STRING_MAX_SIZE - sizeof(ANSI_NULL))
		{
			goto lblCleanup;
		}
	}
	else
	{
		if (psString->MaximumLength > MESSAGE_TABLE_STRING_MAX_SIZE)
		{
			goto lblCleanup;
		}
	}

	bIsValid = TRUE;

lblCleanup:
	return bIsValid;
}

/**
 * Determines whether a UNICODE_STRING structure
 * is valid for use in a message table.
 *
 * @param[in]	pusString	String to check.
 * @param[in]	bCompact	Indicates whether the string
 *							will be compacted on insertion
 *							into the table.
 *
 * @returns BOOLEAN
 */
STATIC
BOOLEAN
messagetable_IsValidUnicodeString(
	_In_opt_	PCUNICODE_STRING	pusString,
	_In_		BOOLEAN				bCompact
)
{
	BOOLEAN	bIsValid	= FALSE;

	if (NULL == pusString)
	{
		goto lblCleanup;
	}

	if (NULL == pusString->Buffer)
	{
		goto lblCleanup;
	}

	if ((0 == pusString->Length) ||
		(0 == pusString->MaximumLength))
	{
		goto lblCleanup;
	}

	if (pusString->MaximumLength < pusString->Length)
	{
		goto lblCleanup;
	}

	if ((0 != pusString->Length % 2) ||
		(0 != pusString->MaximumLength % 2))
	{
		goto lblCleanup;
	}

	if (bCompact)
	{
		C_ASSERT(MESSAGE_TABLE_STRING_MAX_SIZE - sizeof(UNICODE_NULL) > 0);

		if (pusString->Length > MESSAGE_TABLE_STRING_MAX_SIZE - sizeof(UNICODE_NULL))
		{
			goto lblCleanup;
		}
	}
	else
	{
		if (pusString->MaximumLength > MESSAGE_TABLE_STRING_MAX_SIZE)
		{
			goto lblCleanup;
		}
	}

	bIsValid = TRUE;

lblCleanup:
	return bIsValid;
}

/**
 * Inserts an ANSI message resource entry
 * into a message table.
 *
 * @param[in]	hMessageTable	Message table to insert into.
 * @param[in]	nEntryId		ID of the string to insert.
 * @param[in]	ptResourceEntry	The resource entry.
 * @param[in]	bCompact		Indicates whether the entry
 *								should be compacted.
 *
 * @returns NTSTATUS
 *
 * @remark	It is up to the caller to verify that
 *			the resource entry is indeed an ANSI
 *			resource entry.
 */
_IRQL_requires_(PASSIVE_LEVEL)
STATIC
PAGEABLE
NTSTATUS
messagetable_InsertResourceEntryAnsi(
	_In_	HMESSAGETABLE				hMessageTable,
	_In_	ULONG						nEntryId,
	_In_	PCMESSAGE_RESOURCE_ENTRY	ptResourceEntry,
	_In_	BOOLEAN						bCompact
)
{
	NTSTATUS	eStatus		= STATUS_UNSUCCESSFUL;
	SIZE_T		cbStringMax	= 0;
	ANSI_STRING	sString		= { 0 };

	PAGED_CODE();

	ASSERT(NULL != hMessageTable);
	ASSERT(NULL != ptResourceEntry);
	ASSERT(0 == ptResourceEntry->fFlags);
	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	// Calculate the string's maximum size (buffer size).
	eStatus = RtlSIZETSub(ptResourceEntry->cbLength,
						  UFIELD_OFFSET(MESSAGE_RESOURCE_ENTRY, acText),
						  &cbStringMax);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	eStatus = UTIL_InitAnsiStringCb((PCHAR)&(ptResourceEntry->acText[0]),
									cbStringMax,
									&sString);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	eStatus = MESSAGETABLE_InsertAnsi(hMessageTable,
									  nEntryId,
									  &sString,
									  bCompact);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	eStatus = STATUS_SUCCESS;

lblCleanup:
	return eStatus;
}

/**
 * Inserts a Unicode message resource entry
 * into a message table.
 *
 * @param[in]	hMessageTable	Message table to insert into.
 * @param[in]	nEntryId		ID of the string to insert.
 * @param[in]	ptResourceEntry	The resource entry.
 * @param[in]	bCompact		Indicates whether the entry
 *								should be compacted.
 *
 * @returns NTSTATUS
 *
 * @remark	It is up to the caller to verify that
 *			the resource entry is indeed a Unicode
 *			resource entry.
 */
_IRQL_requires_(PASSIVE_LEVEL)
STATIC
PAGEABLE
NTSTATUS
messagetable_InsertResourceEntryUnicode(
	_In_	HMESSAGETABLE				hMessageTable,
	_In_	ULONG						nEntryId,
	_In_	PCMESSAGE_RESOURCE_ENTRY	ptResourceEntry,
	_In_	BOOLEAN						bCompact
)
{
	NTSTATUS		eStatus		= STATUS_UNSUCCESSFUL;
	SIZE_T			cbStringMax	= 0;
	UNICODE_STRING	usString	= { 0 };

	PAGED_CODE();

	ASSERT(NULL != hMessageTable);
	ASSERT(NULL != ptResourceEntry);
	ASSERT(1 == ptResourceEntry->fFlags);
	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	// Calculate the string's maximum size (buffer size).
	eStatus = RtlSIZETSub(ptResourceEntry->cbLength,
						  UFIELD_OFFSET(MESSAGE_RESOURCE_ENTRY, acText),
						  &cbStringMax);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	eStatus = UTIL_InitUnicodeStringCb((PWCHAR)&(ptResourceEntry->acText[0]),
									   cbStringMax,
									   &usString);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	eStatus = MESSAGETABLE_InsertUnicode(hMessageTable,
										 nEntryId,
										 &usString,
										 bCompact);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	eStatus = STATUS_SUCCESS;

lblCleanup:
	return eStatus;
}

/**
 * Calculates the size of a message table entry
 * in its serialized form.
 *
 * @param[in]	ptEntry	Entry to operate on.
 *
 * @returns USHORT.
 */
_IRQL_requires_max_(APC_LEVEL)
STATIC
PAGEABLE
USHORT
messagetable_SizeofSerializedEntry(
	_In_	PCMESSAGE_TABLE_ENTRY	ptEntry
)
{
	NTSTATUS	eStatus	= STATUS_UNSUCCESSFUL;
	USHORT		cbTotal	= 0;

	PAGED_CODE();

	ASSERT(NULL != ptEntry);

	// Begin with the size of the header.
	cbTotal = UFIELD_OFFSET(MESSAGE_RESOURCE_ENTRY, acText);

	// Add the size of the string itself.
	if (ptEntry->bUnicode)
	{
		eStatus = RtlUShortAdd(cbTotal,
							   ptEntry->tData.tUnicode.MaximumLength,
							   &cbTotal);
		ASSERT(NT_SUCCESS(eStatus));
	}
	else
	{
		eStatus = RtlUShortAdd(cbTotal,
							   ptEntry->tData.tAnsi.MaximumLength,
							   &cbTotal);
		ASSERT(NT_SUCCESS(eStatus));
	}

	// Now add any required padding.
	eStatus = RtlUShortAdd(cbTotal,
						   cbTotal % __alignof(MESSAGE_RESOURCE_ENTRY),
						   &cbTotal);
	ASSERT(NT_SUCCESS(eStatus));

	return cbTotal;
}

/**
 * Callback for counting the number of blocks
 * in the serialized message table and the
 * total size required for the serialized strings.
 *
 * @param[in]	ptEntry					Entry currently being enumerated.
 *										Previous entry, or NULL if this is the first
 *										invocation of the callback.
 * @param[in]	pvContext				Alias for PCOUNTING_CALLBACK_CONTEXT.
 * @param[out]	pbContinueEnumeration	Ignored. Enumeration always continues.
 *
 * @see COUNTING_CALLBACK_CONTEXT.
 */
_IRQL_requires_max_(APC_LEVEL)
STATIC
PAGEABLE
VOID
messagetable_CountingCallback(
	_In_		PCMESSAGE_TABLE_ENTRY	ptEntry,
	_In_opt_	PCMESSAGE_TABLE_ENTRY	ptPreviousEntry,
	_In_		PVOID					pvContext,
	_Out_		PBOOLEAN				pbContinueEnumeration
)
{
	NTSTATUS					eStatus		= STATUS_UNSUCCESSFUL;
	PCOUNTING_CALLBACK_CONTEXT	ptContext	= (PCOUNTING_CALLBACK_CONTEXT)pvContext;

	PAGED_CODE();

#ifndef DBG
	UNREFERENCED_PARAMETER(pbContinueEnumeration);
#endif // !DBG

	ASSERT(NULL != ptEntry);
	ASSERT(NULL != pvContext);
	ASSERT(NULL != pbContinueEnumeration);
	ASSERT(*pbContinueEnumeration);

	if ((NULL == ptPreviousEntry) ||
		(1 != ptEntry->nEntryId - ptPreviousEntry->nEntryId))
	{
		// This is either the first time we entered the callback,
		// or the current ID begins a new block.
		eStatus = RtlULongAdd(ptContext->nBlocks,
							  1,
							  &(ptContext->nBlocks));
		ASSERT(NT_SUCCESS(eStatus));
	}

	// Add the size for the current string.
	eStatus = RtlSIZETAdd(ptContext->cbTotalStrings,
						  messagetable_SizeofSerializedEntry(ptEntry),
						  &(ptContext->cbTotalStrings));
	ASSERT(NT_SUCCESS(eStatus));
}

/**
 * Callback for serializing message table entries.
 * Writes each entry to an allocated buffer.
 *
 * @param[in]	ptEntry					Entry currently being enumerated.
 *										Previous entry, or NULL if this is the first
 *										invocation of the callback.
 * @param[in]	pvContext				Alias for PSERIALIZING_CALLBACK_CONTEXT.
 * @param[out]	pbContinueEnumeration	Ignored. Enumeration always continues.
 *
 * @see SERIALIZING_CALLBACK_CONTEXT.
 */
_IRQL_requires_max_(APC_LEVEL)
STATIC
PAGEABLE
VOID
messagetable_SerializingCallback(
	_In_		PCMESSAGE_TABLE_ENTRY	ptEntry,
	_In_opt_	PCMESSAGE_TABLE_ENTRY	ptPreviousEntry,
	_In_		PVOID					pvContext,
	_Out_		PBOOLEAN				pbContinueEnumeration
)
{
	PSERIALIZING_CALLBACK_CONTEXT	ptContext		= (PSERIALIZING_CALLBACK_CONTEXT)pvContext;
	PMESSAGE_RESOURCE_BLOCK			ptCurrentBlock	= NULL;
	PMESSAGE_RESOURCE_ENTRY			ptCurrentEntry	= NULL;

	PAGED_CODE();

#ifndef DBG
	UNREFERENCED_PARAMETER(pbContinueEnumeration);
#endif // !DBG

	ASSERT(NULL != ptEntry);
	ASSERT(NULL != pvContext);
	ASSERT(NULL != pbContinueEnumeration);
	ASSERT(*pbContinueEnumeration);

	// Obtain a pointer to the current block header
	ptCurrentBlock = &(ptContext->ptMessageData->atBlocks[ptContext->nCurrentBlock]);

	// If there is a new block, set it up
	if ((NULL == ptPreviousEntry) ||
		(1 != ptEntry->nEntryId - ptPreviousEntry->nEntryId))
	{
		//
		// New block!
		//

		// Safe to increment the counter because we already
		// ASSERTed the block count inside messagetable_CountingCallback.
		++(ptContext->nCurrentBlock);

		++ptCurrentBlock;

		ptCurrentBlock->nLowId = ptEntry->nEntryId;
		ptCurrentBlock->cbOffsetToEntries = RtlPointerToOffset(ptContext->ptMessageData,
															   ptContext->pcCurrentStringPosition);
	}

	// Update the last ID for the current block
	ptCurrentBlock->nHighId = ptEntry->nEntryId;

	// Copy
	ptCurrentEntry = (PMESSAGE_RESOURCE_ENTRY)(ptContext->pcCurrentStringPosition);
	ptCurrentEntry->cbLength = messagetable_SizeofSerializedEntry(ptEntry);
	if (ptEntry->bUnicode)
	{
		ptCurrentEntry->fFlags = 1;
		RtlMoveMemory(ptCurrentEntry->acText,
					  ptEntry->tData.tUnicode.Buffer,
					  ptEntry->tData.tUnicode.Length);
	}
	else
	{
		ptCurrentEntry->fFlags = 0;
		RtlMoveMemory(ptCurrentEntry->acText,
					  ptEntry->tData.tAnsi.Buffer,
					  ptEntry->tData.tAnsi.Length);
	}
	ptContext->pcCurrentStringPosition += ptCurrentEntry->cbLength;
}

/**
 * Acquires the message table lock.
 *
 * @param[in]	ptMessageTable	Message table to lock.
 * @param[in]	bExclusive		Indicates whether the lock
 *								is to be acquired exclusively.
 *
 * @returns NTSTATUS
 */
_IRQL_requires_max_(APC_LEVEL)
_When_(bExclusive, _Acquires_exclusive_lock_(ptMessageTable->tLock))
_When_(!bExclusive, _Acquires_shared_lock_(ptMessageTable->tLock))
_Acquires_lock_(_Global_critical_region_)
STATIC
PAGEABLE
NTSTATUS
messagetable_AcquireLock(
	_In_	PMESSAGE_TABLE	ptMessageTable,
	_In_	BOOLEAN			bExclusive
)
{
	NTSTATUS	eStatus					= STATUS_UNSUCCESSFUL;
	BOOLEAN		bResult					= FALSE;
	BOOLEAN		bLeaveCriticalRegion	= FALSE;
	BOOLEAN		bReleaseLock			= FALSE;

	PAGED_CODE();

	ASSERT(NULL != ptMessageTable);

	KeEnterCriticalRegion();
	bLeaveCriticalRegion = TRUE;

	bResult =
		(bExclusive)
		? (ExAcquireResourceExclusiveLite(&(ptMessageTable->tLock), TRUE))
		: (ExAcquireResourceSharedLite(&(ptMessageTable->tLock), TRUE));
	if (!bResult)
	{
		eStatus = STATUS_LOCK_NOT_GRANTED;
		goto lblCleanup;
	}
	bReleaseLock = TRUE;

	// All done!
	bReleaseLock = FALSE;
	bLeaveCriticalRegion = FALSE;

	eStatus = STATUS_SUCCESS;

lblCleanup:
	if (bReleaseLock)
	{
		ExReleaseResourceLite(&(ptMessageTable->tLock));
		bReleaseLock = FALSE;
	}
	if (bLeaveCriticalRegion)
	{
		KeLeaveCriticalRegion();
		bLeaveCriticalRegion = FALSE;
	}

	return eStatus;
}

/**
 * Releases the message table lock.
 *
 * @param[in]	ptMessageTable	Message table to unlock.
 */
_IRQL_requires_max_(APC_LEVEL)
_Releases_lock_(ptMessageTable->tLock)
_Releases_lock_(_Global_critical_region_)
STATIC
PAGEABLE
VOID
messagetable_ReleaseLock(
	_In_	PMESSAGE_TABLE	ptMessageTable
)
{
	PAGED_CODE();

	ASSERT(NULL != ptMessageTable);

	ExReleaseResourceLite(&(ptMessageTable->tLock));
	KeLeaveCriticalRegion();
}

_IRQL_requires_(PASSIVE_LEVEL)
PAGEABLE
NTSTATUS
MESSAGETABLE_Create(
	_Out_	PHMESSAGETABLE	phMessageTable
)
{
	NTSTATUS		eStatus			= STATUS_UNSUCCESSFUL;
	PMESSAGE_TABLE	ptMessageTable	= NULL;

	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	if (NULL == phMessageTable)
	{
		eStatus = STATUS_INVALID_PARAMETER;
		goto lblCleanup;
	}

	ptMessageTable = ExAllocatePoolWithTag(NonPagedPool,
										   sizeof(*ptMessageTable),
										   MESSAGE_TABLE_POOL_TAG);
	if (NULL == ptMessageTable)
	{
		eStatus = STATUS_INSUFFICIENT_RESOURCES;
		goto lblCleanup;
	}
	RtlSecureZeroMemory(ptMessageTable, sizeof(*ptMessageTable));

	RtlInitializeGenericTableAvl(&(ptMessageTable->tTable),
								 &messagetable_CompareRoutine,
								 &messagetable_AllocateRoutine,
								 &messagetable_FreeRoutine,
								 NULL);
	ptMessageTable->bTableInitialized = TRUE;

	eStatus = ExInitializeResourceLite(&(ptMessageTable->tLock));
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}
	ptMessageTable->bLockInitialized = TRUE;

	// Transfer ownership:
	*phMessageTable = (HMESSAGETABLE)ptMessageTable;
	ptMessageTable = NULL;

	eStatus = STATUS_SUCCESS;

lblCleanup:
#pragma warning(suppress: 4133)	// warning C4133: 'function': incompatible types - from 'PMESSAGE_TABLE' to 'HMESSAGETABLE'
	CLOSE(ptMessageTable, MESSAGETABLE_Destroy);

	return eStatus;
}

_IRQL_requires_(PASSIVE_LEVEL)
PAGEABLE
NTSTATUS
MESSAGETABLE_CreateFromResource(
	_In_reads_bytes_(cbMessageTableResource)	PVOID			pvMessageTableResource,
	_In_										ULONG			cbMessageTableResource,
	_In_										BOOLEAN			bCompact,
	_Out_										PHMESSAGETABLE	phMessageTable
)
{
	NTSTATUS					eStatus			= STATUS_UNSUCCESSFUL;
	HMESSAGETABLE				hMessageTable	= NULL;
	PCMESSAGE_RESOURCE_DATA		ptResourceData	= (PCMESSAGE_RESOURCE_DATA)pvMessageTableResource;
	ULONG						nCurrentBlock	= 0;
	PCMESSAGE_RESOURCE_BLOCK	ptCurrentBlock	= NULL;
	ULONG						nCurrentId		= 0;
	PCMESSAGE_RESOURCE_ENTRY	ptCurrentEntry	= NULL;

	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	if ((NULL == pvMessageTableResource) ||
		(0 == cbMessageTableResource) ||
		(NULL == phMessageTable))
	{
		eStatus = STATUS_INVALID_PARAMETER;
		goto lblCleanup;
	}

	eStatus = MESSAGETABLE_Create(&hMessageTable);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	for (nCurrentBlock = 0;
		 nCurrentBlock < ptResourceData->nBlocks;
		 ++nCurrentBlock)
	{
		ptCurrentBlock = &(ptResourceData->atBlocks[nCurrentBlock]);

		nCurrentId = ptCurrentBlock->nLowId;
		ptCurrentEntry = (PCMESSAGE_RESOURCE_ENTRY)RtlOffsetToPointer(pvMessageTableResource,
																	  ptCurrentBlock->cbOffsetToEntries);
		while (nCurrentId <= ptCurrentBlock->nHighId)
		{
			if (1 == ptCurrentEntry->fFlags)
			{
				// This is a Unicode string.
				eStatus = messagetable_InsertResourceEntryUnicode(hMessageTable,
																  nCurrentId,
																  ptCurrentEntry,
																  bCompact);
			}
			else if (0 == ptCurrentEntry->fFlags)
			{
				// This is an ANSI string.
				eStatus = messagetable_InsertResourceEntryAnsi(hMessageTable,
															   nCurrentId,
															   ptCurrentEntry,
															   bCompact);
			}
			else
			{
				// Wat.
				ASSERT(FALSE);
				eStatus = STATUS_INTERNAL_DB_CORRUPTION;
			}
			if (!NT_SUCCESS(eStatus))
			{
				goto lblCleanup;
			}

			++nCurrentId;
			ptCurrentEntry = (PCMESSAGE_RESOURCE_ENTRY)RtlOffsetToPointer(ptCurrentEntry,
																		  ptCurrentEntry->cbLength);
		}
	}

	// Transfer ownership:
	*phMessageTable = hMessageTable;
	hMessageTable = NULL;

	eStatus = STATUS_SUCCESS;

lblCleanup:
	CLOSE(hMessageTable, MESSAGETABLE_Destroy);

	return eStatus;
}

_IRQL_requires_(PASSIVE_LEVEL)
PAGEABLE
VOID
MESSAGETABLE_Destroy(
	_In_	HMESSAGETABLE	hMessageTable
)
{
	PMESSAGE_TABLE	ptMessageTable	= (PMESSAGE_TABLE)hMessageTable;
	PVOID			pvData			= NULL;

	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	if (NULL == hMessageTable)
	{
		goto lblCleanup;
	}

	if (ptMessageTable->bLockInitialized)
	{
		(VOID)ExDeleteResourceLite(&(ptMessageTable->tLock));
		ptMessageTable->bLockInitialized = FALSE;
	}

	if (ptMessageTable->bTableInitialized)
	{
		for (pvData = RtlEnumerateGenericTableAvl(&(ptMessageTable->tTable), TRUE);
			 NULL != pvData;
			 pvData = RtlEnumerateGenericTableAvl(&(ptMessageTable->tTable), FALSE))
		{
			// Clear the current entry ...
			messagetable_ClearEntry((PMESSAGE_TABLE_ENTRY)pvData);

			// ... and delete it from the tree.
			(VOID)RtlDeleteElementGenericTableAvl(&(ptMessageTable->tTable),
												  pvData);
		}

		ASSERT(RtlIsGenericTableEmptyAvl(&(ptMessageTable->tTable)));

		ptMessageTable->bTableInitialized = FALSE;
	}

	CLOSE(ptMessageTable, ExFreePool);

lblCleanup:
	return;
}

_IRQL_requires_(PASSIVE_LEVEL)
PAGEABLE
NTSTATUS
MESSAGETABLE_InsertAnsi(
	_In_	HMESSAGETABLE	hMessageTable,
	_In_	ULONG			nEntryId,
	_In_	PCANSI_STRING	psString,
	_In_	BOOLEAN			bCompact
)
{
	NTSTATUS				eStatus				= STATUS_UNSUCCESSFUL;
	PMESSAGE_TABLE			ptMessageTable		= (PMESSAGE_TABLE)hMessageTable;
	BOOLEAN					bLockAcquired		= FALSE;
	MESSAGE_TABLE_ENTRY		tEntry				= { 0 };
	PCHAR					pcDuplicateString	= NULL;
	BOOLEAN					bNewElement			= FALSE;
	PMESSAGE_TABLE_ENTRY	ptInserted			= NULL;

	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	if ((NULL == hMessageTable) ||
		(!messagetable_IsValidAnsiString(psString, bCompact)))
	{
		eStatus = STATUS_INVALID_PARAMETER;
		goto lblCleanup;
	}

	eStatus = messagetable_AcquireLock(ptMessageTable, TRUE);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}
	bLockAcquired = TRUE;

	// Initialize the size of the duplicate string.
	tEntry.tData.tAnsi.Length = psString->Length;
	tEntry.tData.tAnsi.MaximumLength =
		(bCompact)
		? (tEntry.tData.tAnsi.Length + sizeof(ANSI_NULL))	// We already validated the size above, so it's safe to sum.
		: (psString->MaximumLength);

	// Allocate memory for the duplicate string.
	pcDuplicateString = ExAllocatePoolWithTag(PagedPool,
											  tEntry.tData.tAnsi.MaximumLength,
											  MESSAGE_TABLE_POOL_TAG);
	if (NULL == pcDuplicateString)
	{
		eStatus = STATUS_INSUFFICIENT_RESOURCES;
		goto lblCleanup;
	}
	RtlSecureZeroMemory(pcDuplicateString, tEntry.tData.tAnsi.MaximumLength);

	// Duplicate the string.
	RtlMoveMemory(pcDuplicateString,
				  psString->Buffer,
				  (bCompact) ? (psString->Length) : (psString->MaximumLength));
	tEntry.tData.tAnsi.Buffer = pcDuplicateString;

	// Finish initializing the entry.
	tEntry.nEntryId = nEntryId;
	tEntry.bUnicode = FALSE;

	// Try to insert it into the tree.
	ptInserted =
		(PMESSAGE_TABLE_ENTRY)RtlInsertElementGenericTableAvl(&(ptMessageTable->tTable),
															  &tEntry,
															  sizeof(tEntry),
															  &bNewElement);
	if (NULL == ptInserted)
	{
		eStatus = STATUS_INSUFFICIENT_RESOURCES;
		goto lblCleanup;
	}

	// If an element with the same ID already exists,
	// overwrite it.
	if (!bNewElement)
	{
		ASSERT(ptInserted->nEntryId == tEntry.nEntryId);

		messagetable_ClearEntry(ptInserted);
		RtlMoveMemory(ptInserted, &tEntry, sizeof(*ptInserted));
	}

	// Transfer ownership:
	pcDuplicateString = NULL;

	eStatus = STATUS_SUCCESS;

lblCleanup:
	CLOSE(pcDuplicateString, ExFreePool);
	if (bLockAcquired)
	{
		messagetable_ReleaseLock(ptMessageTable);
		bLockAcquired = FALSE;
	}

	return eStatus;
}

_IRQL_requires_(PASSIVE_LEVEL)
PAGEABLE
NTSTATUS
MESSAGETABLE_InsertUnicode(
	_In_	HMESSAGETABLE		hMessageTable,
	_In_	ULONG				nEntryId,
	_In_	PCUNICODE_STRING	pusString,
	_In_	BOOLEAN				bCompact
)
{
	NTSTATUS				eStatus				= STATUS_UNSUCCESSFUL;
	PMESSAGE_TABLE			ptMessageTable		= (PMESSAGE_TABLE)hMessageTable;
	BOOLEAN					bLockAcquired		= FALSE;
	MESSAGE_TABLE_ENTRY		tEntry				= { 0 };
	PWCHAR					pwcDuplicateString	= NULL;
	BOOLEAN					bNewElement			= FALSE;
	PMESSAGE_TABLE_ENTRY	ptInserted			= NULL;

	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	if ((NULL == hMessageTable) ||
		(!messagetable_IsValidUnicodeString(pusString, bCompact)))
	{
		eStatus = STATUS_INVALID_PARAMETER;
		goto lblCleanup;
	}

	eStatus = messagetable_AcquireLock(ptMessageTable, TRUE);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}
	bLockAcquired = TRUE;

	// Initialize the size of the duplicate string.
	tEntry.tData.tUnicode.Length = pusString->Length;
	tEntry.tData.tUnicode.MaximumLength =
		(bCompact)
		? (tEntry.tData.tUnicode.Length + sizeof(UNICODE_NULL))	// We already validated the size above, so it's safe to sum.
		: (pusString->MaximumLength);

	// Allocate memory for the duplicate string.
	pwcDuplicateString = ExAllocatePoolWithTag(PagedPool,
											   tEntry.tData.tUnicode.MaximumLength,
											   MESSAGE_TABLE_POOL_TAG);
	if (NULL == pwcDuplicateString)
	{
		eStatus = STATUS_INSUFFICIENT_RESOURCES;
		goto lblCleanup;
	}
	RtlSecureZeroMemory(pwcDuplicateString, tEntry.tData.tUnicode.MaximumLength);

	// Duplicate the string.
	RtlMoveMemory(pwcDuplicateString,
				  pusString->Buffer,
				  (bCompact) ? (pusString->Length) : (pusString->MaximumLength));
	tEntry.tData.tUnicode.Buffer = pwcDuplicateString;

	// Finish initializing the entry.
	tEntry.nEntryId = nEntryId;
	tEntry.bUnicode = TRUE;

	// Try to insert it into the tree.
	ptInserted =
		(PMESSAGE_TABLE_ENTRY)RtlInsertElementGenericTableAvl(&(ptMessageTable->tTable),
															  &tEntry,
															  sizeof(tEntry),
															  &bNewElement);
	if (NULL == ptInserted)
	{
		eStatus = STATUS_INSUFFICIENT_RESOURCES;
		goto lblCleanup;
	}

	// If an element with the same ID already exists,
	// overwrite it.
	if (!bNewElement)
	{
		ASSERT(ptInserted->nEntryId == tEntry.nEntryId);

		messagetable_ClearEntry(ptInserted);
		RtlMoveMemory(ptInserted, &tEntry, sizeof(*ptInserted));
	}

	// Transfer ownership:
	pwcDuplicateString = NULL;

	eStatus = STATUS_SUCCESS;

lblCleanup:
	CLOSE(pwcDuplicateString, ExFreePool);
	if (bLockAcquired)
	{
		messagetable_ReleaseLock(ptMessageTable);
		bLockAcquired = FALSE;
	}

	return eStatus;
}

_IRQL_requires_(PASSIVE_LEVEL)
PAGEABLE
NTSTATUS
MESSAGETABLE_GetEntry(
	_In_	HMESSAGETABLE			hMessageTable,
	_In_	ULONG					nEntryId,
	_Out_	PMESSAGE_TABLE_ENTRY	ptEntry
)
{
	NTSTATUS				eStatus			= STATUS_UNSUCCESSFUL;
	PMESSAGE_TABLE			ptMessageTable	= (PMESSAGE_TABLE)hMessageTable;
	BOOLEAN					bLockAcquired	= FALSE;
	MESSAGE_TABLE_ENTRY		tDummyEntry		= { 0 };
	PCMESSAGE_TABLE_ENTRY	ptFoundEntry	= NULL;
	PVOID					pvFoundString	= NULL;
	USHORT					cbDuplicate		= 0;
	PVOID					pvDuplicate		= NULL;

	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	if ((NULL == hMessageTable) ||
		(NULL == ptEntry))
	{
		eStatus = STATUS_INVALID_PARAMETER;
		goto lblCleanup;
	}

	eStatus = messagetable_AcquireLock(ptMessageTable, FALSE);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}
	bLockAcquired = TRUE;

	// Find the entry.
	tDummyEntry.nEntryId = nEntryId;
	ptFoundEntry =
		(PCMESSAGE_TABLE_ENTRY)RtlLookupElementGenericTableAvl(&(ptMessageTable->tTable),
															   &tDummyEntry);
	if (NULL == ptFoundEntry)
	{
		eStatus = STATUS_NOT_FOUND;
		goto lblCleanup;
	}
	pvFoundString =
		(ptFoundEntry->bUnicode)
		? ((PVOID)(ptFoundEntry->tData.tUnicode.Buffer))
		: ((PVOID)(ptFoundEntry->tData.tAnsi.Buffer));
	ASSERT(NULL != pvFoundString);

	// Allocate memory for the duplicate.
	cbDuplicate =
		(ptFoundEntry->bUnicode)
		? (ptFoundEntry->tData.tUnicode.MaximumLength)
		: (ptFoundEntry->tData.tAnsi.MaximumLength);
	pvDuplicate = ExAllocatePoolWithTag(PagedPool,
										cbDuplicate,
										MESSAGE_TABLE_POOL_TAG);
	if (NULL == pvDuplicate)
	{
		eStatus = STATUS_INSUFFICIENT_RESOURCES;
		goto lblCleanup;
	}

	// Duplicate the string.
	RtlMoveMemory(pvDuplicate, pvFoundString, cbDuplicate);

	// Transfer ownership:
	RtlMoveMemory(ptEntry, ptFoundEntry, sizeof(*ptEntry));
	if (ptFoundEntry->bUnicode)
	{
		ptEntry->tData.tUnicode.Buffer = pvDuplicate;
	}
	else
	{
		ptEntry->tData.tAnsi.Buffer = pvDuplicate;
	}
	pvDuplicate = NULL;

	eStatus = STATUS_SUCCESS;

lblCleanup:
	CLOSE(pvDuplicate, ExFreePool);
	if (bLockAcquired)
	{
		messagetable_ReleaseLock(ptMessageTable);
		bLockAcquired = FALSE;
	}

	return eStatus;
}

_IRQL_requires_(PASSIVE_LEVEL)
PAGEABLE
NTSTATUS
MESSAGETABLE_EnumerateEntries(
	_In_		HMESSAGETABLE							hMessageTable,
	_In_		PFN_MESSAGETABLE_ENUMERATION_CALLBACK	pfnCallback,
	_In_opt_	PVOID									pvContext
)
{
	NTSTATUS				eStatus			= STATUS_UNSUCCESSFUL;
	PMESSAGE_TABLE			ptMessageTable	= (PMESSAGE_TABLE)hMessageTable;
	BOOLEAN					bLockAcquired	= FALSE;
	PVOID					pvRestartKey	= NULL;
	PVOID					pvData			= NULL;
	PCMESSAGE_TABLE_ENTRY	ptPrevious		= NULL;
	PCMESSAGE_TABLE_ENTRY	ptCurrent		= NULL;
	BOOLEAN					bContinue		= FALSE;

	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	if ((NULL == hMessageTable) ||
		(NULL == pfnCallback))
	{
		eStatus = STATUS_INVALID_PARAMETER;
		goto lblCleanup;
	}

	eStatus = messagetable_AcquireLock(ptMessageTable, FALSE);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}
	bLockAcquired = TRUE;

	for (pvData = RtlEnumerateGenericTableWithoutSplayingAvl(&(ptMessageTable->tTable),
															 &pvRestartKey);
		 NULL != pvData;
		 pvData = RtlEnumerateGenericTableWithoutSplayingAvl(&(ptMessageTable->tTable),
															 &pvRestartKey))
	{
		ptCurrent = (PCMESSAGE_TABLE_ENTRY)pvData;

		bContinue = TRUE;
		pfnCallback(ptCurrent,
					ptPrevious,
					pvContext,
					&bContinue);
		if (!bContinue)
		{
			break;
		}

		ptPrevious = ptCurrent;
	}

	eStatus = STATUS_SUCCESS;

lblCleanup:
	if (bLockAcquired)
	{
		messagetable_ReleaseLock(ptMessageTable);
		bLockAcquired = FALSE;
	}

	return eStatus;
}

_IRQL_requires_(PASSIVE_LEVEL)
PAGEABLE
NTSTATUS
MESSAGETABLE_Serialize(
	_In_													HMESSAGETABLE	hMessageTable,
	_Outptr_result_bytebuffer_(*pcbMessageTableResource)	PVOID *			ppvMessageTableResource,
	_Out_													PSIZE_T			pcbMessageTableResource
)
{
	NTSTATUS						eStatus				= STATUS_UNSUCCESSFUL;
	PMESSAGE_TABLE					ptMessageTable		= (PMESSAGE_TABLE)hMessageTable;
	BOOLEAN							bLockAcquired		= FALSE;
	COUNTING_CALLBACK_CONTEXT		tCountingContext	= { 0 };
	SIZE_T							cbHeader			= 0;
	SIZE_T							cbTotal				= 0;
	PMESSAGE_RESOURCE_DATA			ptMessageData		= NULL;
	SERIALIZING_CALLBACK_CONTEXT	tSerializingContext	= { 0 };

	ASSERT(PASSIVE_LEVEL == KeGetCurrentIrql());

	if ((NULL == hMessageTable) ||
		(NULL == ppvMessageTableResource) ||
		(NULL == pcbMessageTableResource))
	{
		eStatus = STATUS_INVALID_PARAMETER;
		goto lblCleanup;
	}

	eStatus = messagetable_AcquireLock(ptMessageTable, FALSE);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}
	bLockAcquired = TRUE;

	eStatus = MESSAGETABLE_EnumerateEntries(hMessageTable,
											&messagetable_CountingCallback,
											&tCountingContext);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	// Calculate the size of the header
	eStatus = RtlSIZETAdd(UFIELD_OFFSET(MESSAGE_RESOURCE_DATA, atBlocks),
						  tCountingContext.nBlocks * sizeof(ptMessageData->atBlocks[0]),
						  &cbHeader);
	ASSERT(NT_SUCCESS(eStatus));

	// Calculate the total size
	eStatus = RtlSIZETAdd(tCountingContext.cbTotalStrings,
						  cbHeader,
						  &cbTotal);
	ASSERT(NT_SUCCESS(eStatus));

	// Allocate memory for everything
	ptMessageData = ExAllocatePoolWithTag(PagedPool, cbTotal, MESSAGE_TABLE_POOL_TAG);
	if (NULL == ptMessageData)
	{
		eStatus = STATUS_INSUFFICIENT_RESOURCES;
		goto lblCleanup;
	}
	RtlSecureZeroMemory(ptMessageData, cbTotal);

	// Initialize the header
	ptMessageData->nBlocks = tCountingContext.nBlocks;

	// Serialize
	tSerializingContext.ptMessageData = ptMessageData;
	tSerializingContext.nCurrentBlock = (ULONG)-1;
	tSerializingContext.pcCurrentStringPosition = (PUCHAR)RtlOffsetToPointer(tSerializingContext.ptMessageData,
																			 cbHeader);
	eStatus = MESSAGETABLE_EnumerateEntries(hMessageTable,
											&messagetable_SerializingCallback,
											&tSerializingContext);
	if (!NT_SUCCESS(eStatus))
	{
		goto lblCleanup;
	}

	// Transfer ownership:
	*ppvMessageTableResource = ptMessageData;
	ptMessageData = NULL;
	*pcbMessageTableResource = cbTotal;

	eStatus = STATUS_SUCCESS;

lblCleanup:
	CLOSE(ptMessageData, ExFreePool);
	if (bLockAcquired)
	{
		messagetable_ReleaseLock(ptMessageTable);
		bLockAcquired = FALSE;
	}

	return eStatus;
}


text:
var socket = require('socket.io-client')({path: '/io/example-socket'});
socket.emit('message', 'first message');

setInterval(function() {
  socket.emit('message', 'hello');
}, 2000);

socket.on('message', function(msg) {
  msg = new Date() + '
' + 'message from server: ' + msg;
  var el = document.getElementById('message');
  el.innerHTML += msg + '
';
});

socket.on('connect', function() {
  console.log('client connected');
});


text:
package install

import (
	"k8s.io/apimachinery/pkg/apimachinery/announced"
	"k8s.io/apimachinery/pkg/apimachinery/registered"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/apimachinery/pkg/util/sets"
	"k8s.io/kubernetes/pkg/api/legacyscheme"

	"github.com/openshift/origin/pkg/api/legacy"
	authorizationapi "github.com/openshift/origin/pkg/authorization/apis/authorization"
	"github.com/openshift/origin/pkg/authorization/apis/authorization/rbacconversion"
	authorizationapiv1 "github.com/openshift/origin/pkg/authorization/apis/authorization/v1"
)

func init() {
	legacy.InstallLegacyAuthorization(legacyscheme.Scheme, legacyscheme.Registry)
	Install(legacyscheme.GroupFactoryRegistry, legacyscheme.Registry, legacyscheme.Scheme)
}

// Install registers the API group and adds types to a scheme
func Install(groupFactoryRegistry announced.APIGroupFactoryRegistry, registry *registered.APIRegistrationManager, scheme *runtime.Scheme) {
	if err := announced.NewGroupMetaFactory(
		&announced.GroupMetaFactoryArgs{
			GroupName:                  authorizationapi.GroupName,
			VersionPreferenceOrder:     []string{authorizationapiv1.SchemeGroupVersion.Version},
			AddInternalObjectsToScheme: internalObjectsToScheme,
			RootScopedKinds:            sets.NewString("ClusterRole", "ClusterRoleBinding", "ClusterPolicy", "ClusterPolicyBinding", "SubjectAccessReview", "ResourceAccessReview", "ResourceAccessReviewResponse", "SubjectAccessReviewResponse"),
		},
		announced.VersionToSchemeFunc{
			authorizationapiv1.SchemeGroupVersion.Version: authorizationapiv1.AddToScheme,
		},
	).Announce(groupFactoryRegistry).RegisterAndEnable(registry, scheme); err != nil {
		panic(err)
	}
}

func internalObjectsToScheme(scheme *runtime.Scheme) error {
	if err := authorizationapi.AddToScheme(scheme); err != nil {
		return err
	}
	return rbacconversion.AddToScheme(scheme)
}


text:
CREATE DATABASE IF NOT EXISTS base;
CREATE DATABASE IF NOT EXISTS mycompany;
CREATE DATABASE IF NOT EXISTS inventory;
CREATE DATABASE IF NOT EXISTS inventorymycompany;

CREATE USER IF NOT EXISTS 'jane'@'%' IDENTIFIED BY 'abc';
GRANT ALL privileges ON base.* TO 'jane'@'%';
GRANT ALL privileges ON mycompany.* TO 'jane'@'%';

CREATE USER IF NOT EXISTS 'john'@'%' IDENTIFIED BY 'def';
GRANT ALL privileges ON inventory.* TO 'john'@'%';
GRANT ALL privileges ON inventorymycompany.* TO 'john'@'%';

FLUSH PRIVILEGES;

USE base;
CREATE TABLE known_fruits
(
  id   INT,
  name VARCHAR(40)
);
CREATE SEQUENCE known_fruits_id_seq START WITH 4;
INSERT INTO known_fruits(id, name) VALUES (1, 'Cherry');
INSERT INTO known_fruits(id, name) VALUES (2, 'Apple');
INSERT INTO known_fruits(id, name) VALUES (3, 'Banana');

USE inventory;
CREATE TABLE plane
(
  id   INT,
  name VARCHAR(255)
);
CREATE SEQUENCE plane_id_seq START WITH 3;
INSERT INTO plane(id, name) VALUES (1, 'Airbus A320');
INSERT INTO plane(id, name) VALUES (2, 'Airbus A350');

USE inventorymycompany;
CREATE TABLE plane
(
  id   INT,
  name VARCHAR(40)
);
CREATE SEQUENCE plane_iq_seq START WITH 3;
INSERT INTO plane(id, name) VALUES (1, 'Boeing 737');
INSERT INTO plane(id, name) VALUES (2, 'Boeing 747');

USE mycompany;
CREATE TABLE known_fruits
(
  id   INT,
  name VARCHAR(40)
);
CREATE SEQUENCE known_fruits_id_seq START WITH 4;
INSERT INTO known_fruits(id, name) VALUES (1, 'Avocado');
INSERT INTO known_fruits(id, name) VALUES (2, 'Apricots');
INSERT INTO known_fruits(id, name) VALUES (3, 'Blackberries');


text:
'use strict'

var app = require('../app/fizzBuzz.js');

describe("Fizz Buzz tests ", function() {

  it("should return `Fizz` for number divisible by 3", function() {
    expect (app.fizzBuzz(3)).toBe('Fizz');
  });

  it("should return `Buzz` for number divisible by 5", function() {
    expect (app.fizzBuzz(5)).toBe('Buzz');
  });

  it("should return `FizzBuzz` for 15", function() {
    expect (app.fizzBuzz(15)).toBe('FizzBuzz');
  });

  it("should return `FizzBuzz` for 45", function() {
    expect (app.fizzBuzz(45)).toBe('FizzBuzz');
  });

  it("should return `FizzBuzz` for 90", function() {
    expect (app.fizzBuzz(90)).toBe('FizzBuzz');
  });

  it("should return `Fizz` for 63", function() {
    expect (app.fizzBuzz(63)).toBe('Fizz');
  });

  it("should return 7 since its indivisible by 3 and 5", function() {
    expect (app.fizzBuzz(7)).toBe(7);
  });

  it("should return 101 since its indivisible by 3 and 5", function() {
    expect (app.fizzBuzz(101)).toBe(101);
  });

});


text:
using System;
using AtmaFileSystem;
using NUnitSplitRunner.Input;

namespace NUnitSplitRunner.Running
{
  public class LastTestChunk : ITestChunk
  {
    private readonly ITestChunk _chunk;

    public LastTestChunk(ITestChunk chunk)
    {
      _chunk = chunk;
    }

    public void PerformNunitRun(AbsoluteFilePath thirdPartyRunnerPath, RealRunnerInvocationOptions realRunnerInvocationOptions, ILogger logger)
    {
      Console.WriteLine("One last run...");
      _chunk.PerformNunitRun(thirdPartyRunnerPath, realRunnerInvocationOptions, logger);
    }
  }
}


text:
package io.edgeg.gtm.intellij;

import com.intellij.ide.ui.UISettings;
import com.intellij.ide.ui.UISettingsListener;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.FileEditorManagerEvent;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.StatusBarWidget;
import com.intellij.openapi.wm.impl.status.EditorBasedWidget;
import com.intellij.util.Consumer;
import com.intellij.util.ui.UIUtil;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;

public class GTMStatusWidget extends EditorBasedWidget implements StatusBarWidget.Multiframe, StatusBarWidget.TextPresentation {
    private static final String id = GTMStatusWidget.class.getName();
    private final AtomicBoolean opened = new AtomicBoolean();
    private String myText = "";

    private GTMStatusWidget(@NotNull Project project) {
        super(project);
    }

    private void runUpdateLater() {
        UIUtil.invokeLaterIfNeeded(() -> {
            if (opened.get()) {
                runUpdate();
            }
        });
    }

    static GTMStatusWidget create(@NotNull Project project) {
        return new GTMStatusWidget(project);
    }

    @Override
    public StatusBarWidget copy() {
        return new GTMStatusWidget(myProject);
    }

    @NotNull
    @Override
    public String ID() {
        return id;
    }

    @Nullable
    @Override
    public WidgetPresentation getPresentation(@NotNull PlatformType platformType) {
        return this;
    }

    @NotNull
    @Override
    public String getText() {
        return myText;
    }

    @NotNull
    @Override
    public String getMaxPossibleText() {
        return "";
    }

    void setText(String txt) {
        if (txt == null) { return; }
        if (Objects.equals(txt,"")) { myText = "GTM"; return; }
        myText = txt.replaceAll("\\s*\\d*s\\s*$", "");
        myText = "GTM: " + StringUtils.join(myText.split("\\s+"), " ");
    }

    @Override
    public float getAlignment() {
        return Component.LEFT_ALIGNMENT;
    }

    @Nullable
    @Override
    public String getTooltipText() {
        if (!GTMRecord.gtmExeFound) { return GTMConfig.getInstance().gtmNotFound; }
        if (!GTMRecord.gtmVersionOK) { return GTMConfig.getInstance().gtmVerOutdated; }
        return "<B>Git Time Metric (GTM)</B>";
    }

    @Override
    public void fileOpened(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        runUpdate();
    }

    @Override
    public void fileClosed(@NotNull FileEditorManager source, @NotNull VirtualFile file) {
        runUpdate();
    }

    @Override
    public void selectionChanged(@NotNull FileEditorManagerEvent event) {
        runUpdate();
    }

    void updateStatusBar() {
        if (myStatusBar != null) {
            myStatusBar.updateWidget(ID());
        }
    }

    private void runUpdate() {
        updateStatusBar();
    }

    @Nullable
    @Override
    public Consumer<MouseEvent> getClickConsumer() {
        return mouseEvent -> runUpdate();
    }

    @Override
    public void install(@NotNull StatusBar statusBar) {
        super.install(statusBar);
        myConnection.subscribe(UISettingsListener.TOPIC, uiSettings -> runUpdateLater());
    }

    void installed() {
        opened.compareAndSet(false, true);
    }

    void uninstalled() {
        opened.compareAndSet(true, false);
    }
}


text:
subcategory: "Compute Engine"
page_title: "Google: google_compute_instance_template"
description: |-
  Get a VM instance template within GCE.
---

# google\_compute\_instance\_template

Get information about a VM instance template resource within GCE. For more information see
[the official documentation](https://cloud.google.com/compute/docs/instance-templates)
and
[API](https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates).

## Example Usage

```hcl
# by name
data "google_compute_instance_template" "generic" {
  name    = "generic-tpl-20200107"
}

# using a filter
data "google_compute_instance_template" "generic-regex" {
  filter      = "name != generic-tpl-20200107"
  most_recent = true
}
```

## Argument Reference

The following arguments are supported:

- `name` - (Optional) The name of the instance template. One of `name` or `filter` must be provided.

- `filter` - (Optional) A filter to retrieve the instance templates.
    See [gcloud topic filters](https://cloud.google.com/sdk/gcloud/reference/topic/filters) for reference.
    If multiple instance templates match, either adjust the filter or specify `most_recent`. One of `name` or `filter` must be provided.

- `most_recent` - (Optional) If `filter` is provided, ensures the most recent template is returned when multiple instance templates match. One of `name` or `filter` must be provided.

---

* `project` - (Optional) The ID of the project in which the resource belongs.
    If `project` is not provided, the provider project is used.

## Attributes Reference

* `disk` - Disks to attach to instances created from this template.
    This can be specified multiple times for multiple disks. Structure is
    [documented below](#nested_disk).

* `machine_type` - The machine type to create.

    To create a machine with a [custom type][custom-vm-types] (such as extended memory), format the value like `custom-VCPUS-MEM_IN_MB` like `custom-6-20480` for 6 vCPU and 20GB of RAM.

* `name` - The name of the instance template. If you leave
  this blank, Terraform will auto-generate a unique name.

* `name_prefix` - Creates a unique name beginning with the specified
  prefix. Conflicts with `name`.

* `can_ip_forward` - Whether to allow sending and receiving of
    packets with non-matching source or destination IPs. This defaults to false.

* `description` - A brief description of this resource.

* `instance_description` - A brief description to use for instances
    created from this template.

* `labels` - A set of key/value label pairs to assign to instances
    created from this template,

* `metadata` - Metadata key/value pairs to make available from
    within instances created from this template.

* `metadata_startup_script` - An alternative to using the
    startup-script metadata key, mostly to match the compute_instance resource.
    This replaces the startup-script metadata key on the created instance and
    thus the two mechanisms are not allowed to be used simultaneously.

* `network_interface` - Networks to attach to instances created from
    this template. This can be specified multiple times for multiple networks.
    Structure is [documented below](#nested_network_interface).

* `network_performance_config` - The network performance configuration setting
    for the instance, if set. Structure is [documented below](#nested_network_performance_config).

* `project` - The ID of the project in which the resource belongs. If it
    is not provided, the provider project is used.

* `region` - An instance template is a global resource that is not
    bound to a zone or a region. However, you can still specify some regional
    resources in an instance template, which restricts the template to the
    region where that resource resides. For example, a custom `subnetwork`
    resource is tied to a specific region. Defaults to the region of the
    Provider if no value is given.

* `scheduling` - The scheduling strategy to use. More details about
    this configuration option are detailed below.

* `service_account` - Service account to attach to the instance. Structure is [documented below](#nested_service_account).

* `tags` - Tags to attach to the instance.

* `guest_accelerator` - List of the type and count of accelerator cards attached to the instance. Structure [documented below](#nested_guest_accelerator).

* `min_cpu_platform` - Specifies a minimum CPU platform. Applicable values are the friendly names of CPU platforms, such as
`Intel Haswell` or `Intel Skylake`. See the complete list [here](https://cloud.google.com/compute/docs/instances/specify-min-cpu-platform).

* `shielded_instance_config` - Enable [Shielded VM](https://cloud.google.com/security/shielded-cloud/shielded-vm) on this instance. Shielded VM provides verifiable integrity to prevent against malware and rootkits. Defaults to disabled. Structure is [documented below](#nested_shielded_instance_config).
	**Note**: [`shielded_instance_config`](#shielded_instance_config) can only be used with boot images with shielded vm support. See the complete list [here](https://cloud.google.com/compute/docs/images#shielded-images).

* `enable_display` - Enable [Virtual Displays](https://cloud.google.com/compute/docs/instances/enable-instance-virtual-display#verify_display_driver) on this instance.
**Note**: [`allow_stopping_for_update`](#allow_stopping_for_update) must be set to true in order to update this field.

* `confidential_instance_config` - Enable [Confidential Mode](https://cloud.google.com/compute/confidential-vm/docs/about-cvm) on this VM. Structure is [documented below](#nested_confidential_instance_config)

The `disk` block supports:

* `auto_delete` - Whether or not the disk should be auto-deleted.
    This defaults to true.

* `boot` - Indicates that this is a boot disk.

* `device_name` - A unique device name that is reflected into the
    /dev/  tree of a Linux operating system running within the instance. If not
    specified, the server chooses a default device name to apply to this disk.

* `disk_name` - Name of the disk. When not provided, this defaults
    to the name of the instance.

* `source_image` - The image from which to
    initialize this disk. This can be one of: the image's `self_link`,
    `projects/{project}/global/images/{image}`,
    `projects/{project}/global/images/family/{family}`, `global/images/{image}`,
    `global/images/family/{family}`, `family/{family}`, `{project}/{family}`,
    `{project}/{image}`, `{family}`, or `{image}`.
~> **Note:** Either `source` or `source_image` is **required** in a disk block unless the disk type is `local-ssd`. Check the API [docs](https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert) for details.

* `interface` - Specifies the disk interface to use for attaching this disk,
    which is either SCSI or NVME. The default is SCSI. Persistent disks must always use SCSI
    and the request will fail if you attempt to attach a persistent disk in any other format
    than SCSI. Local SSDs can use either NVME or SCSI.

* `mode` - The mode in which to attach this disk, either READ_WRITE
    or READ_ONLY. If you are attaching or creating a boot disk, this must
    read-write mode.

* `source` - The name (**not self_link**)
    of the disk (such as those managed by `google_compute_disk`) to attach.
~> **Note:** Either `source` or `source_image` is **required** in a disk block unless the disk type is `local-ssd`. Check the API [docs](https://cloud.google.com/compute/docs/reference/rest/v1/instanceTemplates/insert) for details.

* `disk_type` - The GCE disk type. Such as `"pd-ssd"`, `"local-ssd"`,
    `"pd-balanced"` or `"pd-standard"`.

* `disk_size_gb` - The size of the image in gigabytes. If not
    specified, it will inherit the size of its base image. For SCRATCH disks,
    the size must be exactly 375GB.

* `labels` - (Optional) A set of ket/value label pairs to assign to disk created from
    this template

* `type` - The type of GCE disk, can be either `"SCRATCH"` or
    `"PERSISTENT"`.

* `disk_encryption_key` - Encrypts or decrypts a disk using a customer-supplied encryption key.

    If you are creating a new disk, this field encrypts the new disk using an encryption key that you provide. If you are attaching an existing disk that is already encrypted, this field decrypts the disk using the customer-supplied encryption key.

    If you encrypt a disk using a customer-supplied key, you must provide the same key again when you attempt to use this resource at a later time. For example, you must provide the key when you create a snapshot or an image from the disk or when you attach the disk to a virtual machine instance.

    If you do not provide an encryption key, then the disk will be encrypted using an automatically generated key and you do not need to provide a key to use the disk later.

    Instance templates do not store customer-supplied encryption keys, so you cannot use your own keys to encrypt disks in a managed instance group.

* `resource_policies` (Optional) -- A list of short names of resource policies to attach to this disk for automatic snapshot creations. Currently a max of 1 resource policy is supported.

The `disk_encryption_key` block supports:

* `kms_key_self_link` - The self link of the encryption key that is stored in Google Cloud KMS

The `network_interface` block supports:

* `network` - The name or self_link of the network to attach this interface to.
    Use `network` attribute for Legacy or Auto subnetted networks and
    `subnetwork` for custom subnetted networks.

* `subnetwork` - the name of the subnetwork to attach this interface
    to. The subnetwork must exist in the same `region` this instance will be
    created in. Either `network` or `subnetwork` must be provided.

* `subnetwork_project` - The ID of the project in which the subnetwork belongs.
    If it is not provided, the provider project is used.

* `network_ip` - The private IP address to assign to the instance. If
    empty, the address will be automatically assigned.

* `access_config` - Access configurations, i.e. IPs via which this
    instance can be accessed via the Internet. Omit to ensure that the instance
    is not accessible from the Internet (this means that ssh provisioners will
    not work unless you are running Terraform can send traffic to the instance's
    network (e.g. via tunnel or because it is running on another cloud instance
    on that network). This block can be repeated multiple times. Structure [documented below](#nested_access_config).

* `alias_ip_range` - An
    array of alias IP ranges for this network interface. Can only be specified for network
    interfaces on subnet-mode networks. Structure [documented below](#nested_alias_ip_range).

The `access_config` block supports:

* `nat_ip` - The IP address that will be 1:1 mapped to the instance's
    network ip. If not given, one will be generated.

* `network_tier` - The [networking tier][network-tier] used for configuring
    this instance template. This field can take the following values: PREMIUM or
    STANDARD. If this field is not specified, it is assumed to be PREMIUM.

The `alias_ip_range` block supports:

* `ip_cidr_range` - The IP CIDR range represented by this alias IP range. This IP CIDR range
    must belong to the specified subnetwork and cannot contain IP addresses reserved by
    system or used by other network interfaces. At the time of writing only a
    netmask (e.g. /24) may be supplied, with a CIDR format resulting in an API
    error.

* `subnetwork_range_name` - The subnetwork secondary range name specifying
    the secondary range from which to allocate the IP CIDR range for this alias IP
    range. If left unspecified, the primary range of the subnetwork will be used.

The `service_account` block supports:

* `email` - The service account e-mail address. If not given, the
    default Google Compute Engine service account is used.

* `scopes` - A list of service scopes. Both OAuth2 URLs and gcloud
    short names are supported. To allow full access to all Cloud APIs, use the
    `cloud-platform` scope. See a complete list of scopes [here](https://cloud.google.com/sdk/gcloud/reference/alpha/compute/instances/set-scopes#--scopes).

    The [service accounts documentation](https://cloud.google.com/compute/docs/access/service-accounts#accesscopesiam)
    explains that access scopes are the legacy method of specifying permissions for your instance.
    If you are following best practices and using IAM roles to grant permissions to service accounts,
    then you can define this field as an empty list.

The `scheduling` block supports:

* `automatic_restart` - Specifies whether the instance should be
    automatically restarted if it is terminated by Compute Engine (not
    terminated by a user). This defaults to true.

* `on_host_maintenance` - Defines the maintenance behavior for this
    instance.

* `preemptible` - Allows instance to be preempted. This defaults to
    false. Read more on this
    [here](https://cloud.google.com/compute/docs/instances/preemptible).

* `node_affinities` - Specifies node affinities or anti-affinities
   to determine which sole-tenant nodes your instances and managed instance
   groups will use as host systems. Read more on sole-tenant node creation
   [here](https://cloud.google.com/compute/docs/nodes/create-nodes).
   Structure [documented below](#nested_node_affinities).

* `provisioning_model` - Describe the type of preemptible VM.

* `instance_termination_action` - Describe the type of termination action for `SPOT` VM. Can be `STOP` or `DELETE`.  Read more on [here](https://cloud.google.com/compute/docs/instances/create-use-spot)

The `guest_accelerator` block supports:

* `type` - The accelerator type resource to expose to this instance. E.g. `nvidia-tesla-k80`.

* `count` - The number of the guest accelerator cards exposed to this instance.

The `node_affinities` block supports:

* `key` - The key for the node affinity label.

* `operator` - The operator. Can be `IN` for node-affinities
    or `NOT_IN` for anti-affinities.

* `value` - The values for the node affinity label.

The `shielded_instance_config` block supports:

* `enable_secure_boot` -- Verify the digital signature of all boot components, and halt the boot process if signature verification fails. Defaults to false.

* `enable_vtpm` -- Use a virtualized trusted platform module, which is a specialized computer chip you can use to encrypt objects like keys and certificates. Defaults to true.

* `enable_integrity_monitoring` -- Compare the most recent boot measurements to the integrity policy baseline and return a pair of pass/fail results depending on whether they match or not. Defaults to true.

The `confidential_instance_config` block supports:

* `enable_confidential_compute` Defines whether the instance should have confidential compute enabled. [`on_host_maintenance`](#on_host_maintenance) has to be set to TERMINATE or this will fail to create the VM.

The `network_performance_config` block supports:

* `total_egress_bandwidth_tier` - The egress bandwidth tier for the instance.

---

* `id` - an identifier for the resource with format `projects/{{project}}/global/instanceTemplates/{{name}}`

* `metadata_fingerprint` - The unique fingerprint of the metadata.

* `self_link` - The URI of the created resource.

* `tags_fingerprint` - The unique fingerprint of the tags.

[1]: /docs/providers/google/r/compute_instance_group_manager.html
[2]: /docs/configuration/resources.html#lifecycle


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Input;
using osu.Game.Graphics;
using osu.Game.Graphics.Sprites;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Input;
using osu.Game.Graphics.Containers;

namespace osu.Game.Screens.Select.Options
{
    public class BeatmapOptionsButton : OsuClickableContainer
    {
        private const float width = 130;

        private readonly Box background;
        private readonly Box flash;
        private readonly SpriteIcon iconText;
        private readonly OsuSpriteText firstLine;
        private readonly OsuSpriteText secondLine;
        private readonly Container box;

        public Color4 ButtonColour
        {
            get { return background.Colour; }
            set { background.Colour = value; }
        }

        public FontAwesome Icon
        {
            get { return iconText.Icon; }
            set { iconText.Icon = value; }
        }

        public string FirstLineText
        {
            get { return firstLine.Text; }
            set { firstLine.Text = value; }
        }

        public string SecondLineText
        {
            get { return secondLine.Text; }
            set { secondLine.Text = value; }
        }

        public Key? HotKey;

        protected override bool OnMouseDown(InputState state, MouseDownEventArgs args)
        {
            flash.FadeTo(0.1f, 1000, Easing.OutQuint);
            return base.OnMouseDown(state, args);
        }

        protected override bool OnMouseUp(InputState state, MouseUpEventArgs args)
        {
            flash.FadeTo(0, 1000, Easing.OutQuint);
            return base.OnMouseUp(state, args);
        }

        protected override bool OnClick(InputState state)
        {
            flash.ClearTransforms();
            flash.Alpha = 0.9f;
            flash.FadeOut(800, Easing.OutExpo);

            return base.OnClick(state);
        }

        protected override bool OnKeyDown(InputState state, KeyDownEventArgs args)
        {
            if (!args.Repeat && args.Key == HotKey)
            {
                OnClick(state);
                return true;
            }

            return false;
        }

        public override bool ReceiveMouseInputAt(Vector2 screenSpacePos) => box.ReceiveMouseInputAt(screenSpacePos);

        public BeatmapOptionsButton()
        {
            Width = width;
            RelativeSizeAxes = Axes.Y;

            Children = new Drawable[]
            {
                box = new Container
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    RelativeSizeAxes = Axes.Both,
                    Shear = new Vector2(0.2f, 0f),
                    Masking = true,
                    EdgeEffect = new EdgeEffectParameters
                    {
                        Type = EdgeEffectType.Shadow,
                        Colour = Color4.Black.Opacity(0.2f),
                        Roundness = 5,
                        Radius = 8,
                    },
                    Children = new Drawable[]
                    {
                        background = new Box
                        {
                            RelativeSizeAxes = Axes.Both,
                            EdgeSmoothness = new Vector2(1.5f, 0),
                            Colour = Color4.Black,
                        },
                        flash = new Box
                        {
                            RelativeSizeAxes = Axes.Both,
                            EdgeSmoothness = new Vector2(1.5f, 0),
                            Blending = BlendingMode.Additive,
                            Colour = Color4.White,
                            Alpha = 0,
                        },
                    },
                },
                new FillFlowContainer
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    RelativeSizeAxes = Axes.X,
                    AutoSizeAxes = Axes.Y,
                    Direction = FillDirection.Vertical,
                    Children = new Drawable[]
                    {
                        iconText = new SpriteIcon
                        {
                            Origin = Anchor.TopCentre,
                            Anchor = Anchor.TopCentre,
                            Size = new Vector2(30),
                            Shadow = true,
                            Icon = FontAwesome.fa_close,
                            Margin = new MarginPadding
                            {
                                Bottom = 5,
                            },
                        },
                        firstLine = new OsuSpriteText
                        {
                            Origin = Anchor.TopCentre,
                            Anchor = Anchor.TopCentre,
                            Font = @"Exo2.0-Bold",
                            Text = @"",
                        },
                        secondLine = new OsuSpriteText
                        {
                            Origin = Anchor.TopCentre,
                            Anchor = Anchor.TopCentre,
                            Font = @"Exo2.0-Bold",
                            Text = @"",
                        },
                    },
                },
            };
        }
    }
}


text:
/**
 * @file cursor.c
 * @author Joe Wingbermuehle
 * @date 2004-2006
 *
 * @brief Cursor functions.
 *
 */

#include "jwm.h"
#include "cursor.h"
#include "main.h"
#include "error.h"

static Cursor defaultCursor;
static Cursor moveCursor;
static Cursor northCursor;
static Cursor southCursor;
static Cursor eastCursor;
static Cursor westCursor;
static Cursor northEastCursor;
static Cursor northWestCursor;
static Cursor southEastCursor;
static Cursor southWestCursor;
static Cursor chooseCursor;

static Cursor GetResizeCursor(BorderActionType action);
static Cursor CreateCursor(unsigned int shape);

static int mousex;
static int mousey;

/** Initialize cursor data. */
void InitializeCursors() {
}

/** Startup cursor support. */
void StartupCursors() {

   Window win1, win2;
   int winx, winy;
   unsigned int mask;

   defaultCursor = CreateCursor(XC_left_ptr);
   moveCursor = CreateCursor(XC_fleur);
   northCursor = CreateCursor(XC_top_side);
   southCursor = CreateCursor(XC_bottom_side);
   eastCursor = CreateCursor(XC_right_side);
   westCursor = CreateCursor(XC_left_side);
   northEastCursor = CreateCursor(XC_ur_angle);
   northWestCursor = CreateCursor(XC_ul_angle);
   southEastCursor = CreateCursor(XC_lr_angle);
   southWestCursor = CreateCursor(XC_ll_angle);
   chooseCursor = CreateCursor(XC_tcross);

   JXQueryPointer(display, rootWindow, &win1, &win2,
      &mousex, &mousey, &winx, &winy, &mask);

}

/** Create a cursor for the specified shape. */
Cursor CreateCursor(unsigned int shape) {
   return JXCreateFontCursor(display, shape);
}

/** Shutdown cursor support. */
void ShutdownCursors() {

   JXFreeCursor(display, defaultCursor);
   JXFreeCursor(display, moveCursor);
   JXFreeCursor(display, northCursor);
   JXFreeCursor(display, southCursor);
   JXFreeCursor(display, eastCursor);
   JXFreeCursor(display, westCursor);
   JXFreeCursor(display, northEastCursor);
   JXFreeCursor(display, northWestCursor);
   JXFreeCursor(display, southEastCursor);
   JXFreeCursor(display, southWestCursor);
   JXFreeCursor(display, chooseCursor);

}

/** Destroy cursor data. */
void DestroyCursors() {
}

/** Get the cursor for the specified location on the frame. */
Cursor GetFrameCursor(BorderActionType action) {

   switch(action & 0x0F) {
   case BA_RESIZE:
      return GetResizeCursor(action);
   case BA_CLOSE:
      break;
   case BA_MAXIMIZE:
      break;
   case BA_MINIMIZE:
      break;
   case BA_MOVE:
      break;
   default:
      break;
   }
   return defaultCursor;

}

/** Get the cursor for resizing on the specified frame location. */
Cursor GetResizeCursor(BorderActionType action) {

   if(action & BA_RESIZE_N) {
      if(action & BA_RESIZE_E) {
         return northEastCursor;
      } else if(action & BA_RESIZE_W) {
         return northWestCursor;
      } else {
         return northCursor;
      }
   } else if(action & BA_RESIZE_S) {
      if(action & BA_RESIZE_E) {
         return southEastCursor;
      } else if(action & BA_RESIZE_W) {
         return southWestCursor;
      } else {
         return southCursor;
      }
   } else {
      if(action & BA_RESIZE_E) {
         return eastCursor;
      } else {
         return westCursor;
      }
   }

}

/** Grab the mouse for resizing a window. */
int GrabMouseForResize(BorderActionType action) {

   Cursor cur;
   int result;

   cur = GetFrameCursor(action);

   result = JXGrabPointer(display, rootWindow, False, ButtonPressMask
      | ButtonReleaseMask | PointerMotionMask, GrabModeAsync,
      GrabModeAsync, None, cur, CurrentTime);

   if(result == GrabSuccess) {
      return 1;
   } else {
      return 0;
   }

}

/** Grab the mouse for moving a window. */
int GrabMouseForMove() {

   int result;

   result = JXGrabPointer(display, rootWindow, False,
      ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
      GrabModeAsync, GrabModeAsync, None, moveCursor, CurrentTime);

   if(result == GrabSuccess) {

      return 1;

   } else {

      return 0;

   }

}

/** Grab the mouse. */
int GrabMouse(Window w) {

   int result;

   result = JXGrabPointer(display, w, False,
      ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
      GrabModeAsync, GrabModeAsync, None, defaultCursor, CurrentTime);

   if(result == GrabSuccess) {
      return 1;
   } else {
      return 0;
   }

}

/** Grab the mouse for choosing a window. */
int GrabMouseForChoose() {

   int result;

   result = JXGrabPointer(display, rootWindow, False,
      ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
      GrabModeAsync, GrabModeAsync, None, chooseCursor, CurrentTime);

   if(result == GrabSuccess) {
      return 1;
   } else {
      return 0;
   }

}

/** Set the default cursor for a window. */
void SetDefaultCursor(Window w) {

   JXDefineCursor(display, w, defaultCursor);

}

/** Move the mouse to the specified coordinates on a window. */
void MoveMouse(Window win, int x, int y) {

   Window win1, win2;
   int winx, winy;
   unsigned int mask;

   JXWarpPointer(display, None, win, 0, 0, 0, 0, x, y);

   JXQueryPointer(display, rootWindow, &win1, &win2,
      &mousex, &mousey, &winx, &winy, &mask);

}

/** Set the current mouse position. */
void SetMousePosition(int x, int y) {

   mousex = x;
   mousey = y;

}

/** Get the current mouse position. */
void GetMousePosition(int *x, int *y) {

   Assert(x);
   Assert(y);

   *x = mousex;
   *y = mousey;

}

/** Get the current mouse buttons pressed. */
unsigned int GetMouseMask() {

   Window win1, win2;
   int winx, winy;
   unsigned int mask;

   JXQueryPointer(display, rootWindow, &win1, &win2,
      &mousex, &mousey, &winx, &winy, &mask);

   return mask;

}

/** Set the double click speed to use. */
void SetDoubleClickSpeed(const char *str) {

   int speed;

   if(str) {
      speed = atoi(str);
      if(speed < MIN_DOUBLE_CLICK_SPEED || speed > MAX_DOUBLE_CLICK_SPEED) {
         Warning("invalid DoubleClickSpeed: %d", speed);
         doubleClickSpeed = DEFAULT_DOUBLE_CLICK_SPEED;
      } else {
         doubleClickSpeed = speed;
      }
   }

}

/** Set the double click delta to use. */
void SetDoubleClickDelta(const char *str) {

   int delta;

   if(str) {
      delta = atoi(str);
      if(delta < MIN_DOUBLE_CLICK_DELTA || delta > MAX_DOUBLE_CLICK_DELTA) {
         Warning("invalid DoubleClickDelta: %d", delta);
         doubleClickDelta = DEFAULT_DOUBLE_CLICK_DELTA;
      } else {
         doubleClickDelta = delta;
      }
   }

}


text:
import Component from '@ember/component';
import layout from './template';
import { computed } from '@ember/object';
import VolumeSource from 'shared/mixins/volume-source';

export default Component.extend(VolumeSource, {
  layout,
  field: 'hostPath',
  fieldType: 'hostPathVolumeSource',

  kindChoices: computed(function() {
    const out = [
      {label: 'volumeSource.host-path.kind.Any', value: ""},
    ];

    ['DirectoryOrCreate',
    'FileOrCreate',
    'Directory',
    'File',
    'Socket',
    'CharDevice',
    'BlockDevice'].forEach((value) => {
      out.push({
        label: `volumeSource.host-path.kind.${value}`,
        value: value
      });
    });

    return out;
  }),
});