text:
package brontide

import (
	"crypto/cipher"
	"crypto/sha256"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"math"

	"golang.org/x/crypto/chacha20poly1305"
	"golang.org/x/crypto/hkdf"

	"github.com/roasbeef/btcd/btcec"
)

const (
	// protocolName is the precise instantiation of the Noise protocol
	// handshake at the center of Brontide. This value will be used as part
	// of the prologue. If the initiator and responder aren't using the
	// exact same string for this value, along with prologue of the Bitcoin
	// network, then the initial handshake will fail.
	protocolName = "Noise_XK_secp256k1_ChaChaPoly_SHA256"

	// macSize is the length in bytes of the tags generated by poly1305.
	macSize = 16

	// lengthHeaderSize is the number of bytes used to prefix encode the
	// length of a message payload.
	lengthHeaderSize = 2

	// keyRotationInterval is the number of messages sent on a single
	// cipher stream before the keys are rotated forwards.
	keyRotationInterval = 1000
)

var (
	// ErrMaxMessageLengthExceeded is returned a message to be written to
	// the cipher session exceeds the maximum allowed message payload.
	ErrMaxMessageLengthExceeded = errors.New("the generated payload exceeds " +
		"the max allowed message length of (2^16)-1")
)

// TODO(roasbeef): free buffer pool?

// ecdh performs an ECDH operation between pub and priv. The returned value is
// the sha256 of the compressed shared point.
func ecdh(pub *btcec.PublicKey, priv *btcec.PrivateKey) []byte {
	s := &btcec.PublicKey{}
	x, y := btcec.S256().ScalarMult(pub.X, pub.Y, priv.D.Bytes())
	s.X = x
	s.Y = y

	h := sha256.Sum256(s.SerializeCompressed())
	return h[:]
}

// cipherState encapsulates the state for the AEAD which will be used to
// encrypt+authenticate any payloads sent during the handshake, and messages
// sent once the handshake has completed.
type cipherState struct {
	// nonce is the nonce passed into the chacha20-poly1305 instance for
	// encryption+decryption. The nonce is incremented after each successful
	// encryption/decryption.
	//
	// TODO(roasbeef): this should actually be 96 bit
	nonce uint64

	// secretKey is the shared symmetric key which will be used to
	// instantiate the cipher.
	//
	// TODO(roasbeef): m-lock??
	secretKey [32]byte

	// salt is an additional secret which is used during key rotation to
	// generate new keys.
	salt [32]byte

	// cipher is an instance of the ChaCha20-Poly1305 AEAD construction
	// created using the secretKey above.
	cipher cipher.AEAD
}

// Encrypt returns a ciphertext which is the encryption of the plainText
// observing the passed associatedData within the AEAD construction.
func (c *cipherState) Encrypt(associatedData, cipherText, plainText []byte) []byte {
	defer func() {
		c.nonce++

		if c.nonce == keyRotationInterval {
			c.rotateKey()
		}
	}()

	var nonce [12]byte
	binary.LittleEndian.PutUint64(nonce[4:], c.nonce)

	return c.cipher.Seal(cipherText, nonce[:], plainText, associatedData)
}

// Decrypt attempts to decrypt the passed ciphertext observing the specified
// associatedData within the AEAD construction. In the case that the final MAC
// check fails, then a non-nil error will be returned.
func (c *cipherState) Decrypt(associatedData, plainText, cipherText []byte) ([]byte, error) {
	defer func() {
		c.nonce++

		if c.nonce == keyRotationInterval {
			c.rotateKey()
		}
	}()

	var nonce [12]byte
	binary.LittleEndian.PutUint64(nonce[4:], c.nonce)

	return c.cipher.Open(plainText, nonce[:], cipherText, associatedData)
}

// InitializeKey initializes the secret key and AEAD cipher scheme based off of
// the passed key.
func (c *cipherState) InitializeKey(key [32]byte) {
	c.secretKey = key
	c.nonce = 0

	// Safe to ignore the error here as our key is properly sized
	// (32-bytes).
	c.cipher, _ = chacha20poly1305.New(c.secretKey[:])
}

// InitializeKeyWithSalt is identical to InitializeKey however it also sets the
// cipherState's salt field which is used for key rotation.
func (c *cipherState) InitializeKeyWithSalt(salt, key [32]byte) {
	c.salt = salt
	c.InitializeKey(key)
}

// rotateKey rotates the current encryption/decryption key for this cipherState
// instance. Key rotation is performed by ratcheting the current key forward
// using an HKDF invocation with the cipherState's salt as the salt, and the
// current key as the input.
func (c *cipherState) rotateKey() {
	var (
		info    []byte
		nextKey [32]byte
	)

	oldKey := c.secretKey
	h := hkdf.New(sha256.New, oldKey[:], c.salt[:], info)

	// hkdf(ck, k, zero)
	// |
	// | \
	// |  \
	// ck  k'
	h.Read(c.salt[:])
	h.Read(nextKey[:])

	c.InitializeKey(nextKey)
}

// symmetricState encapsulates a cipherState object and houses the ephemeral
// handshake digest state. This struct is used during the handshake to derive
// new shared secrets based off of the result of ECDH operations. Ultimately,
// the final key yielded by this struct is the result of an incremental
// Triple-DH operation.
type symmetricState struct {
	cipherState

	// chainingKey is used as the salt to the HKDF function to derive a new
	// chaining key as well as a new tempKey which is used for
	// encryption/decryption.
	chainingKey [32]byte

	// tempKey is the latter 32 bytes resulted from the latest HKDF
	// iteration. This key is used to encrypt/decrypt any handshake
	// messages or payloads sent until the next DH operation is executed.
	tempKey [32]byte

	// handshakeDigest is the cumulative hash digest of all handshake
	// messages sent from start to finish. This value is never transmitted
	// to the other side, but will be used as the AD when
	// encrypting/decrypting messages using our AEAD construction.
	handshakeDigest [32]byte
}

// mixKey is implements a basic HKDF-based key ratchet. This method is called
// with the result of each DH output generated during the handshake process.
// The first 32 bytes extract from the HKDF reader is the next chaining key,
// then latter 32 bytes become the temp secret key using within any future AEAD
// operations until another DH operation is performed.
func (s *symmetricState) mixKey(input []byte) {
	var info []byte

	secret := input
	salt := s.chainingKey
	h := hkdf.New(sha256.New, secret, salt[:], info)

	// hkdf(ck, input, zero)
	// |
	// | \
	// |  \
	// ck  k
	h.Read(s.chainingKey[:])
	h.Read(s.tempKey[:])

	// cipher.k = temp_key
	s.InitializeKey(s.tempKey)
}

// mixHash hashes the passed input data into the cumulative handshake digest.
// The running result of this value (h) is used as the associated data in all
// decryption/encryption operations.
func (s *symmetricState) mixHash(data []byte) {
	h := sha256.New()
	h.Write(s.handshakeDigest[:])
	h.Write(data)

	copy(s.handshakeDigest[:], h.Sum(nil))
}

// EncryptAndHash returns the authenticated encryption of the passed plaintext.
// When encrypting the handshake digest (h) is used as the associated data to
// the AEAD cipher.
func (s *symmetricState) EncryptAndHash(plaintext []byte) []byte {
	ciphertext := s.Encrypt(s.handshakeDigest[:], nil, plaintext)

	s.mixHash(ciphertext)

	return ciphertext
}

// DecryptAndHash returns the authenticated decryption of the passed
// ciphertext.  When encrypting the handshake digest (h) is used as the
// associated data to the AEAD cipher.
func (s *symmetricState) DecryptAndHash(ciphertext []byte) ([]byte, error) {
	plaintext, err := s.Decrypt(s.handshakeDigest[:], nil, ciphertext)
	if err != nil {
		return nil, err
	}

	s.mixHash(ciphertext)

	return plaintext, nil
}

// InitializeSymmetric initializes the symmetric state by setting the handshake
// digest (h) and the chaining key (ck) to protocol name.
func (s *symmetricState) InitializeSymmetric(protocolName []byte) {
	var empty [32]byte

	s.handshakeDigest = sha256.Sum256(protocolName)
	s.chainingKey = s.handshakeDigest
	s.InitializeKey(empty)
}

// handshakeState encapsulates the symmetricState and keeps track of all the
// public keys (static and ephemeral) for both sides during the handshake
// transcript. If the handshake completes successfully, then two instances of a
// cipherState are emitted: one to encrypt messages from initiator to
// responder, and the other for the opposite direction.
type handshakeState struct {
	symmetricState

	initiator bool

	localStatic    *btcec.PrivateKey
	localEphemeral *btcec.PrivateKey

	remoteStatic    *btcec.PublicKey
	remoteEphemeral *btcec.PublicKey
}

// newHandshakeState returns a new instance of the handshake state initialized
// with the prologue and protocol name. If this is the responder's handshake
// state, then the remotePub can be nil.
func newHandshakeState(initiator bool, prologue []byte,
	localPub *btcec.PrivateKey, remotePub *btcec.PublicKey) handshakeState {

	h := handshakeState{
		initiator:    initiator,
		localStatic:  localPub,
		remoteStatic: remotePub,
	}

	// Set the current chaining key and handshake digest to the hash of the
	// protocol name, and additionally mix in the prologue. If either sides
	// disagree about the prologue or protocol name, then the handshake
	// will fail.
	h.InitializeSymmetric([]byte(protocolName))
	h.mixHash(prologue)

	// In Noise_XK, then initiator should know the responder's static
	// public key, therefore we include the responder's static key in the
	// handshake digest. If the initiator gets this value wrong, then the
	// handshake will fail.
	if initiator {
		h.mixHash(remotePub.SerializeCompressed())
	} else {
		h.mixHash(localPub.PubKey().SerializeCompressed())
	}

	return h
}

// EphemeralGenerator is a functional option that allows callers to substitute
// a custom function for use when generating ephemeral keys for ActOne or
// ActTwo.  The function closure return by this function can be passed into
// NewBrontideMachine as a function option parameter.
func EphemeralGenerator(gen func() (*btcec.PrivateKey, error)) func(*Machine) {
	return func(m *Machine) {
		m.ephemeralGen = gen
	}
}

// Machine is a state-machine which implements Brontide: an
// Authenticated-key Exchange in Three Acts. Brontide is derived from the Noise
// framework, specifically implementing the Noise_XK handshake. Once the
// initial 3-act handshake has completed all messages are encrypted with a
// chacha20 AEAD cipher. On the wire, all messages are prefixed with an
// authenticated+encrypted length field. Additionally, the encrypted+auth'd
// length prefix is used as the AD when encrypting+decryption messages. This
// construction provides confidentiality of packet length, avoids introducing
// a padding-oracle, and binds the encrypted packet length to the packet
// itself.
//
// The acts proceeds the following order (initiator on the left):
//  GenActOne()   ->
//                    RecvActOne()
//                <-  GenActTwo()
//  RecvActTwo()
//  GenActThree() ->
//                    RecvActThree()
//
// This exchange corresponds to the following Noise handshake:
//   <- s
//   ...
//   -> e, es
//   <- e, ee
//   -> s, se
type Machine struct {
	sendCipher cipherState
	recvCipher cipherState

	ephemeralGen func() (*btcec.PrivateKey, error)

	handshakeState
}

// NewBrontideMachine creates a new instance of the brontide state-machine. If
// the responder (listener) is creating the object, then the remotePub should
// be nil. The handshake state within brontide is initialized using the ascii
// string "bitcoin" as the prologue. The last parameter is a set of variadic
// arguments for adding additional options to the brontide Machine
// initialization.
func NewBrontideMachine(initiator bool, localPub *btcec.PrivateKey,
	remotePub *btcec.PublicKey, options ...func(*Machine)) *Machine {

	handshake := newHandshakeState(initiator, []byte("lightning"), localPub,
		remotePub)

	m := &Machine{handshakeState: handshake}

	// With the initial base machine created, we'll assign our default
	// version of the ephemeral key generator.
	m.ephemeralGen = func() (*btcec.PrivateKey, error) {
		return btcec.NewPrivateKey(btcec.S256())
	}

	// With the default options established, we'll now process all the
	// options passed in as parameters.
	for _, option := range options {
		option(m)
	}

	return m
}

const (
	// HandshakeVersion is the expected version of the brontide handshake.
	// Any messages that carry a different version will cause the handshake
	// to abort immediately.
	HandshakeVersion = byte(0)

	// ActOneSize is the size of the packet sent from initiator to
	// responder in ActOne. The packet consists of a handshake version, an
	// ephemeral key in compressed format, and a 16-byte poly1305 tag.
	//
	// 1 + 33 + 16
	ActOneSize = 50

	// ActTwoSize is the size the packet sent from responder to initiator
	// in ActTwo. The packet consists of a handshake version, an ephemeral
	// key in compressed format and a 16-byte poly1305 tag.
	//
	// 1 + 33 + 16
	ActTwoSize = 50

	// ActThreeSize is the size of the packet sent from initiator to
	// responder in ActThree. The packet consists of a handshake version,
	// the initiators static key encrypted with strong forward secrecy and
	// a 16-byte poly1035
	// tag.
	//
	// 1 + 33 + 16 + 16
	ActThreeSize = 66
)

// GenActOne generates the initial packet (act one) to be sent from initiator
// to responder. During act one the initiator generates a fresh ephemeral key,
// hashes it into the handshake digest, and performs an ECDH between this key
// and the responder's static key. Future payloads are encrypted with a key
// derived from this result.
//
//    -> e, es
func (b *Machine) GenActOne() ([ActOneSize]byte, error) {
	var (
		err    error
		actOne [ActOneSize]byte
	)

	// e
	b.localEphemeral, err = b.ephemeralGen()
	if err != nil {
		return actOne, err
	}

	ephemeral := b.localEphemeral.PubKey().SerializeCompressed()
	b.mixHash(ephemeral)

	// es
	s := ecdh(b.remoteStatic, b.localEphemeral)
	b.mixKey(s[:])

	authPayload := b.EncryptAndHash([]byte{})

	actOne[0] = HandshakeVersion
	copy(actOne[1:34], ephemeral)
	copy(actOne[34:], authPayload)

	return actOne, nil
}

// RecvActOne processes the act one packet sent by the initiator. The responder
// executes the mirrored actions to that of the initiator extending the
// handshake digest and deriving a new shared secret based on a ECDH with the
// initiator's ephemeral key and responder's static key.
func (b *Machine) RecvActOne(actOne [ActOneSize]byte) error {
	var (
		err error
		e   [33]byte
		p   [16]byte
	)

	// If the handshake version is unknown, then the handshake fails
	// immediately.
	if actOne[0] != HandshakeVersion {
		return fmt.Errorf("Act One: invalid handshake version: %v, "+
			"only %v is valid, msg=%x", actOne[0], HandshakeVersion,
			actOne[:])
	}

	copy(e[:], actOne[1:34])
	copy(p[:], actOne[34:])

	// e
	b.remoteEphemeral, err = btcec.ParsePubKey(e[:], btcec.S256())
	if err != nil {
		return err
	}
	b.mixHash(b.remoteEphemeral.SerializeCompressed())

	// es
	s := ecdh(b.remoteEphemeral, b.localStatic)
	b.mixKey(s)

	// If the initiator doesn't know our static key, then this operation
	// will fail.
	_, err = b.DecryptAndHash(p[:])
	return err
}

// GenActTwo generates the second packet (act two) to be sent from the
// responder to the initiator. The packet for act two is identify to that of
// act one, but then results in a different ECDH operation between the
// initiator's and responder's ephemeral keys.
//
//    <- e, ee
func (b *Machine) GenActTwo() ([ActTwoSize]byte, error) {
	var (
		err    error
		actTwo [ActTwoSize]byte
	)

	// e
	b.localEphemeral, err = b.ephemeralGen()
	if err != nil {
		return actTwo, err
	}

	ephemeral := b.localEphemeral.PubKey().SerializeCompressed()
	b.mixHash(b.localEphemeral.PubKey().SerializeCompressed())

	// ee
	s := ecdh(b.remoteEphemeral, b.localEphemeral)
	b.mixKey(s)

	authPayload := b.EncryptAndHash([]byte{})

	actTwo[0] = HandshakeVersion
	copy(actTwo[1:34], ephemeral)
	copy(actTwo[34:], authPayload)

	return actTwo, nil
}

// RecvActTwo processes the second packet (act two) sent from the responder to
// the initiator. A successful processing of this packet authenticates the
// initiator to the responder.
func (b *Machine) RecvActTwo(actTwo [ActTwoSize]byte) error {
	var (
		err error
		e   [33]byte
		p   [16]byte
	)

	// If the handshake version is unknown, then the handshake fails
	// immediately.
	if actTwo[0] != HandshakeVersion {
		return fmt.Errorf("Act Two: invalid handshake version: %v, "+
			"only %v is valid, msg=%x", actTwo[0], HandshakeVersion,
			actTwo[:])
	}

	copy(e[:], actTwo[1:34])
	copy(p[:], actTwo[34:])

	// e
	b.remoteEphemeral, err = btcec.ParsePubKey(e[:], btcec.S256())
	if err != nil {
		return err
	}
	b.mixHash(b.remoteEphemeral.SerializeCompressed())

	// ee
	s := ecdh(b.remoteEphemeral, b.localEphemeral)
	b.mixKey(s)

	_, err = b.DecryptAndHash(p[:])
	return err
}

// GenActThree creates the final (act three) packet of the handshake. Act three
// is to be sent from the initiator to the responder. The purpose of act three
// is to transmit the initiator's public key under strong forward secrecy to
// the responder. This act also includes the final ECDH operation which yields
// the final session.
//
//    -> s, se
func (b *Machine) GenActThree() ([ActThreeSize]byte, error) {
	var actThree [ActThreeSize]byte

	ourPubkey := b.localStatic.PubKey().SerializeCompressed()
	ciphertext := b.EncryptAndHash(ourPubkey)

	s := ecdh(b.remoteEphemeral, b.localStatic)
	b.mixKey(s)

	authPayload := b.EncryptAndHash([]byte{})

	actThree[0] = HandshakeVersion
	copy(actThree[1:50], ciphertext)
	copy(actThree[50:], authPayload)

	// With the final ECDH operation complete, derive the session sending
	// and receiving keys.
	b.split()

	return actThree, nil
}

// RecvActThree processes the final act (act three) sent from the initiator to
// the responder. After processing this act, the responder learns of the
// initiator's static public key. Decryption of the static key serves to
// authenticate the initiator to the responder.
func (b *Machine) RecvActThree(actThree [ActThreeSize]byte) error {
	var (
		err error
		s   [33 + 16]byte
		p   [16]byte
	)

	// If the handshake version is unknown, then the handshake fails
	// immediately.
	if actThree[0] != HandshakeVersion {
		return fmt.Errorf("Act Three: invalid handshake version: %v, "+
			"only %v is valid, msg=%x", actThree[0], HandshakeVersion,
			actThree[:])
	}

	copy(s[:], actThree[1:33+16+1])
	copy(p[:], actThree[33+16+1:])

	// s
	remotePub, err := b.DecryptAndHash(s[:])
	if err != nil {
		return err
	}
	b.remoteStatic, err = btcec.ParsePubKey(remotePub, btcec.S256())
	if err != nil {
		return err
	}

	// se
	se := ecdh(b.remoteStatic, b.localEphemeral)
	b.mixKey(se)

	if _, err := b.DecryptAndHash(p[:]); err != nil {
		return err
	}

	// With the final ECDH operation complete, derive the session sending
	// and receiving keys.
	b.split()

	return nil
}

// split is the final wrap-up act to be executed at the end of a successful
// three act handshake. This function creates to internal cipherState
// instances: one which is used to encrypt messages from the initiator to the
// responder, and another which is used to encrypt message for the opposite
// direction.
func (b *Machine) split() {
	var (
		empty   []byte
		sendKey [32]byte
		recvKey [32]byte
	)

	h := hkdf.New(sha256.New, empty, b.chainingKey[:], empty)

	// If we're the initiator the first 32 bytes are used to encrypt our
	// messages and the second 32-bytes to decrypt their messages. For the
	// responder the opposite is true.
	if b.initiator {
		h.Read(sendKey[:])
		b.sendCipher = cipherState{}
		b.sendCipher.InitializeKeyWithSalt(b.chainingKey, sendKey)

		h.Read(recvKey[:])
		b.recvCipher = cipherState{}
		b.recvCipher.InitializeKeyWithSalt(b.chainingKey, recvKey)
	} else {
		h.Read(recvKey[:])
		b.recvCipher = cipherState{}
		b.recvCipher.InitializeKeyWithSalt(b.chainingKey, recvKey)

		h.Read(sendKey[:])
		b.sendCipher = cipherState{}
		b.sendCipher.InitializeKeyWithSalt(b.chainingKey, sendKey)
	}
}

// WriteMessage writes the next message p to the passed io.Writer. The
// ciphertext of the message is pre-pended with an encrypt+auth'd length which
// must be used as the AD to the AEAD construction when being decrypted by the
// other side.
func (b *Machine) WriteMessage(w io.Writer, p []byte) error {
	// The total length of each message payload including the MAC size
	// payload exceed the largest number encodable within a 16-bit unsigned
	// integer.
	if len(p) > math.MaxUint16 {
		return ErrMaxMessageLengthExceeded
	}

	// The full length of the packet is only the packet length, and does
	// NOT include the MAC.
	fullLength := uint16(len(p))

	var pktLen [2]byte
	binary.BigEndian.PutUint16(pktLen[:], fullLength)

	// First, write out the encrypted+MAC'd length prefix for the packet.
	cipherLen := b.sendCipher.Encrypt(nil, nil, pktLen[:])
	if _, err := w.Write(cipherLen); err != nil {
		return err
	}

	// Finally, write out the encrypted packet itself. We only write out a
	// single packet, as any fragmentation should have taken place at a
	// higher level.
	cipherText := b.sendCipher.Encrypt(nil, nil, p)
	_, err := w.Write(cipherText)
	return err
}

// ReadMessage attempts to read the next message from the passed io.Reader. In
// the case of an authentication error, a non-nil error is returned.
func (b *Machine) ReadMessage(r io.Reader) ([]byte, error) {
	var cipherLen [lengthHeaderSize + macSize]byte
	if _, err := io.ReadFull(r, cipherLen[:]); err != nil {
		return nil, err
	}

	// Attempt to decrypt+auth the packet length present in the stream.
	pktLenBytes, err := b.recvCipher.Decrypt(nil, nil, cipherLen[:])
	if err != nil {
		return nil, err
	}

	// Next, using the length read from the packet header, read the
	// encrypted packet itself.
	var cipherText [math.MaxUint16 + macSize]byte
	pktLen := uint32(binary.BigEndian.Uint16(pktLenBytes)) + macSize
	if _, err := io.ReadFull(r, cipherText[:pktLen]); err != nil {
		return nil, err
	}

	// TODO(roasbeef): modify to let pass in slice
	return b.recvCipher.Decrypt(nil, nil, cipherText[:pktLen])
}


text:
using namespace angle;

namespace
{
constexpr uint32_t kSize        = 32;
constexpr char kExtensionName[] = "GL_ANGLE_get_image";
constexpr uint32_t kSmallSize   = 2;
constexpr uint8_t kUNormZero    = 0x00;
constexpr uint8_t kUNormHalf    = 0x7F;
constexpr uint8_t kUNormFull    = 0xFF;

class GetImageTest : public ANGLETest
{
  public:
    GetImageTest()
    {
        setWindowWidth(kSize);
        setWindowHeight(kSize);
        setConfigRedBits(8);
        setConfigGreenBits(8);
        setConfigBlueBits(8);
        setConfigAlphaBits(8);
    }
};

class GetImageTestNoExtensions : public ANGLETest
{
  public:
    GetImageTestNoExtensions() { setExtensionsEnabled(false); }
};

GLTexture InitTextureWithFormatAndSize(GLenum format, uint32_t size, void *pixelData)
{
    GLTexture tex;
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D(GL_TEXTURE_2D, 0, format, size, size, 0, format, GL_UNSIGNED_BYTE, pixelData);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    return tex;
}

GLTexture InitTextureWithSize(uint32_t size, void *pixelData)
{
    // Create a simple texture.
    GLTexture tex;
    glBindTexture(GL_TEXTURE_2D, tex);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, size, size, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixelData);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    return tex;
}

GLTexture InitSimpleTexture()
{
    std::vector<GLColor> pixelData(kSize * kSize, GLColor::red);
    return InitTextureWithSize(kSize, pixelData.data());
}

GLRenderbuffer InitRenderbufferWithSize(uint32_t size)
{
    // Create a simple renderbuffer.
    GLRenderbuffer renderbuf;
    glBindRenderbuffer(GL_RENDERBUFFER, renderbuf);
    glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA4, size, size);
    return renderbuf;
}

GLRenderbuffer InitSimpleRenderbuffer()
{
    return InitRenderbufferWithSize(kSize);
}

// Test validation for the extension functions.
TEST_P(GetImageTest, NegativeAPI)
{
    // Verify the extension is enabled.
    ASSERT_TRUE(IsGLExtensionEnabled(kExtensionName));

    // Draw once with simple texture.
    GLTexture tex = InitSimpleTexture();
    ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Texture2D(), essl1_shaders::fs::Texture2D());
    drawQuad(program, essl1_shaders::PositionAttrib(), 0.5, 1.0f, true);
    EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);
    ASSERT_GL_NO_ERROR();

    // Pack pixels tightly.
    glPixelStorei(GL_PACK_ALIGNMENT, 1);

    // Verify GetTexImage can work with correct parameters.
    std::vector<GLColor> buffer(kSize * kSize);
    glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_NO_ERROR();

    // Test invalid texture target.
    glGetTexImageANGLE(GL_TEXTURE_CUBE_MAP, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_ENUM);

    // Test invalid texture level.
    glGetTexImageANGLE(GL_TEXTURE_2D, -1, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_VALUE);
    glGetTexImageANGLE(GL_TEXTURE_2D, 2000, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_VALUE);

    // Test invalid format and type.
    glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_NONE, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_ENUM);
    glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_RGBA, GL_NONE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_ENUM);

    // Create a simple renderbuffer.
    GLRenderbuffer renderbuf = InitSimpleRenderbuffer();
    ASSERT_GL_NO_ERROR();

    // Verify GetRenderbufferImage can work with correct parameters.
    glGetRenderbufferImageANGLE(GL_RENDERBUFFER, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_NO_ERROR();

    // Test invalid renderbuffer target.
    glGetRenderbufferImageANGLE(GL_TEXTURE_2D, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_ENUM);

    // Test invalid renderbuffer format/type.
    glGetRenderbufferImageANGLE(GL_RENDERBUFFER, GL_NONE, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_ENUM);
    glGetRenderbufferImageANGLE(GL_RENDERBUFFER, GL_RGBA, GL_NONE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_ENUM);

    // Pack buffer tests. Requires ES 3+ or extension.
    if (getClientMajorVersion() >= 3 || IsGLExtensionEnabled("GL_NV_pixel_buffer_object"))
    {
        // Test valid pack buffer.
        GLBuffer packBuffer;
        glBindBuffer(GL_PIXEL_PACK_BUFFER, packBuffer);
        glBufferData(GL_PIXEL_PACK_BUFFER, kSize * kSize * sizeof(GLColor), nullptr,
                     GL_STATIC_DRAW);
        glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
        EXPECT_GL_ERROR(GL_INVALID_OPERATION);
        glGetRenderbufferImageANGLE(GL_RENDERBUFFER, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
        EXPECT_GL_ERROR(GL_INVALID_OPERATION);

        // Test too small pack buffer.
        glBufferData(GL_PIXEL_PACK_BUFFER, kSize, nullptr, GL_STATIC_DRAW);
        glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
        EXPECT_GL_ERROR(GL_INVALID_OPERATION);
        glGetRenderbufferImageANGLE(GL_RENDERBUFFER, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
        EXPECT_GL_ERROR(GL_INVALID_OPERATION);
    }
}

// Simple test for GetTexImage
TEST_P(GetImageTest, GetTexImage)
{
    // Verify the extension is enabled.
    ASSERT_TRUE(IsGLExtensionEnabled(kExtensionName));

    constexpr uint32_t kSmallSize     = 2;
    std::vector<GLColor> expectedData = {GLColor::red, GLColor::blue, GLColor::green,
                                         GLColor::yellow};

    glViewport(0, 0, kSmallSize, kSmallSize);

    // Draw once with simple texture.
    GLTexture tex = InitTextureWithSize(kSmallSize, expectedData.data());
    ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Texture2D(), essl1_shaders::fs::Texture2D());
    drawQuad(program, essl1_shaders::PositionAttrib(), 0.5, 1.0f, true);
    EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);
    ASSERT_GL_NO_ERROR();

    // Pack pixels tightly.
    glPixelStorei(GL_PACK_ALIGNMENT, 1);

    // Verify GetImage.
    std::vector<GLColor> actualData(kSmallSize * kSmallSize);
    glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, actualData.data());
    EXPECT_GL_NO_ERROR();
    EXPECT_EQ(expectedData, actualData);
}

// Simple cube map test for GetTexImage
TEST_P(GetImageTest, CubeMap)
{
    // Verify the extension is enabled.
    ASSERT_TRUE(IsGLExtensionEnabled(kExtensionName));

    const std::array<std::array<GLColor, kSmallSize * kSmallSize>, kCubeFaces.size()> expectedData =
        {{
            {GLColor::red, GLColor::red, GLColor::red, GLColor::red},
            {GLColor::green, GLColor::green, GLColor::green, GLColor::green},
            {GLColor::blue, GLColor::blue, GLColor::blue, GLColor::blue},
            {GLColor::yellow, GLColor::yellow, GLColor::yellow, GLColor::yellow},
            {GLColor::cyan, GLColor::cyan, GLColor::cyan, GLColor::cyan},
            {GLColor::magenta, GLColor::magenta, GLColor::magenta, GLColor::magenta},
        }};

    GLTexture texture;
    glBindTexture(GL_TEXTURE_CUBE_MAP, texture);

    for (size_t faceIndex = 0; faceIndex < kCubeFaces.size(); ++faceIndex)
    {
        glTexImage2D(kCubeFaces[faceIndex], 0, GL_RGBA, kSmallSize, kSmallSize, 0, GL_RGBA,
                     GL_UNSIGNED_BYTE, expectedData[faceIndex].data());
    }
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

    // Pack pixels tightly.
    glPixelStorei(GL_PACK_ALIGNMENT, 1);

    // Verify GetImage.
    std::array<GLColor, kSmallSize *kSmallSize> actualData = {};
    for (size_t faceIndex = 0; faceIndex < kCubeFaces.size(); ++faceIndex)
    {
        glGetTexImageANGLE(kCubeFaces[faceIndex], 0, GL_RGBA, GL_UNSIGNED_BYTE, actualData.data());
        EXPECT_GL_NO_ERROR();
        EXPECT_EQ(expectedData[faceIndex], actualData);
    }
}

// Simple test for GetRenderbufferImage
TEST_P(GetImageTest, GetRenderbufferImage)
{
    // Verify the extension is enabled.
    ASSERT_TRUE(IsGLExtensionEnabled(kExtensionName));

    std::vector<GLColor> expectedData = {GLColor::red, GLColor::blue, GLColor::green,
                                         GLColor::yellow};

    glViewport(0, 0, kSmallSize, kSmallSize);

    // Set up a simple Framebuffer with a Renderbuffer.
    GLRenderbuffer renderbuffer = InitRenderbufferWithSize(kSmallSize);
    GLFramebuffer framebuffer;
    glBindFramebuffer(GL_FRAMEBUFFER, framebuffer);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, renderbuffer);
    ASSERT_GL_FRAMEBUFFER_COMPLETE(GL_FRAMEBUFFER);

    // Draw once with simple texture.
    GLTexture tex = InitTextureWithSize(kSmallSize, expectedData.data());
    ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Texture2D(), essl1_shaders::fs::Texture2D());
    drawQuad(program, essl1_shaders::PositionAttrib(), 0.5, 1.0f, true);
    EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);
    ASSERT_GL_NO_ERROR();

    // Pack pixels tightly.
    glPixelStorei(GL_PACK_ALIGNMENT, 1);

    // Verify GetImage.
    std::vector<GLColor> actualData(kSmallSize * kSmallSize);
    glGetRenderbufferImageANGLE(GL_RENDERBUFFER, GL_RGBA, GL_UNSIGNED_BYTE, actualData.data());
    EXPECT_GL_NO_ERROR();
    EXPECT_EQ(expectedData, actualData);
}

// Verifies that the extension enums and entry points are invalid when the extension is disabled.
TEST_P(GetImageTestNoExtensions, EntryPointsInactive)
{
    // Verify the extension is not enabled.
    ASSERT_FALSE(IsGLExtensionEnabled(kExtensionName));

    // Draw once with simple texture.
    GLTexture tex = InitSimpleTexture();
    ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Texture2D(), essl1_shaders::fs::Texture2D());
    drawQuad(program, essl1_shaders::PositionAttrib(), 0.5, 1.0f, true);
    EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor::red);
    ASSERT_GL_NO_ERROR();

    // Query implementation format and type. Should give invalid enum.
    GLint param;
    glGetTexParameteriv(GL_TEXTURE_2D, GL_IMPLEMENTATION_COLOR_READ_FORMAT, &param);
    EXPECT_GL_ERROR(GL_INVALID_ENUM);

    glGetTexParameteriv(GL_TEXTURE_2D, GL_IMPLEMENTATION_COLOR_READ_TYPE, &param);
    EXPECT_GL_ERROR(GL_INVALID_ENUM);

    // Verify calling GetTexImage produces an error.
    std::vector<GLColor> buffer(kSize * kSize, 0);
    glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_OPERATION);

    // Create a simple renderbuffer.
    GLRenderbuffer renderbuf = InitSimpleRenderbuffer();
    ASSERT_GL_NO_ERROR();

    // Query implementation format and type. Should give invalid enum.
    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_IMPLEMENTATION_COLOR_READ_FORMAT, &param);
    EXPECT_GL_ERROR(GL_INVALID_ENUM);

    glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_IMPLEMENTATION_COLOR_READ_TYPE, &param);
    EXPECT_GL_ERROR(GL_INVALID_ENUM);

    // Verify calling GetRenderbufferImage produces an error.
    glGetRenderbufferImageANGLE(GL_RENDERBUFFER, GL_RGBA, GL_UNSIGNED_BYTE, buffer.data());
    EXPECT_GL_ERROR(GL_INVALID_OPERATION);
}

// Test LUMINANCE_ALPHA (non-renderable) format with GetTexImage
TEST_P(GetImageTest, GetTexImageLuminanceAlpha)
{
    // Verify the extension is enabled.
    ASSERT_TRUE(IsGLExtensionEnabled(kExtensionName));

    constexpr GLColorRG kMediumLumAlpha = GLColorRG(kUNormHalf, kUNormHalf);
    std::vector<GLColorRG> expectedData = {kMediumLumAlpha, kMediumLumAlpha, kMediumLumAlpha,
                                           kMediumLumAlpha};

    glViewport(0, 0, kSmallSize, kSmallSize);

    // Set up a simple LUMINANCE_ALPHA texture
    GLTexture tex =
        InitTextureWithFormatAndSize(GL_LUMINANCE_ALPHA, kSmallSize, expectedData.data());

    // Draw once with simple texture.
    ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Texture2D(), essl1_shaders::fs::Texture2D());
    drawQuad(program, essl1_shaders::PositionAttrib(), 0.5, 1.0f, true);
    EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor(kUNormHalf, kUNormHalf, kUNormHalf, kUNormHalf));
    ASSERT_GL_NO_ERROR();

    // Pack pixels tightly.
    glPixelStorei(GL_PACK_ALIGNMENT, 1);

    // Verify GetImage.
    std::vector<GLColorRG> actualData(kSmallSize * kSmallSize);
    glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, actualData.data());
    EXPECT_GL_NO_ERROR();
    for (uint32_t i = 0; i < kSmallSize * kSmallSize; ++i)
    {
        EXPECT_EQ(expectedData[i].R, actualData[i].R);
        EXPECT_EQ(expectedData[i].G, actualData[i].G);
    }
}

// Test LUMINANCE (non-renderable) format with GetTexImage
TEST_P(GetImageTest, GetTexImageLuminance)
{
    // Verify the extension is enabled.
    ASSERT_TRUE(IsGLExtensionEnabled(kExtensionName));

    constexpr GLColorR kMediumLuminance = GLColorR(kUNormHalf);
    std::vector<GLColorR> expectedData  = {kMediumLuminance, kMediumLuminance, kMediumLuminance,
                                          kMediumLuminance};

    glViewport(0, 0, kSmallSize, kSmallSize);

    // Set up a simple LUMINANCE texture
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    GLTexture tex = InitTextureWithFormatAndSize(GL_LUMINANCE, kSmallSize, expectedData.data());

    // Draw once with simple texture.
    ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Texture2D(), essl1_shaders::fs::Texture2D());
    drawQuad(program, essl1_shaders::PositionAttrib(), 0.5, 1.0f, true);
    EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor(kUNormHalf, kUNormHalf, kUNormHalf, kUNormFull));
    ASSERT_GL_NO_ERROR();

    // Pack pixels tightly.
    glPixelStorei(GL_PACK_ALIGNMENT, 1);

    // Verify GetImage.
    std::vector<GLColorR> actualData(kSmallSize * kSmallSize);
    glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, actualData.data());
    EXPECT_GL_NO_ERROR();
    for (uint32_t i = 0; i < kSmallSize * kSmallSize; ++i)
    {
        EXPECT_EQ(expectedData[i].R, actualData[i].R);
    }
}

// Test ALPHA (non-renderable) format with GetTexImage
TEST_P(GetImageTest, GetTexImageAlpha)
{
    // Verify the extension is enabled.
    ASSERT_TRUE(IsGLExtensionEnabled(kExtensionName));

    constexpr GLColorR kMediumAlpha    = GLColorR(kUNormHalf);
    std::vector<GLColorR> expectedData = {kMediumAlpha, kMediumAlpha, kMediumAlpha, kMediumAlpha};

    glViewport(0, 0, kSmallSize, kSmallSize);

    // Set up a simple ALPHA texture
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    GLTexture tex = InitTextureWithFormatAndSize(GL_ALPHA, kSmallSize, expectedData.data());

    // Draw once with simple texture
    ANGLE_GL_PROGRAM(program, essl1_shaders::vs::Texture2D(), essl1_shaders::fs::Texture2D());
    drawQuad(program, essl1_shaders::PositionAttrib(), 0.5, 1.0f, true);
    EXPECT_PIXEL_COLOR_EQ(0, 0, GLColor(kUNormZero, kUNormZero, kUNormZero, kUNormHalf));
    ASSERT_GL_NO_ERROR();

    // Pack pixels tightly.
    glPixelStorei(GL_PACK_ALIGNMENT, 1);

    // Verify we get back the correct pixels from GetTexImage
    std::vector<GLColorR> actualData(kSmallSize * kSmallSize);
    glGetTexImageANGLE(GL_TEXTURE_2D, 0, GL_ALPHA, GL_UNSIGNED_BYTE, actualData.data());
    EXPECT_GL_NO_ERROR();
    for (uint32_t i = 0; i < kSmallSize * kSmallSize; ++i)
    {
        EXPECT_EQ(expectedData[i].R, actualData[i].R);
    }
}

GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GetImageTest);
ANGLE_INSTANTIATE_TEST(GetImageTest, ES2_VULKAN(), ES3_VULKAN());

GTEST_ALLOW_UNINSTANTIATED_PARAMETERIZED_TEST(GetImageTestNoExtensions);
ANGLE_INSTANTIATE_TEST(GetImageTestNoExtensions, ES2_VULKAN(), ES3_VULKAN());

}  // namespace

redpajama_set_name: RedPajamaGithub


text:
class CreateMicroposts < ActiveRecord::Migration
  def change
    create_table :microposts do |t|
      t.string :content
      t.references :user, index: true

      t.timestamps
    end
  end
end


text:
A javascript library for formatting and manipulating numbers.

[Website and documentation](http://foretagsplatsen.github.io/numbro)

# Travis Build Status

Master [![Build Status](https://travis-ci.org/foretagsplatsen/numbro.svg?branch=master)](https://travis-ci.org/foretagsplatsen/numbro)

Develop [![Build Status](https://travis-ci.org/foretagsplatsen/numbro.svg?branch=develop)](https://travis-ci.org/foretagsplatsen/numbro)

# NPM

[![NPM](https://nodei.co/npm/numbro.png?downloads=true)](https://nodei.co/npm/numbro/)

# Contributing

Please submit all pull requests to the `develop` branch.

1. Fork the library

2. [Install grunt](http://gruntjs.com/getting-started#installing-the-cli)

3. Run `npm install` to install dependencies

4. Add your tests to the files in `/tests`

5. To test your tests, run `grunt test`

6. When all your tests are passing, submit a pull request to the `develop` branch.

### Languages

Languages names follows the Microsoft culture name convention as found
[here](https://msdn.microsoft.com/en-us/library/ee825488.aspx). If Microsoft does not have a code
for the country/locale combination, use the format `lang-locale` where the language code is a 2
letter abbreviation from the list of [ISO 639-1 language
codes](http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) and the `localecode` is from the list
of [ISO 3166-1 country codes](http://en.wikipedia.org/wiki/ISO_3166-1)

### Language translations will not be merged without unit tests.

See [the english unit tests](https://github.com/foretagsplatsen/numbro/blob/master/tests/languages/en-GB.js) for an example.

# Changelog

See [CHANGELOG.md](CHANGELOG.md).

# Acknowlegements

`numbro` is forked from [Adam Draper](https://github.com/adamwdraper)'s project
[Numeral.js](http://numeraljs.com/), which was in turn inspired by and heavily borrowed from
[Moment.js](http://momentjs.com).

# License

Copyright © 2014 Adam Draper

Copyright © 2015 Företagsplatsen AB

---

Distributed under the MIT license. If you want to know more, see the `LICENSE` file.

The original license file for `Numeral.js` can be found in `LICENSE-Numeraljs`


text:
// Copyright 2014 The Cloud Input Tools Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * @fileoverview Provides common operation of dom for input tools.
 */

goog.provide('i18n.input.common.FocusHandler');

goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.events.BrowserEvent');
goog.require('goog.events.EventHandler');
goog.require('goog.events.EventTarget');
goog.require('goog.object');
goog.require('goog.uri.utils');
goog.require('goog.userAgent');
goog.require('i18n.input.api.DocumentReplacer');
goog.require('i18n.input.common.GlobalSettings');
goog.require('i18n.input.common.dom');

/**
 * Tracks focus switch between elements of page, include iframe. If focus
 * causes current active element changing then fire an events. Suggests
 * pass current active element document.
 *
 * @param {!Document|!Array.<!Document>} doc The document or array of documents
 *     to listen on.
 * @constructor
 * @extends {goog.events.EventTarget}
 */
i18n.input.common.FocusHandler = function(doc) {
  goog.base(this);

  /**
   * Mark the visited documents flag.
   *
   * @type {!Object.<number, boolean>}
   * @private
   */
  this.visitedDocuments_ = {};

  /**
   * The main document.
   *
   * @type {!Document}
   * @private
   */
  this.mainDocument_ = goog.isArrayLike(doc) ? doc[0] : doc;

  /**
   * The current active element.
   *
   * @type {?Element}
   * @private
   */
  this.currentActiveElement_ = null;

  /**
   * The event handler.
   *
   * @type {goog.events.EventHandler}
   * @private
   */
  this.eventHandler_ = new goog.events.EventHandler(this);

  this.addFocusHandler_(doc);
};
goog.inherits(i18n.input.common.FocusHandler, goog.events.EventTarget);

/**
 * Enum type for the events fired by the focus handler.
 *
 * @enum {string}
 */
i18n.input.common.FocusHandler.EventType = {
  ACTIVE_ELEMENT_CHANGE: 'aec'
};

/**
 * Initializes the focus handler.
 *
 * @param {!Document|!Array.<!Document>} doc The document or array of documents
 *     to listen on.
 * @private
 */
i18n.input.common.FocusHandler.prototype.addFocusHandler_ = function(doc) {
  var docs = /** @type {!Array.<!Document>} */
      (goog.isArrayLike(doc) ? doc : [doc]);

  // In IE we use focusin/focusout and in other browsers we use a capturing
  // listener for focus/blur
  var typeIn = goog.userAgent.IE ? 'focusin' : 'focus';
  var typeOut = goog.userAgent.IE ? 'focusout' : 'blur';

  goog.array.forEach(docs, function(value) {
    var uid = goog.getUid(value);
    if (!this.visitedDocuments_[uid]) {
      this.visitedDocuments_[uid] = true;
      var target = goog.userAgent.WEBKIT ?
          goog.dom.getWindow(value) : value;
      this.eventHandler_.listen(target, typeIn, this.onFocusIn_,
          i18n.input.common.GlobalSettings.canListenInCaptureForIE8);
      this.eventHandler_.listen(target, typeOut, this.onFocusOut_,
          i18n.input.common.GlobalSettings.canListenInCaptureForIE8);
    }
  }, this);
};

/**
 * Handles the focus in event.
 *
 * @param {!goog.events.BrowserEvent} e The event.
 * @private
 */
i18n.input.common.FocusHandler.prototype.onFocusIn_ = function(e) {
  var target = e.target;
  if (target && target != i18n.input.api.DocumentReplacer.getWindow()) {
    if (target.frameElement) {
      target = target.frameElement;
    }
    this.fireEvent_(e, /** @type {!Element} */ (target));
  }
};

/**
 * Handles the focus out event.
 *
 * @param {!goog.events.BrowserEvent} e The event.
 * @private
 */
i18n.input.common.FocusHandler.prototype.onFocusOut_ = function(e) {
  // Browser setting document active element has some latency,
  // so set up time to solve it.

  // In IE, the Event object will be invalid after the event handling has
  // finished. Take a copy of the Event object and create a new BrowserEvent.
  var rawEventCopy = /** @type {Event} */
      (goog.object.clone(e.getBrowserEvent()));
  var wrappedFocusOut = goog.bind(this.onFocusOutInner_,
      this, this.mainDocument_, new goog.events.BrowserEvent(rawEventCopy));
  goog.Timer.callOnce(wrappedFocusOut, 0);
};

/**
 * Handles the focus out event.
 *
 * @param {!Document} currentDocument The document.
 * @param {!goog.events.BrowserEvent} e The event.
 * @private
 */
i18n.input.common.FocusHandler.prototype.onFocusOutInner_ =
    function(currentDocument, e) {
  if (!this.visitedDocuments_) {
    // Avoids this method is called after the focus handler is disposed.
    return;
  }

  // TODO(shuchen): remove the below check for docs apps and investigate the
  // root cause of b/7250478.
  var appName = i18n.input.common.GlobalSettings.ApplicationName;
  if (appName != 'kix' && appName != 'punch' && appName != 'trix' ||
      !goog.userAgent.IE) {
    var domHelper = goog.dom.getDomHelper(currentDocument);
    // If switches from one iframe to another iframe, the activeElement of the
    // parent document won't change, so iterate all the iframes.
    goog.array.forEach(i18n.input.common.dom.getSameDomainDocuments(
        domHelper.getDocument()), function(frameDoc) {
          /** @preserveTry */
          try {
            // In IE and FF3.5, some iframe is not allowed to access.
            // It throws exception when access the iframe property.
            this.addFocusHandler_(frameDoc);
          } catch (ex) {}
        }, this);
  }

  // Gets the current active element.
  var activeElement = goog.dom.getActiveElement(currentDocument);
  if (activeElement) {
    var parentActiveElement = activeElement;

    // The current active element is iframe. Add focus event on its inner
    // document.
    var tagName = activeElement.tagName;
    while (tagName && (tagName == goog.dom.TagName.IFRAME ||
            tagName == goog.dom.TagName.FRAME)) {
      if (activeElement.src &&
          !goog.uri.utils.haveSameDomain(activeElement.src,
              window.location.href)) {
        break;
      }
      var innerDocument = goog.dom.getFrameContentDocument(activeElement);
      if (!innerDocument) {
        break;
      }
      this.addFocusHandler_(innerDocument);

      var innerDocumentActiveElement = goog.dom.getActiveElement(innerDocument);
      if (!innerDocumentActiveElement) {
        break;
      }

      parentActiveElement = activeElement;
      activeElement = innerDocumentActiveElement;
      tagName = activeElement.tagName;
      if (tagName && tagName.toUpperCase() == goog.dom.TagName.BODY) {
        // Resets active element to parent iframe.
        activeElement = parentActiveElement;
        break;
      }
    }
    this.fireEvent_(e, activeElement);
  }
};

/**
 * Fires active element change event if current active element changes.
 *
 * @param {!goog.events.BrowserEvent} e The browser event.
 * @param {Element} activeElement The active element.
 * @private
 */
i18n.input.common.FocusHandler.prototype.fireEvent_ =
    function(e, activeElement) {
  if (activeElement != this.currentActiveElement_) {
    // Resets the current active element.
    this.currentActiveElement_ = activeElement;
    // Fires the active element change event.
    var be = e.getBrowserEvent();
    var event = new goog.events.BrowserEvent(be);
    event.target = activeElement;
    event.type = i18n.input.common.FocusHandler.EventType.ACTIVE_ELEMENT_CHANGE;

    this.dispatchEvent(event);
  }
};

/** @override */
i18n.input.common.FocusHandler.prototype.disposeInternal = function() {
  goog.base(this, 'disposeInternal');
  // In Docs, some iframes' domains may be changed during runtime.
  // To avoid different domain exception, add try to catch it.
  /** @preserveTry */
  try {
    goog.dispose(this.eventHandler_);
  } catch (e) {}
  delete this.visitedDocuments_;
  delete this.currentActiveElement_;
};


text:
package com.shen.mymvparm.mvp.ui.adapter;

import android.view.View;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.shen.mymvparm.R;
import com.shen.mymvparm.app.utils.Utils;
import com.shen.mymvparm.mvp.model.entity.Doc;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;

public class DocAdapter extends BaseQuickAdapter<Doc, BaseViewHolder> {
    public DocAdapter(ArrayList<Doc> list) {
        super(R.layout.adapter_note, list);
    }

    @Override
    protected BaseViewHolder createBaseViewHolder(View view) {
        AutoUtils.autoSize(view);
        return super.createBaseViewHolder(view);
    }

    @Override
    public int getItemCount() {
        return super.getItemCount();
    }

    @Override
    protected void convert(BaseViewHolder helper, Doc item) {
        helper.setText(R.id.tv_title, item.getTitle())
                .setText(R.id.tv_content, item.getContent())
                .setText(R.id.tv_modify, Utils.getTime(mContext,Long.parseLong(item.getLastModify())));

    }
}


text:
layout: post
permalink: /fiddle-resources
title: "Ultimate Collection of Fiddle Resources"
category: "On the Web"
tags: fiddle jsfiddle refiddle sqlfiddle sql javascript regex
---
### Why Fiddle?

We are heavily engaged in the Open-Source and Q/A community which means we love to share code. Whether it is sharing a demo or assisting with the debugging of code, we need a way to share visually and collaborate logically. Fiddle resources provided just that. Below, I have compiled a list of Fiddle Resources which come with much appreciation and untold amounts of usefulness.

## Regex Fiddling

[reFiddle](http://www.refiddle.com) - A ReGex Fiddle reFiddle is a great resource for testing regular expressions.

## SQL Fiddling

[sqlFiddle](http://www.sqlfiddle.com) - An SQL Fiddle sqlFiddle is a good way to build schema, test queries and more for SQL services.

## Javascript Fiddling

[jsFiddle](http://www.jsfiddle.net) - A JavaScript Fiddle jsFiddle is an awesome resource for testing javascript code. As more are discovered, I will update the above list.


text:
package types

import (
	"reflect"
)

const (
	Version = 1
)

type Config struct {
	Version  int      `json:"ignitionVersion"`
	Storage  Storage  `json:"storage,omitempty"`
	Systemd  Systemd  `json:"systemd,omitempty"`
	Networkd Networkd `json:"networkd,omitempty"`
	Passwd   Passwd   `json:"passwd,omitempty"`
}

func (c Config) AssertValid() error {
	return assertStructValid(reflect.ValueOf(c))
}

func assertValid(vObj reflect.Value) error {
	if !vObj.IsValid() {
		return nil
	}

	if obj, ok := vObj.Interface().(interface {
		AssertValid() error
	}); ok && !(vObj.Kind() == reflect.Ptr && vObj.IsNil()) {
		if err := obj.AssertValid(); err != nil {
			return err
		}
	}

	switch vObj.Kind() {
	case reflect.Ptr:
		return assertValid(vObj.Elem())
	case reflect.Struct:
		return assertStructValid(vObj)
	case reflect.Slice:
		for i := 0; i < vObj.Len(); i++ {
			if err := assertValid(vObj.Index(i)); err != nil {
				return err
			}
		}
	}

	return nil
}

func assertStructValid(vObj reflect.Value) error {
	for i := 0; i < vObj.Type().NumField(); i++ {
		if err := assertValid(vObj.Field(i)); err != nil {
			return err
		}
	}
	return nil
}


text:
import { FC, memo } from 'react'

import type { TProps as TArticleStateBadgeProps } from './index'

import { AS_TYPE } from '@/constant'

import {
  Wrapper,
  BugWrapper,
  QuestionWrapper,
  LockWrapper,
} from './styles/label'

type TProps = Pick<
  TArticleStateBadgeProps,
  'type' | 'kanbanLayout' | 'articleInfoLayout'
>

const Label: FC<TProps> = ({ type, kanbanLayout, articleInfoLayout }) => {
  switch (type) {
    case AS_TYPE.FEATURE: {
      return <Wrapper kanbanLayout={kanbanLayout}>功能建议</Wrapper>
    }

    case AS_TYPE.BUG: {
      return <BugWrapper kanbanLayout={kanbanLayout}>Bug/吐槽</BugWrapper>
    }

    case AS_TYPE.QUESTION: {
      return (
        <QuestionWrapper articleInfoLayout={articleInfoLayout}>
          已解决
        </QuestionWrapper>
      )
    }

    case AS_TYPE.LOCK: {
      return (
        <LockWrapper articleInfoLayout={articleInfoLayout}>
          重复问题
        </LockWrapper>
      )
    }

    default:
      return null
  }
}

export default memo(Label)


text:
import Sequelize from 'sequelize';

let Choice;
export default function (SequelizeInst) {
    if (!Choice) {
        Choice = SequelizeInst.define('choice', {
            value: { type: Sequelize.STRING },
        });
    }
    return Choice;
}


text:
package marketplacecommerceanalytics_test

import (
	"context"
	"testing"
	"time"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/aws/awserr"
	"github.com/aws/aws-sdk-go/aws/request"
	"github.com/aws/aws-sdk-go/awstesting/integration"
	"github.com/aws/aws-sdk-go/private/protocol"
	"github.com/aws/aws-sdk-go/service/marketplacecommerceanalytics"
)

var _ aws.Config
var _ awserr.Error
var _ request.Request

func TestInteg_00_GenerateDataSet(t *testing.T) {
	ctx, cancelFn := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancelFn()

	sess := integration.SessionWithDefaultRegion("us-east-1")
	svc := marketplacecommerceanalytics.New(sess)
	params := &marketplacecommerceanalytics.GenerateDataSetInput{
		DataSetPublicationDate: func() *time.Time {
			v, err := protocol.ParseTime("unixTimestamp", "0.000000")
			if err != nil {
				panic(err)
			}
			return &v
		}(),
		DataSetType:             aws.String("fake-type"),
		DestinationS3BucketName: aws.String("fake-bucket"),
		RoleNameArn:             aws.String("fake-arn"),
		SnsTopicArn:             aws.String("fake-arn"),
	}
	_, err := svc.GenerateDataSetWithContext(ctx, params, func(r *request.Request) {
		r.Handlers.Validate.RemoveByName("core.ValidateParametersHandler")
	})
	if err == nil {
		t.Fatalf("expect request to fail")
	}
	aerr, ok := err.(awserr.RequestFailure)
	if !ok {
		t.Fatalf("expect awserr, was %T", err)
	}
	if len(aerr.Code()) == 0 {
		t.Errorf("expect non-empty error code")
	}
	if v := aerr.Code(); v == request.ErrCodeSerialization {
		t.Errorf("expect API error code got serialization failure")
	}
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
J. gen. appl. Microbiol. , Tokyo 40(5): 405 (1994)

#### Original name
Hemispora coremiformis M. Moore

### Remarks
null


text:
<!doctype html>
<title>Set cookie from location.hash</title>
<script>
if (location.hash)
    document.cookie = decodeURIComponent(location.hash.substr(1))+'=yes;path=/;max-age=15';
</script>


text:
<?php

/**
 * This file is part of Bldr.io
 *
 * (c) Aaron Scherer <aequasi@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE
 */

namespace Bldr\Block\Core\Command;

use Bldr\Application;
use Bldr\Block\Core\Service\Builder;
use Bldr\Command\AbstractCommand;
use Bldr\Definition\JobDefinition;
use Bldr\Definition\TaskDefinition;
use Bldr\Exception\BldrException;
use Bldr\Registry\JobRegistry;
use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Input\InputArgument;

/**
 * @author Aaron Scherer <aequasi@gmail.com>
 */
class RunCommand extends AbstractCommand
{
    /**
     * @var Builder $builder
     */
    private $builder;

    /**
     * @var JobRegistry $registry
     */
    private $registry;

    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        $this->setName('run')
            ->setDescription("Runs the project for the directory you are in. Must contain a config file.")
            ->addArgument('profile', InputArgument::OPTIONAL, 'Profile to run')
            ->setHelp(
                <<<EOF

The <info>%command.name%</info> builds the current project, using the config file in the root directory.

To use:

    <info>$ bldr %command.name% <profile_name></info>

EOF
            )
        ;
    }

    /**
     * {@inheritDoc}
     */
    protected function doExecute()
    {
        $this->registry = $this->container->get('bldr.registry.job');
        $this->builder  = $this->container->get('bldr.builder');
        $profileName    = $this->input->getArgument('profile') ?: 'default';

        $this->output->writeln(["\n", Application::$logo, "\n"]);

        $profile = $this->getProfile($profileName);

        $projectFormat = [];

        if ($this->container->getParameter('name') !== '') {
            $projectFormat[] = sprintf("Building the '%s' project", $this->container->getParameter('name'));
        }
        if ($this->container->getParameter('description') !== '') {
            $projectFormat[] = sprintf(" - %s - ", $this->container->getParameter('description'));
        }

        $profileFormat = [sprintf("Using the '%s' profile", $profileName)];
        if (!empty($profile['description'])) {
            $profileFormat[] = sprintf(" - %s - ", $profile['description']);
        }

        $this->output->writeln(
            [
                "",
                $projectFormat === [] ? '' : $this->formatBlock($projectFormat, 'blue', 'black'),
                "",
                $this->formatBlock($profileFormat, 'blue', 'black'),
                ""
            ]
        );

        $this->fetchJobs($profile);
        $this->builder->runJobs($this->registry);

        $this->output->writeln(['', $this->formatBlock('Build Success!', 'green', 'white', true), '']);
    }

    /**
     * @param string|array $output
     * @param string       $background
     * @param string       $foreground
     *
     * @return string
     */
    private function formatBlock($output, $background, $foreground, $large = false)
    {
        /** @var FormatterHelper $formatter */
        $formatter = $this->getApplication()->getHelperSet()->get('formatter');

        return $formatter->formatBlock($output, "bg={$background};fg={$foreground}", $large);
    }

    /**
     * @param array $profile
     */
    private function fetchJobs(array $profile)
    {
        if (!empty($profile['uses']) && !empty($profile['uses']['before'])) {
            foreach ($profile['uses']['before'] as $name) {
                $this->fetchJobs($this->getProfile($name));
            }
        }

        $this->buildJobs($profile['jobs']);

        if (!empty($profile['uses']) && !empty($profile['uses']['after'])) {
            foreach ($profile['uses']['after'] as $name) {
                $this->fetchJobs($this->getProfile($name));
            }
        }
    }

    /**
     * @param string[] $names
     *
     * @throws \Exception
     * @return array
     */
    private function buildJobs(array $names)
    {
        $jobs = $this->container->getParameter('jobs');
        foreach ($names as $name) {
            if (!array_key_exists($name, $jobs)) {
                throw new BldrException(
                    sprintf(
                        "Job `%s` does not exist. Found: %s",
                        $name,
                        implode(', ', array_keys($jobs))
                    )
                );
            }

            $jobInfo     = $jobs[$name];
            $description = isset($jobInfo['description']) ? $jobInfo['description'] : "";
            $job         = new JobDefinition($name, $description);

            foreach ($jobInfo['tasks'] as $taskInfo) {
                $task = new TaskDefinition($taskInfo['type']);
                $task->setContinueOnError(isset($taskInfo['continueOnError']) ? $taskInfo['continueOnError'] : false);
                unset($taskInfo['type'], $taskInfo['continueOnError']);
                $task->setParameters($taskInfo);
                $job->addTask($task);
            }

            $this->registry->addJob($job);
        }
    }

    /**
     * @param $name
     *
     * @return mixed
     * @throws \Exception
     */
    private function getProfile($name)
    {
        $profiles = $this->container->getParameter('profiles');
        if (!array_key_exists($name, $profiles)) {
            throw new \Exception(
                sprintf(
                    'There is no profile with the name \'%s\', expecting: (%s)',
                    $name,
                    implode(', ', array_keys($profiles))
                )
            );
        }

        return $profiles[$name];
    }
}


text:
/**
 * This is a thrid party component created by Tony Li
 *
 * all right reserved by @author Tony Li
 *
 */
import React from 'react';
import ReactDOM from 'react-dom';
import ReactDrawer from '../src/ReactDrawer';

class Main extends React.Component {
  constructor() {
    super();
    this.state = {
      open: false,
      position: 'right',
      noOverlay: false
    };
    this.toggleDrawer = this.toggleDrawer.bind(this);
    this.closeDrawer = this.closeDrawer.bind(this);
    this.onDrawerClose = this.onDrawerClose.bind(this);
    this.setPosition = this.setPosition.bind(this);
    this.setNoOverlay = this.setNoOverlay.bind(this);
  }
  setPosition(e) {
    this.setState({position: e.target.value});
  }
  setNoOverlay(e) {
    this.setState({noOverlay: e.target.checked});
  }
  toggleDrawer() {
    this.setState({open: !this.state.open});
  }
  closeDrawer() {
    this.setState({open: false});
  }
  onDrawerClose() {
    this.setState({open: false});
  }
  render() {
    return (

React Drawer configuration

            Position
            <select value={this.state.position} onChange={this.setPosition}>
              <option value="top">top</option>
              <option value="bottom">bottom</option>
              <option value="left">left</option>
              <option value="right">right</option>
            </select>

            <input type="checkbox"
              checked={this.state.noOverlay}
              onChange={this.setNoOverlay}
            />
            No overlay
            (The overlay lets you close the drawer on click)

          <button
            style={{margin: 20}}
            onClick={this.toggleDrawer}
            disabled={this.state.open && !this.state.noOverlay}
            >
            {!this.state.open ? show drawer: close drawer}
          </button>

        <ReactDrawer
          open={this.state.open}
          position={this.state.position}
          onClose={this.onDrawerClose}
          noOverlay={this.state.noOverlay}>

What a nice drawer !

        </ReactDrawer>

    );
  }
}

ReactDOM.render(, document.getElementById('app'));


text:
@echo off

rem Author:   Andrey Dibrov (andry at inbox dot ru)

rem Description:
rem   Script to copy/archive the build stage directories set of a project build
rem   output (basically the last build stage output of previous project in a
rem   build pipeline) into a stage of calling project.
rem   The copy performs file filtering and archiving by pattern.

rem Examples:
rem 1. call xcopy_archive_to_stagein_all_dirs.bat "../.." ^
rem    "%%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.PDB_DIR%%" "%%PROJECT_STAGE_POSTBUILD_ROOT.PDB_DIR%%" ^
rem    "%%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.LIB_DIR%%" "%%PROJECT_STAGE_POSTBUILD_ROOT.LIB_DIR%%" ^
rem    "%%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.GEN_DIR%%" "%%PROJECT_STAGE_POSTBUILD_ROOT.GEN_DIR%%" ^
rem    "%%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.VAR_DIR%%" "%%PROJECT_STAGE_POSTBUILD_ROOT.VAR_DIR%%" || exit /b

setlocal

set "?~dp0=%~dp0"

set "ARCHIVE_COPY_FROM_OFFSET=%~1"
shift

set "PROJECT_PDB_ROOT=%~1"
set "PROJECT_STAGE_PDB_ROOT=%~2"
set "PROJECT_LIB_ROOT=%~3"
set "PROJECT_STAGE_LIB_ROOT=%~4"
set "PROJECT_GEN_ROOT=%~5"
set "PROJECT_STAGE_GEN_ROOT=%~6"
set "PROJECT_VAR_ROOT=%~7"
set "PROJECT_STAGE_VAR_ROOT=%~8"

rem Drop last error level
call;

call "%%?~dp0%%__init__.bat" || exit /b

:PDB_STAGE
if not exist "%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.PDB_DIR%" goto PDB_STAGE_END
call "%%CONTOOLS_BUILD_TOOLS_ROOT%%/xcopy_archive_to_stage.bat" "stage-in project debug information" "stage" ^
  "%%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.PDB_DIR%%" "%%PROJECT_STAGE_PDB_ROOT%%" ^
  "%%ARCHIVE_COPY_FROM_OFFSET%%" ^
  "%%PROJECT_STAGE_PDB_ROOT%%/%%STAGE_IN.PROJECT_NAME%%_pdb_%%STAGE_IN.BUILD_SCM_BRANCH%%_%%STAGE_IN.PROJECT_TYPE%%_%%STAGE_IN.APP_TARGET_NAME%%_v%%STAGE_IN.PRODUCT_VERSION_FILE_SUFFIX%%.pdb.7z" ^
  "*.pdb:*.ilk:*.map" "*.pdb.7z" "/S /Y /H" || exit /b 1

:PDB_STAGE_END

:LIB_STAGE
if not exist "%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.LIB_DIR%" goto LIB_STAGE_END
call "%%CONTOOLS_BUILD_TOOLS_ROOT%%/xcopy_archive_to_stage.bat" "stage-in project library" "stage" ^
  "%%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.LIB_DIR%%" "%%PROJECT_STAGE_LIB_ROOT%%" ^
  "%%ARCHIVE_COPY_FROM_OFFSET%%" ^
  "%%PROJECT_STAGE_LIB_ROOT%%/%%STAGE_IN.PROJECT_NAME%%_lib_%%STAGE_IN.BUILD_SCM_BRANCH%%_%%STAGE_IN.PROJECT_TYPE%%_%%STAGE_IN.APP_TARGET_NAME%%_v%%STAGE_IN.PRODUCT_VERSION_FILE_SUFFIX%%.lib.7z" ^
  "*.lib:*.exp" "*.lib.7z" "/S /Y /H" || exit /b 2

:LIB_STAGE_END

:GEN_STAGE
if not exist "%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.GEN_DIR%" goto GEN_STAGE_END
call "%%CONTOOLS_BUILD_TOOLS_ROOT%%/xcopy_to_stage.bat" "stage-in project generated" "stage" ^
  "%%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.GEN_DIR%%" "%%PROJECT_STAGE_GEN_ROOT%%/%%STAGE_IN.PROJECT_NAME%%" "*.*" "/S /Y /H" || exit /b 3

:GEN_STAGE_END

:VAR_STAGE
if not exist "%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.VAR_DIR%" goto VAR_STAGE_END
call "%%CONTOOLS_BUILD_TOOLS_ROOT%%/xcopy_to_stage.bat" "stage-in project variables" "stage" ^
  "%%STAGE_IN.PROJECT_STAGE_POSTBUILD_ROOT.VAR_DIR%%" "%%PROJECT_STAGE_VAR_ROOT%%/%%STAGE_IN.PROJECT_NAME%%" "*.*" "/S /Y /H" || exit /b 4

:VAR_STAGE_END

exit /b 0


text:
<?php

session_start();

if (isset($_POST["submit"])){

require_once("./connect.php");
//============================================getting value for loggin============================================================//

$name=$_POST["name"]; // email is received as name//
$enc=md5($_POST["password"]);
$pass=substr($enc,0,30);

$_SESSION["query"]=$name;
$_SESSION["query2"]=$pass;

//=========================================Admin login checking===================================================================//

$query="SELECT email FROM admin WHERE email = '$name' AND password='$pass'";

$result=mysql_query($query);
if (!$result){
print(mysql_error());
exit;
}
$array=mysql_fetch_array($result);
$user=$array["email"];

$row=mysql_num_rows($result);
if ($row==1){
$_SESSION["admin"]=$user;
header("Location:../admin/index.php");
exit;}

if ($row !=1){

$name=$_SESSION["query"];
$pass=$_SESSION["query2"];
//================================================CE login checking================================================================//

$query="SELECT email FROM chief_editor WHERE email = '$name' AND password='$pass'";

$result=mysql_query($query);
if (!$result){
print(mysql_error());
exit;
}
$array=mysql_fetch_array($result);

$user=$array["email"];

$row=mysql_num_rows($result);

if ($row==1){
$_SESSION["chief_editor"]=$user;
header("Location:../admin/index.php");

exit;}

}

if ($row !=1){

$name=$_SESSION["query"];
$pass=$_SESSION["query2"];
//===============================data entry login checking=======================================================================//

$query="SELECT email FROM data_entry WHERE email = '$name' AND password='$pass'";

$result=mysql_query($query);
if (!$result){
print(mysql_error());
exit;
}
$array=mysql_fetch_array($result);

$user=$array["email"];
$row=mysql_num_rows($result);

if ($row==1){
$_SESSION["data_entry"]=$user;
header("Location:../admin/index.php");
exit;}

}

if ($row !=1){

$name=$_SESSION["query"];
$pass=$_SESSION["query2"];

//======================================Editors login checking=====================================================================//

$query="SELECT email FROM editors WHERE email = '$name' AND password='$pass'";

$result=mysql_query($query);
if (!$result){
print(mysql_error());
exit;
}
$array=mysql_fetch_array($result);

$user=$array["email"];
$row=mysql_num_rows($result);
if ($row==1){
$_SESSION["editor"]=$user;
header("Location:../admin/index.php");

exit;}

}
if ($row !=1){

$name=$_SESSION["query"];
$pass=$_SESSION["query2"];
//==================================contributors login checking==================================================================//

$query="SELECT email FROM contributors WHERE email = '$name' AND password='$pass'";

$result=mysql_query($query);
if (!$result){
print(mysql_error());
exit;
}
$array=mysql_fetch_array($result);
$user=$array["email"];

$row=mysql_num_rows($result);
if ($row==1){
$_SESSION["contributor"]=$user;
header("Location:../contributor/index.php");

exit;}

}
if ($row !=1){
        echo ('<script type="text/javascript">
				alert("Invalid E-mail or Password")
				window.location= "../login.php"
				</script>');
exit;}

}

/*
history.go(-1)
$key = 'password to (en/de)crypt';
$string = 'string to be encrypted';

$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($encrypted), MCRYPT_MODE_CBC, md5(md5($key))), "\0");

var_dump($encrypted);
var_dump($decrypted);
*/
?>


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
/*
 * This code was generated by https://github.com/googleapis/google-api-java-client-services/
 * Modify at your own risk.
 */

package com.google.api.services.videointelligence.v1p2beta1.model;

/**
 * Celebrity definition.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the Cloud Video Intelligence API. For a detailed
 * explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class GoogleCloudVideointelligenceV1p3beta1Celebrity extends com.google.api.client.json.GenericJson {

  /**
   * Textual description of additional information about the celebrity, if applicable.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String description;

  /**
   * The celebrity name.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String displayName;

  /**
   * The resource name of the celebrity. Have the format `video-intelligence/kg-mid` indicates a
   * celebrity from preloaded gallery. kg-mid is the id in Google knowledge graph, which is unique
   * for the celebrity.
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String name;

  /**
   * Textual description of additional information about the celebrity, if applicable.
   * @return value or {@code null} for none
   */
  public java.lang.String getDescription() {
    return description;
  }

  /**
   * Textual description of additional information about the celebrity, if applicable.
   * @param description description or {@code null} for none
   */
  public GoogleCloudVideointelligenceV1p3beta1Celebrity setDescription(java.lang.String description) {
    this.description = description;
    return this;
  }

  /**
   * The celebrity name.
   * @return value or {@code null} for none
   */
  public java.lang.String getDisplayName() {
    return displayName;
  }

  /**
   * The celebrity name.
   * @param displayName displayName or {@code null} for none
   */
  public GoogleCloudVideointelligenceV1p3beta1Celebrity setDisplayName(java.lang.String displayName) {
    this.displayName = displayName;
    return this;
  }

  /**
   * The resource name of the celebrity. Have the format `video-intelligence/kg-mid` indicates a
   * celebrity from preloaded gallery. kg-mid is the id in Google knowledge graph, which is unique
   * for the celebrity.
   * @return value or {@code null} for none
   */
  public java.lang.String getName() {
    return name;
  }

  /**
   * The resource name of the celebrity. Have the format `video-intelligence/kg-mid` indicates a
   * celebrity from preloaded gallery. kg-mid is the id in Google knowledge graph, which is unique
   * for the celebrity.
   * @param name name or {@code null} for none
   */
  public GoogleCloudVideointelligenceV1p3beta1Celebrity setName(java.lang.String name) {
    this.name = name;
    return this;
  }

  @Override
  public GoogleCloudVideointelligenceV1p3beta1Celebrity set(String fieldName, Object value) {
    return (GoogleCloudVideointelligenceV1p3beta1Celebrity) super.set(fieldName, value);
  }

  @Override
  public GoogleCloudVideointelligenceV1p3beta1Celebrity clone() {
    return (GoogleCloudVideointelligenceV1p3beta1Celebrity) super.clone();
  }

}