text:
package protocol

import (
	"crypto/sha256"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"path"
	"strings"
	"sync"
	"time"

	lz4 "github.com/bkaradzic/go-lz4"
)

const (
	// Shifts
	KiB = 10
	MiB = 20
	GiB = 30
)

const (
	// MaxMessageLen is the largest message size allowed on the wire. (500 MB)
	MaxMessageLen = 500 * 1000 * 1000

	// MinBlockSize is the minimum block size allowed
	MinBlockSize = 128 << KiB

	// MaxBlockSize is the maximum block size allowed
	MaxBlockSize = 16 << MiB

	// DesiredPerFileBlocks is the number of blocks we aim for per file
	DesiredPerFileBlocks = 2000
)

// BlockSizes is the list of valid block sizes, from min to max
var BlockSizes []int

// For each block size, the hash of a block of all zeroes
var sha256OfEmptyBlock = make(map[int][sha256.Size]byte)

func init() {
	for blockSize := MinBlockSize; blockSize <= MaxBlockSize; blockSize *= 2 {
		BlockSizes = append(BlockSizes, blockSize)
		sha256OfEmptyBlock[blockSize] = sha256.Sum256(make([]byte, blockSize))
	}
}

// BlockSize returns the block size to use for the given file size
func BlockSize(fileSize int64) int {
	var blockSize int
	for _, blockSize = range BlockSizes {
		if fileSize < int64(DesiredPerFileBlocks*blockSize) {
			break
		}
	}

	return blockSize
}

const (
	stateInitial = iota
	stateReady
)

// Request message flags
const (
	FlagFromTemporary uint32 = 1 << iota
)

// ClusterConfigMessage.Folders flags
const (
	FlagFolderReadOnly            uint32 = 1 << 0
	FlagFolderIgnorePerms                = 1 << 1
	FlagFolderIgnoreDelete               = 1 << 2
	FlagFolderDisabledTempIndexes        = 1 << 3
	FlagFolderAll                        = 1<<4 - 1
)

// ClusterConfigMessage.Folders.Devices flags
const (
	FlagShareTrusted  uint32 = 1 << 0
	FlagShareReadOnly        = 1 << 1
	FlagIntroducer           = 1 << 2
	FlagShareBits            = 0x000000ff
)

var (
	ErrClosed               = errors.New("connection closed")
	ErrTimeout              = errors.New("read timeout")
	ErrSwitchingConnections = errors.New("switching connections")
	errUnknownMessage       = errors.New("unknown message")
	errInvalidFilename      = errors.New("filename is invalid")
	errUncleanFilename      = errors.New("filename not in canonical format")
	errDeletedHasBlocks     = errors.New("deleted file with non-empty block list")
	errDirectoryHasBlocks   = errors.New("directory with non-empty block list")
	errFileHasNoBlocks      = errors.New("file with empty block list")
)

type Model interface {
	// An index was received from the peer device
	Index(deviceID DeviceID, folder string, files []FileInfo)
	// An index update was received from the peer device
	IndexUpdate(deviceID DeviceID, folder string, files []FileInfo)
	// A request was made by the peer device
	Request(deviceID DeviceID, folder string, name string, offset int64, hash []byte, weakHash uint32, fromTemporary bool, buf []byte) error
	// A cluster configuration message was received
	ClusterConfig(deviceID DeviceID, config ClusterConfig)
	// The peer device closed the connection
	Closed(conn Connection, err error)
	// The peer device sent progress updates for the files it is currently downloading
	DownloadProgress(deviceID DeviceID, folder string, updates []FileDownloadProgressUpdate)
}

type Connection interface {
	Start()
	ID() DeviceID
	Name() string
	Index(folder string, files []FileInfo) error
	IndexUpdate(folder string, files []FileInfo) error
	Request(folder string, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error)
	ClusterConfig(config ClusterConfig)
	DownloadProgress(folder string, updates []FileDownloadProgressUpdate)
	Statistics() Statistics
	Closed() bool
}

type rawConnection struct {
	id       DeviceID
	name     string
	receiver Model

	cr *countingReader
	cw *countingWriter

	awaiting    map[int32]chan asyncResult
	awaitingMut sync.Mutex

	idxMut sync.Mutex // ensures serialization of Index calls

	nextID    int32
	nextIDMut sync.Mutex

	outbox      chan asyncMessage
	closed      chan struct{}
	once        sync.Once
	pool        bufferPool
	compression Compression
}

type asyncResult struct {
	val []byte
	err error
}

type message interface {
	ProtoSize() int
	Marshal() ([]byte, error)
	MarshalTo([]byte) (int, error)
	Unmarshal([]byte) error
}

type asyncMessage struct {
	msg  message
	done chan struct{} // done closes when we're done marshalling the message and its contents can be reused
}

const (
	// PingSendInterval is how often we make sure to send a message, by
	// triggering pings if necessary.
	PingSendInterval = 90 * time.Second
	// ReceiveTimeout is the longest we'll wait for a message from the other
	// side before closing the connection.
	ReceiveTimeout = 300 * time.Second
)

// A buffer pool for global use. We don't allocate smaller buffers than 64k,
// in the hope of being able to reuse them later.
var buffers = bufferPool{
	minSize: 64 << 10,
}

func NewConnection(deviceID DeviceID, reader io.Reader, writer io.Writer, receiver Model, name string, compress Compression) Connection {
	cr := &countingReader{Reader: reader}
	cw := &countingWriter{Writer: writer}

	c := rawConnection{
		id:          deviceID,
		name:        name,
		receiver:    nativeModel{receiver},
		cr:          cr,
		cw:          cw,
		awaiting:    make(map[int32]chan asyncResult),
		outbox:      make(chan asyncMessage),
		closed:      make(chan struct{}),
		pool:        bufferPool{minSize: MinBlockSize},
		compression: compress,
	}

	return wireFormatConnection{&c}
}

// Start creates the goroutines for sending and receiving of messages. It must
// be called exactly once after creating a connection.
func (c *rawConnection) Start() {
	go c.readerLoop()
	go c.writerLoop()
	go c.pingSender()
	go c.pingReceiver()
}

func (c *rawConnection) ID() DeviceID {
	return c.id
}

func (c *rawConnection) Name() string {
	return c.name
}

// Index writes the list of file information to the connected peer device
func (c *rawConnection) Index(folder string, idx []FileInfo) error {
	select {
	case <-c.closed:
		return ErrClosed
	default:
	}
	c.idxMut.Lock()
	c.send(&Index{
		Folder: folder,
		Files:  idx,
	}, nil)
	c.idxMut.Unlock()
	return nil
}

// IndexUpdate writes the list of file information to the connected peer device as an update
func (c *rawConnection) IndexUpdate(folder string, idx []FileInfo) error {
	select {
	case <-c.closed:
		return ErrClosed
	default:
	}
	c.idxMut.Lock()
	c.send(&IndexUpdate{
		Folder: folder,
		Files:  idx,
	}, nil)
	c.idxMut.Unlock()
	return nil
}

// Request returns the bytes for the specified block after fetching them from the connected peer.
func (c *rawConnection) Request(folder string, name string, offset int64, size int, hash []byte, weakHash uint32, fromTemporary bool) ([]byte, error) {
	c.nextIDMut.Lock()
	id := c.nextID
	c.nextID++
	c.nextIDMut.Unlock()

	c.awaitingMut.Lock()
	if _, ok := c.awaiting[id]; ok {
		panic("id taken")
	}
	rc := make(chan asyncResult, 1)
	c.awaiting[id] = rc
	c.awaitingMut.Unlock()

	ok := c.send(&Request{
		ID:            id,
		Folder:        folder,
		Name:          name,
		Offset:        offset,
		Size:          int32(size),
		Hash:          hash,
		WeakHash:      weakHash,
		FromTemporary: fromTemporary,
	}, nil)
	if !ok {
		return nil, ErrClosed
	}

	res, ok := <-rc
	if !ok {
		return nil, ErrClosed
	}
	return res.val, res.err
}

// ClusterConfig send the cluster configuration message to the peer and returns any error
func (c *rawConnection) ClusterConfig(config ClusterConfig) {
	c.send(&config, nil)
}

func (c *rawConnection) Closed() bool {
	select {
	case <-c.closed:
		return true
	default:
		return false
	}
}

// DownloadProgress sends the progress updates for the files that are currently being downloaded.
func (c *rawConnection) DownloadProgress(folder string, updates []FileDownloadProgressUpdate) {
	c.send(&DownloadProgress{
		Folder:  folder,
		Updates: updates,
	}, nil)
}

func (c *rawConnection) ping() bool {
	return c.send(&Ping{}, nil)
}

func (c *rawConnection) readerLoop() (err error) {
	defer func() {
		c.close(err)
	}()

	state := stateInitial
	for {
		select {
		case <-c.closed:
			return ErrClosed
		default:
		}

		msg, err := c.readMessage()
		if err == errUnknownMessage {
			// Unknown message types are skipped, for future extensibility.
			continue
		}
		if err != nil {
			return err
		}

		switch msg := msg.(type) {
		case *ClusterConfig:
			l.Debugln("read ClusterConfig message")
			if state != stateInitial {
				return fmt.Errorf("protocol error: cluster config message in state %d", state)
			}
			c.receiver.ClusterConfig(c.id, *msg)
			state = stateReady

		case *Index:
			l.Debugln("read Index message")
			if state != stateReady {
				return fmt.Errorf("protocol error: index message in state %d", state)
			}
			if err := checkIndexConsistency(msg.Files); err != nil {
				return fmt.Errorf("protocol error: index: %v", err)
			}
			c.handleIndex(*msg)
			state = stateReady

		case *IndexUpdate:
			l.Debugln("read IndexUpdate message")
			if state != stateReady {
				return fmt.Errorf("protocol error: index update message in state %d", state)
			}
			if err := checkIndexConsistency(msg.Files); err != nil {
				return fmt.Errorf("protocol error: index update: %v", err)
			}
			c.handleIndexUpdate(*msg)
			state = stateReady

		case *Request:
			l.Debugln("read Request message")
			if state != stateReady {
				return fmt.Errorf("protocol error: request message in state %d", state)
			}
			if err := checkFilename(msg.Name); err != nil {
				return fmt.Errorf("protocol error: request: %q: %v", msg.Name, err)
			}
			// Requests are handled asynchronously
			go c.handleRequest(*msg)

		case *Response:
			l.Debugln("read Response message")
			if state != stateReady {
				return fmt.Errorf("protocol error: response message in state %d", state)
			}
			c.handleResponse(*msg)

		case *DownloadProgress:
			l.Debugln("read DownloadProgress message")
			if state != stateReady {
				return fmt.Errorf("protocol error: response message in state %d", state)
			}
			c.receiver.DownloadProgress(c.id, msg.Folder, msg.Updates)

		case *Ping:
			l.Debugln("read Ping message")
			if state != stateReady {
				return fmt.Errorf("protocol error: ping message in state %d", state)
			}
			// Nothing

		case *Close:
			l.Debugln("read Close message")
			return errors.New(msg.Reason)

		default:
			l.Debugf("read unknown message: %+T", msg)
			return fmt.Errorf("protocol error: %s: unknown or empty message", c.id)
		}
	}
}

func (c *rawConnection) readMessage() (message, error) {
	hdr, err := c.readHeader()
	if err != nil {
		return nil, err
	}

	return c.readMessageAfterHeader(hdr)
}

func (c *rawConnection) readMessageAfterHeader(hdr Header) (message, error) {
	// First comes a 4 byte message length

	buf := buffers.get(4)
	if _, err := io.ReadFull(c.cr, buf); err != nil {
		return nil, fmt.Errorf("reading message length: %v", err)
	}
	msgLen := int32(binary.BigEndian.Uint32(buf))
	if msgLen < 0 {
		return nil, fmt.Errorf("negative message length %d", msgLen)
	}

	// Then comes the message

	buf = buffers.upgrade(buf, int(msgLen))
	if _, err := io.ReadFull(c.cr, buf); err != nil {
		return nil, fmt.Errorf("reading message: %v", err)
	}

	// ... which might be compressed

	switch hdr.Compression {
	case MessageCompressionNone:
		// Nothing

	case MessageCompressionLZ4:
		decomp, err := c.lz4Decompress(buf)
		buffers.put(buf)
		if err != nil {
			return nil, fmt.Errorf("decompressing message: %v", err)
		}
		buf = decomp

	default:
		return nil, fmt.Errorf("unknown message compression %d", hdr.Compression)
	}

	// ... and is then unmarshalled

	msg, err := c.newMessage(hdr.Type)
	if err != nil {
		return nil, err
	}
	if err := msg.Unmarshal(buf); err != nil {
		return nil, fmt.Errorf("unmarshalling message: %v", err)
	}
	buffers.put(buf)

	return msg, nil
}

func (c *rawConnection) readHeader() (Header, error) {
	// First comes a 2 byte header length

	buf := buffers.get(2)
	if _, err := io.ReadFull(c.cr, buf); err != nil {
		return Header{}, fmt.Errorf("reading length: %v", err)
	}
	hdrLen := int16(binary.BigEndian.Uint16(buf))
	if hdrLen < 0 {
		return Header{}, fmt.Errorf("negative header length %d", hdrLen)
	}

	// Then comes the header

	buf = buffers.upgrade(buf, int(hdrLen))
	if _, err := io.ReadFull(c.cr, buf); err != nil {
		return Header{}, fmt.Errorf("reading header: %v", err)
	}

	var hdr Header
	if err := hdr.Unmarshal(buf); err != nil {
		return Header{}, fmt.Errorf("unmarshalling header: %v", err)
	}

	buffers.put(buf)
	return hdr, nil
}

func (c *rawConnection) handleIndex(im Index) {
	l.Debugf("Index(%v, %v, %d file)", c.id, im.Folder, len(im.Files))
	c.receiver.Index(c.id, im.Folder, im.Files)
}

func (c *rawConnection) handleIndexUpdate(im IndexUpdate) {
	l.Debugf("queueing IndexUpdate(%v, %v, %d files)", c.id, im.Folder, len(im.Files))
	c.receiver.IndexUpdate(c.id, im.Folder, im.Files)
}

// checkIndexConsistency verifies a number of invariants on FileInfos received in
// index messages.
func checkIndexConsistency(fs []FileInfo) error {
	for _, f := range fs {
		if err := checkFileInfoConsistency(f); err != nil {
			return fmt.Errorf("%q: %v", f.Name, err)
		}
	}
	return nil
}

// checkFileInfoConsistency verifies a number of invariants on the given FileInfo
func checkFileInfoConsistency(f FileInfo) error {
	if err := checkFilename(f.Name); err != nil {
		return err
	}

	switch {
	case f.Deleted && len(f.Blocks) != 0:
		// Deleted files should have no blocks
		return errDeletedHasBlocks

	case f.Type == FileInfoTypeDirectory && len(f.Blocks) != 0:
		// Directories should have no blocks
		return errDirectoryHasBlocks

	case !f.Deleted && !f.Invalid && f.Type == FileInfoTypeFile && len(f.Blocks) == 0:
		// Non-deleted, non-invalid files should have at least one block
		return errFileHasNoBlocks
	}
	return nil
}

// checkFilename verifies that the given filename is valid according to the
// spec on what's allowed over the wire. A filename failing this test is
// grounds for disconnecting the device.
func checkFilename(name string) error {
	cleanedName := path.Clean(name)
	if cleanedName != name {
		// The filename on the wire should be in canonical format. If
		// Clean() managed to clean it up, there was something wrong with
		// it.
		return errUncleanFilename
	}

	switch name {
	case "", ".", "..":
		// These names are always invalid.
		return errInvalidFilename
	}
	if strings.HasPrefix(name, "/") {
		// Names are folder relative, not absolute.
		return errInvalidFilename
	}
	if strings.HasPrefix(name, "../") {
		// Starting with a dotdot is not allowed. Any other dotdots would
		// have been handled by the Clean() call at the top.
		return errInvalidFilename
	}
	return nil
}

func (c *rawConnection) handleRequest(req Request) {
	size := int(req.Size)
	usePool := size <= MaxBlockSize

	var buf []byte
	var done chan struct{}

	if usePool {
		buf = c.pool.get(size)
		done = make(chan struct{})
	} else {
		buf = make([]byte, size)
	}

	err := c.receiver.Request(c.id, req.Folder, req.Name, req.Offset, req.Hash, req.WeakHash, req.FromTemporary, buf)
	if err != nil {
		c.send(&Response{
			ID:   req.ID,
			Data: nil,
			Code: errorToCode(err),
		}, done)
	} else {
		c.send(&Response{
			ID:   req.ID,
			Data: buf,
			Code: errorToCode(err),
		}, done)
	}

	if usePool {
		<-done
		c.pool.put(buf)
	}
}

func (c *rawConnection) handleResponse(resp Response) {
	c.awaitingMut.Lock()
	if rc := c.awaiting[resp.ID]; rc != nil {
		delete(c.awaiting, resp.ID)
		rc <- asyncResult{resp.Data, codeToError(resp.Code)}
		close(rc)
	}
	c.awaitingMut.Unlock()
}

func (c *rawConnection) send(msg message, done chan struct{}) bool {
	select {
	case c.outbox <- asyncMessage{msg, done}:
		return true
	case <-c.closed:
		return false
	}
}

func (c *rawConnection) writerLoop() {
	for {
		select {
		case hm := <-c.outbox:
			if err := c.writeMessage(hm); err != nil {
				c.close(err)
				return
			}

		case <-c.closed:
			return
		}
	}
}

func (c *rawConnection) writeMessage(hm asyncMessage) error {
	if c.shouldCompressMessage(hm.msg) {
		return c.writeCompressedMessage(hm)
	}
	return c.writeUncompressedMessage(hm)
}

func (c *rawConnection) writeCompressedMessage(hm asyncMessage) error {
	size := hm.msg.ProtoSize()
	buf := buffers.get(size)
	if _, err := hm.msg.MarshalTo(buf); err != nil {
		return fmt.Errorf("marshalling message: %v", err)
	}
	if hm.done != nil {
		close(hm.done)
	}

	compressed, err := c.lz4Compress(buf)
	if err != nil {
		return fmt.Errorf("compressing message: %v", err)
	}

	hdr := Header{
		Type:        c.typeOf(hm.msg),
		Compression: MessageCompressionLZ4,
	}
	hdrSize := hdr.ProtoSize()
	if hdrSize > 1<<16-1 {
		panic("impossibly large header")
	}

	totSize := 2 + hdrSize + 4 + len(compressed)
	buf = buffers.upgrade(buf, totSize)

	// Header length
	binary.BigEndian.PutUint16(buf, uint16(hdrSize))
	// Header
	if _, err := hdr.MarshalTo(buf[2:]); err != nil {
		return fmt.Errorf("marshalling header: %v", err)
	}
	// Message length
	binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(len(compressed)))
	// Message
	copy(buf[2+hdrSize+4:], compressed)
	buffers.put(compressed)

	n, err := c.cw.Write(buf)
	buffers.put(buf)

	l.Debugf("wrote %d bytes on the wire (2 bytes length, %d bytes header, 4 bytes message length, %d bytes message (%d uncompressed)), err=%v", n, hdrSize, len(compressed), size, err)
	if err != nil {
		return fmt.Errorf("writing message: %v", err)
	}
	return nil
}

func (c *rawConnection) writeUncompressedMessage(hm asyncMessage) error {
	size := hm.msg.ProtoSize()

	hdr := Header{
		Type: c.typeOf(hm.msg),
	}
	hdrSize := hdr.ProtoSize()
	if hdrSize > 1<<16-1 {
		panic("impossibly large header")
	}

	totSize := 2 + hdrSize + 4 + size
	buf := buffers.get(totSize)

	// Header length
	binary.BigEndian.PutUint16(buf, uint16(hdrSize))
	// Header
	if _, err := hdr.MarshalTo(buf[2:]); err != nil {
		return fmt.Errorf("marshalling header: %v", err)
	}
	// Message length
	binary.BigEndian.PutUint32(buf[2+hdrSize:], uint32(size))
	// Message
	if _, err := hm.msg.MarshalTo(buf[2+hdrSize+4:]); err != nil {
		return fmt.Errorf("marshalling message: %v", err)
	}
	if hm.done != nil {
		close(hm.done)
	}

	n, err := c.cw.Write(buf[:totSize])
	buffers.put(buf)

	l.Debugf("wrote %d bytes on the wire (2 bytes length, %d bytes header, 4 bytes message length, %d bytes message), err=%v", n, hdrSize, size, err)
	if err != nil {
		return fmt.Errorf("writing message: %v", err)
	}
	return nil
}

func (c *rawConnection) typeOf(msg message) MessageType {
	switch msg.(type) {
	case *ClusterConfig:
		return messageTypeClusterConfig
	case *Index:
		return messageTypeIndex
	case *IndexUpdate:
		return messageTypeIndexUpdate
	case *Request:
		return messageTypeRequest
	case *Response:
		return messageTypeResponse
	case *DownloadProgress:
		return messageTypeDownloadProgress
	case *Ping:
		return messageTypePing
	case *Close:
		return messageTypeClose
	default:
		panic("bug: unknown message type")
	}
}

func (c *rawConnection) newMessage(t MessageType) (message, error) {
	switch t {
	case messageTypeClusterConfig:
		return new(ClusterConfig), nil
	case messageTypeIndex:
		return new(Index), nil
	case messageTypeIndexUpdate:
		return new(IndexUpdate), nil
	case messageTypeRequest:
		return new(Request), nil
	case messageTypeResponse:
		return new(Response), nil
	case messageTypeDownloadProgress:
		return new(DownloadProgress), nil
	case messageTypePing:
		return new(Ping), nil
	case messageTypeClose:
		return new(Close), nil
	default:
		return nil, errUnknownMessage
	}
}

func (c *rawConnection) shouldCompressMessage(msg message) bool {
	switch c.compression {
	case CompressNever:
		return false

	case CompressAlways:
		// Use compression for large enough messages
		return msg.ProtoSize() >= compressionThreshold

	case CompressMetadata:
		_, isResponse := msg.(*Response)
		// Compress if it's large enough and not a response message
		return !isResponse && msg.ProtoSize() >= compressionThreshold

	default:
		panic("unknown compression setting")
	}
}

func (c *rawConnection) close(err error) {
	c.once.Do(func() {
		l.Debugln("close due to", err)
		close(c.closed)

		c.awaitingMut.Lock()
		for i, ch := range c.awaiting {
			if ch != nil {
				close(ch)
				delete(c.awaiting, i)
			}
		}
		c.awaitingMut.Unlock()

		c.receiver.Closed(c, err)
	})
}

// The pingSender makes sure that we've sent a message within the last
// PingSendInterval. If we already have something sent in the last
// PingSendInterval/2, we do nothing. Otherwise we send a ping message. This
// results in an effecting ping interval of somewhere between
// PingSendInterval/2 and PingSendInterval.
func (c *rawConnection) pingSender() {
	ticker := time.NewTicker(PingSendInterval / 2)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			d := time.Since(c.cw.Last())
			if d < PingSendInterval/2 {
				l.Debugln(c.id, "ping skipped after wr", d)
				continue
			}

			l.Debugln(c.id, "ping -> after", d)
			c.ping()

		case <-c.closed:
			return
		}
	}
}

// The pingReceiver checks that we've received a message (any message will do,
// but we expect pings in the absence of other messages) within the last
// ReceiveTimeout. If not, we close the connection with an ErrTimeout.
func (c *rawConnection) pingReceiver() {
	ticker := time.NewTicker(ReceiveTimeout / 2)
	defer ticker.Stop()

	for {
		select {
		case <-ticker.C:
			d := time.Since(c.cr.Last())
			if d > ReceiveTimeout {
				l.Debugln(c.id, "ping timeout", d)
				c.close(ErrTimeout)
			}

			l.Debugln(c.id, "last read within", d)

		case <-c.closed:
			return
		}
	}
}

type Statistics struct {
	At            time.Time
	InBytesTotal  int64
	OutBytesTotal int64
}

func (c *rawConnection) Statistics() Statistics {
	return Statistics{
		At:            time.Now(),
		InBytesTotal:  c.cr.Tot(),
		OutBytesTotal: c.cw.Tot(),
	}
}

func (c *rawConnection) lz4Compress(src []byte) ([]byte, error) {
	var err error
	buf := buffers.get(len(src))
	buf, err = lz4.Encode(buf, src)
	if err != nil {
		return nil, err
	}

	binary.BigEndian.PutUint32(buf, binary.LittleEndian.Uint32(buf))
	return buf, nil
}

func (c *rawConnection) lz4Decompress(src []byte) ([]byte, error) {
	size := binary.BigEndian.Uint32(src)
	binary.LittleEndian.PutUint32(src, size)
	var err error
	buf := buffers.get(int(size))
	buf, err = lz4.Decode(buf, src)
	if err != nil {
		return nil, err
	}
	return buf, nil
}


text:
$(document).ready(function () {
	oFunctions.start();
});

var oFunctions = (function functionClousure () {

	function initListeners () {
		$('#select-per-page').on('change', function () {
			var numPerPage = $(this).val();

			$('#input-products-per-page').val(numPerPage);
			$('#show-products-per-page').submit();
		});
	}

	return {
		start : function () {
			initListeners();
		}
	}

}) ();

redpajama_set_name: RedPajamaGithub


text:
var baseForOwn = require('./_baseForOwn'),
    baseIteratee = require('./_baseIteratee');

/**
 * The opposite of `_.mapValues`; this method creates an object with the
 * same values as `object` and keys generated by running each own enumerable
 * property of `object` through `iteratee`. The iteratee is invoked with
 * three arguments: (value, key, object).
 *
 * @static
 * @memberOf _
 * @category Object
 * @param {Object} object The object to iterate over.
 * @param {Function|Object|string} [iteratee=_.identity] The function invoked per iteration.
 * @returns {Object} Returns the new mapped object.
 * @example
 *
 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
 *   return key + value;
 * });
 * // => { 'a1': 1, 'b2': 2 }
 */
function mapKeys(object, iteratee) {
  var result = {};
  iteratee = baseIteratee(iteratee, 3);

  baseForOwn(object, function(value, key, object) {
    result[iteratee(value, key, object)] = value;
  });
  return result;
}

module.exports = mapKeys;


text:
from base import BaseTest
from utils import create_certificates_for_host

class TestCertificates(BaseTest):
    def test_custom_certificate(self):
        """
        Ensure that Ceryx uses the given certificate for each route, if configured
        so.
        """
        certificate_path , key_path = create_certificates_for_host(self.host)

        api_base_url = "http://api:5555/"
        self.redis.set(self.redis_target_key, api_base_url)

        self.redis.hset(self.redis_settings_key, "certificate_path", certificate_path)
        self.redis.hset(self.redis_settings_key, "key_path", key_path)

        self.client.get(f"https://{self.host}/", verify=certificate_path)

    def test_fallback_certificate(self):
        """
        Ensure that Ceryx uses the fallback certificate if a route gets accessed
        via HTTPS with no configured certificate or automatic Let's Encrypt
        certificates enabled.
        """
        try:
            response = self.client.get(f"https://ghost.ceryx.test/", verify="/etc/ceryx/ssl/default.crt")
        except Exception as e:
            assert "sni-support-required-for-valid-ssl" in str(e)


text:
<?php

/**
 * @file index.php
 * Dispatcher para la página web
 * @version 2014-04-02
 */

// Directorio de instalación de SowerPHP, En caso de una instalación compartida
// se debe modificar esta definición indicando el directorio donde está
// instalado el framework, ejemplo: /usr/share/sowerphp
#define ('DIR_FRAMEWORK', dirname(dirname(dirname(dirname(__FILE__)))));
define ('DIR_FRAMEWORK', "/usr/share/sowerphp");

// Directorio que contiene el proyecto (directorio project) ¡no modificar!
define ('DIR_PROJECT', dirname(dirname(dirname(__FILE__))));

// Extensiones que se utilizarán. Deberá ser vendor/extensión dentro de
// DIR_FRAMEWORK/extensions o bien dentro de DIR_PROJECT/extensions, ejemplo:
// $_EXTENSIONS = array('sowerphp/dev', 'sowerphp/general');
$_EXTENSIONS = array('sowerphp/app', 'sowerphp/general');

// Iniciar bootstrap (proceso que prepara e inicia el proyecto)
if (!@include(DIR_FRAMEWORK.'/lib/sowerphp/core/bootstrap.php')) {
    echo 'Bootstrap no ha podido ser ejecutado, verificar DIR_FRAMEWORK ',
        'en ',DIR_PROJECT,'/website/webroot/index.php'
    ;
    exit(1);
}

// Despachar/ejecutar la página
\sowerphp\core\Routing_Dispatcher::dispatch();


text:
package org.aracrown.commons.persistence;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

public class AbstractDaoTest {
	protected static EntityManager em;
	protected static EntityManagerFactory emf;

	@Before
	public void startTransaction() throws Exception {
		em.getTransaction().begin();
		em.clear();
	}

	@After
	public void rollbackTransaction() {
		em.getTransaction().rollback();
	}

	@BeforeClass
	public static void setup() throws Exception {
		emf = Persistence.createEntityManagerFactory("sports");
		em = emf.createEntityManager();
	}

	@AfterClass
	public static void close() {
		em.close();
		emf.close();
	}

	protected FakeEntityDao newFakeEntityDao() {
		return new FakeEntityDao(em);
	}
}


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

<title>G-Index</title>
<meta name="date" content="2015-04-05">
<link rel="stylesheet" type="text/css" href="../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes

E G I M R S T

G

getComputerFingers() - Method in class Morra

getComputerScore() - Method in class Morra

getComputerTotal() - Method in class Morra

getGameWinner() - Method in class Morra

Get the winner of the game.

getPlayerFingers() - Method in class Morra

getPlayerScore() - Method in class Morra

getPlayerTotal() - Method in class Morra

getRoundsPlayed() - Method in class Morra

Get the number of rounds played of the game.

getRoundTotal() - Method in class Morra

getRoundWinner() - Method in class Morra

Get the winner of the round.

getWinsNeeded() - Method in class Morra

E G I M R S T

Skip navigation links

Package

Class

Tree

Deprecated

Index

Help

Prev Letter

Next Letter

Frames

No Frames

All Classes


text:
namespace FlaUI.Core.Definitions
{
    public enum PropertyConditionFlags
    {
        None = 0,
        IgnoreCase = 1
    }
}


text:
const DrawCard = require('../../../drawcard.js');

class SmallCouncilChamber extends DrawCard {
    setupCardAbilities(ability) {
        this.persistentEffect({
            match: this,
            effect: ability.effects.immuneTo(card => card.getType() === 'event')
        });
        this.reaction({
            when: {
                afterChallenge: (e, challenge) => challenge.winner === this.controller && challenge.challengeType === 'intrigue'
            },
            handler: () => {
                this.game.addMessage('{0} gains 1 power on {1}', this.controller, this);
                this.modifyPower(1);
            }
        });
    }
}

SmallCouncilChamber.code = '02110';

module.exports = SmallCouncilChamber;


text:
@interface AppDelegate ()
@property(nonatomic,strong) AVAudioPlayer *player;
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    //注册通知,使应用图标可以显示未读消息的总和
    UIUserNotificationSettings *settings =[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];

    [application registerUserNotificationSettings:settings];

    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];

    //选择跟试图控制器
    //判断是否授权
    if ([CyAcountTool acount]) {//已经授权
        [CyRootTool choseRootViewController:self.window];
    }else{
        CyOAuthViewController *authoVC = [[CyOAuthViewController alloc] init];

        self.window.rootViewController = authoVC;
    }

    [self.window makeKeyAndVisible];

    return YES;
}

//内存告罄
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application{

    //停止所有的下载
    [[SDWebImageManager sharedManager] cancelAll];

    //删除缓存
    [[SDWebImageManager sharedManager].imageCache clearMemory];
}

//失去焦点
- (void)applicationWillResignActive:(UIApplication *)application {
    NSURL *url =[[NSBundle mainBundle] URLForResource:@"silence.mp3" withExtension:nil];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];

    _player = player;

    [player prepareToPlay];
    player.numberOfLoops = -1;
    [player play];

}
//进入后台程序时候调用
- (void)applicationDidEnterBackground:(UIApplication *)application {
    //开启一个后台任务,优先级比较低,苹果系统优先处理结束,时间不确定
    UIBackgroundTaskIdentifier Id = [application beginBackgroundTaskWithExpirationHandler:^{

        //当后台程序结束时,调用
        [application endBackgroundTask:Id];

    }];

    // 如何提高后台任务的优先级,欺骗苹果,我们是后台播放程序

    // 但是苹果会检测你的程序当时有没有播放音乐,如果没有,有可能就干掉你

    // 微博:在程序即将失去焦点的时候播放静音音乐.

}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
<?xml version="1.0" encoding="utf-8"?>

    <android.support.v7.widget.CardView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/layout_margin_8"
        android:layout_marginEnd="@dimen/layout_margin_16"
        android:layout_marginLeft="@dimen/layout_margin_16"
        android:layout_marginRight="@dimen/layout_margin_16"
        android:layout_marginStart="@dimen/layout_margin_16"
        android:layout_marginTop="@dimen/layout_margin_8"
        app:cardCornerRadius="4dp"
        app:elevation="5dp">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="@dimen/layout_margin_16"
            android:src="@drawable/ic_play_icon"/>

        <TextView
            android:id="@+id/tv_detail_trailer_item"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            tools:text="Trailer 1"/>
    </LinearLayout>

</android.support.v7.widget.CardView>


text:
package de.philipphager.disclosure.feature.analyser.library.usecase;

import de.philipphager.disclosure.database.library.model.Library;
import de.philipphager.disclosure.database.method.model.Method;
import de.philipphager.disclosure.feature.analyser.library.LibraryParser;
import java.io.File;
import java.util.List;
import javax.inject.Inject;
import rx.Observable;

public class AnalyseLibraryMethodInvocations {
  @SuppressWarnings("PMD.UnnecessaryConstructor")
  @Inject public AnalyseLibraryMethodInvocations() {
    // Needed for dagger injection.
  }

  public Observable<List<Method>> run(File decompiledApkDir, Library library) {
    return Observable.just(getLibrarySourceDirectory(decompiledApkDir, library))
        .filter(File::exists)
        .map(LibraryParser::new)
        .flatMap(LibraryParser::findMethodInvocations)
        .flatMap(Observable::from)
        .distinct()
        .filter(new FilterIrrelevantMethods())
        .toList();
  }

  private File getLibrarySourceDirectory(File decompiledApkDir, Library library) {
    return new File(decompiledApkDir.getPath() + File.separator + library.sourceDir());
  }
}


text: Map Content: {{getMapName()}}


text:
{% assign post = site.posts.first %}

{{ post.title2 }}

{{ post.categories }}s

                <canvas class="chartjs-polar2 chartjs-charts" width="320" height="280"></canvas>

{{ post.title }}

{{ post.categories }}s

                <canvas class="chartjs-polar chartjs-charts" width="320" height="280"></canvas>


text:
<!DOCTYPE html>
<html lang="ja" prefix="og: http://ogp.me/ns#">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="viewport" content="width=device-width">
<meta name="format-detection" content="telephone=no">
<meta name="description" content="">
<meta property="og:site_name" content="">
<meta property="og:title" content="">
<meta property="og:type" content="website">
<meta property="og:url" content="">
<meta property="og:image" content="">
<meta property="og:description" content="">
<link href="/assets/css/base.css" rel="stylesheet">
</head>
<body id="sid-A-01">
<script src="/assets/js/libs/require.js" data-main="/assets/js/main" charset="utf-8"></script>
<!--[if lt IE 9]>
<script src="/assets/js/libs/html5shiv.js"></script><![endif]-->

</body>
</html>


text:
/*
 * Created on Jul 21, 2004
 */
package net.negativetwenty.bookmarker;

import net.negativetwenty.bookmarker.models.*;

import org.apache.tapestry.*;
import org.apache.tapestry.event.*;
import org.apache.tapestry.form.IPropertySelectionModel;
import org.apache.tapestry.valid.IValidationDelegate;
import org.objectstyle.cayenne.access.DataContext;

/**
 * Controls adding new categories to the database.
 *
 * @author nirvdrum
 */
public abstract class AddCategory extends SecureApplicationPage implements PageRenderListener
{
	public abstract Category getCategory();
	public abstract void setCategory(Category category);
	public abstract Category getParent();
	public abstract void setParent(Category parent);

	/**
	 * Builds up a new CategorySelectionModel for a category drop-down list  (PropertySelection component).
	 *
	 * @return The new CategorySelectionModel instance.
	 */
	public IPropertySelectionModel getCategoryModel()
	{
		return new CategorySelectionModel(getDataContext());
	}

	/**
	 * AddCategory listener.  Adds a new category to the database.
	 *
	 * @param cycle
	 */
	public void addCategory(final IRequestCycle cycle)
	{
		final IValidationDelegate delegate = (IValidationDelegate) getBeans().getBean("delegate");

		if (true == delegate.getHasErrors())
		{
		    return;
		}

	    final DataContext dc = getDataContext();
	    final Category category = getCategory();

	    // Register the category with the dc.
	    dc.registerNewObject(category);

	    // Set the category's property values.
	    category.setCreated(new java.util.Date());
	    category.setCreatedBy(getUser());
	    category.setParent(getParent());

	    // Add the category to the db.
	    dc.commitChanges();

		// TODO Change this to be some sort of callback.
		cycle.activate("Home");
	}

	/**
	 * Make sure the category property is a valid Category instance when the page renders.
	 *
	 * @param event
	 */
	public void pageBeginRender(final PageEvent event)
	{
		if (getCategory() == null)
		{
			setCategory(new Category());
		}
	}
}


text:
<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="HACK INN">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">

    <title>HACK INN</title>
    <meta property="og:title" content="HACK INN" />
    <meta property="og:locale" content="ko_KR" />
    <link rel="canonical" href="http://hackinn.co.kr/" />
    <meta property="og:url" content="http://hackinn.co.kr/" />
    <meta property="og:site_name" content="HACK INN" />
    <meta property="og:image" content="http://hackinn.co.kr/images/hackinn-logo-171026.png" />

    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:regular,bold,italic,thin,light,bolditalic,black,medium&lang=en">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.min.css">
    <link rel="stylesheet" href="styles.css">

HACK INN

Place for hacking stereotype

            Coming soon


text:
package service

import (
	"net/http"
)

type ServerConfigSaveRequestHandle interface {
	Save(*http.Request) error
}

func NewServerConfigSaveRequestHandle() ServerConfigSaveRequestHandle {
	return &serverConfigSaveRequestHandleImpl{}
}


text:
MAP=/group/stranger-lab/moliva/ImmVar/probes_mapping/Hugene_info/HuGene-1_0-st-v1.r4.mps
CLF=/group/stranger-lab/moliva/ImmVar/probes_mapping/Hugene_info/HuGene-1_0-st-v1.r4.clf

F=/group/stranger-lab/immvar/apt_scripts/probes

echo -e "probe_id\tprobeset_id\tx\ty" > /group/stranger-lab/immvar/apt_scripts/kill_list.txt.tmp;
while read line
do
	#pset=$(grep -e '\s$line\s' $MAP | cut -f 1);
	#loc=$(grep -e "^$line\s" $CLF | cut -f 2,3);
	entry=$(grep -w -m 1 $line $F)
	echo $entry >> /group/stranger-lab/immvar/apt_scripts/kill_list.txt.tmp;
done < /group/stranger-lab/immvar/apt_scripts/probes_to_kill.txt


text:
/**
 * Generates character limit modifier
 *
 * @param {number} limit Maximum character limit value
 * @returns {function(string): string} Function that truncates text length to limit
 */
function CharacterLimitModifier(limit) {
  return function (text) {
    if (limit <= 0 || text == null) {
      return text;
    }
    return text.substring(0, limit);
  }
}

export default CharacterLimitModifier;


text:
"""Make the AWS bucket optional.

Revision ID: b6533e0a4e58
Revises: eca04db5c363
Create Date: 2017-02-06 02:16:03.926797

"""

# revision identifiers, used by Alembic.
revision = 'b6533e0a4e58'
down_revision = 'eca04db5c363'

from alembic import op
import sqlalchemy as sa

def upgrade():
    op.alter_column('aws_key',
        column_name='billing_bucket_name',
        existing_type=sa.String(length=63),
        nullable=True,
    )

def downgrade():
    op.alter_column('aws_key',
        column_name='billing_bucket_name',
        existing_type=sa.String(length=63),
        nullable=False,
    )


text:
IA
==

Artificial Intelligence project
Test.


text:
static bool g_is_crash_reporting_enabled = false;
static Lumix::DefaultAllocator stack_node_allocator;

namespace Lumix
{

namespace debug
{

void enableFloatingPointTraps(bool enable)
{
	unsigned int cw = _control87(0, 0) & MCW_EM;
	if (enable)
	{
		cw &= ~(_EM_OVERFLOW | _EM_ZERODIVIDE | _EM_INVALID | _EM_DENORMAL); // can not enable _EM_INEXACT because it is common in QT
	}
	else
	{
		cw |= _EM_OVERFLOW | _EM_INVALID | _EM_DENORMAL; // can not enable _EM_INEXACT because it is common in QT
	}
	_control87(cw, MCW_EM);
}

void debugOutput(const char* message)
{
	OutputDebugString(message);
}

void debugBreak()
{
	DebugBreak();
}

int StackTree::s_instances = 0;

struct StackNode
{
	~StackNode()
	{
		LUMIX_DELETE(stack_node_allocator, m_next);
		LUMIX_DELETE(stack_node_allocator, m_first_child);
	}

	void* m_instruction;
	StackNode* m_next = nullptr;
	StackNode* m_first_child = nullptr;
	StackNode* m_parent;
};

StackTree::StackTree()
{
	m_root = nullptr;
	if (atomicIncrement(&s_instances) == 1)
	{
		HANDLE process = GetCurrentProcess();
		SymInitialize(process, nullptr, TRUE);
	}
}

StackTree::~StackTree()
{
	LUMIX_DELETE(stack_node_allocator, m_root);
	if (atomicDecrement(&s_instances) == 0)
	{
		HANDLE process = GetCurrentProcess();
		SymCleanup(process);
	}
}

void StackTree::refreshModuleList()
{
	ASSERT(s_instances > 0);
	SymRefreshModuleList(GetCurrentProcess());
}

int StackTree::getPath(StackNode* node, Span<StackNode*> output)
{
	u32 i = 0;
	while (i < output.length() && node)
	{
		output[i] = node;
		i++;
		node = node->m_parent;
	}
	return i;
}

StackNode* StackTree::getParent(StackNode* node)
{
	return node ? node->m_parent : nullptr;
}

bool StackTree::getFunction(StackNode* node, Span<char> out, int& line)
{
	HANDLE process = GetCurrentProcess();
	alignas(SYMBOL_INFO) u8 symbol_mem[sizeof(SYMBOL_INFO) + 256 * sizeof(char)] = {};
	SYMBOL_INFO* symbol = reinterpret_cast<SYMBOL_INFO*>(symbol_mem);
	symbol->MaxNameLen = 255;
	symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
	BOOL success = SymFromAddr(process, (DWORD64)(node->m_instruction), 0, symbol);
	IMAGEHLP_LINE64 line_info;
	DWORD displacement;
	if (SymGetLineFromAddr64(process, (DWORD64)(node->m_instruction), &displacement, &line_info))
	{
		line = line_info.LineNumber;
	}
	else
	{
		line = -1;
	}
	if (success) copyString(out, symbol->Name);

	return success != FALSE;
}

void StackTree::printCallstack(StackNode* node)
{
	while (node)
	{
		HANDLE process = GetCurrentProcess();
		alignas(SYMBOL_INFO) u8 symbol_mem[sizeof(SYMBOL_INFO) + 256 * sizeof(char)];
		SYMBOL_INFO* symbol = reinterpret_cast<SYMBOL_INFO*>(symbol_mem);
		memset(symbol_mem, 0, sizeof(symbol_mem));
		symbol->MaxNameLen = 255;
		symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
		BOOL success = SymFromAddr(process, (DWORD64)(node->m_instruction), 0, symbol);
		if (success)
		{
			IMAGEHLP_LINE line;
			DWORD offset;
			if (SymGetLineFromAddr(process, (DWORD64)(node->m_instruction), &offset, &line))
			{
				OutputDebugString("\t");
				OutputDebugString(line.FileName);
				OutputDebugString("(");
				char tmp[20];
				toCString((u32)line.LineNumber, Span(tmp));
				OutputDebugString(tmp);
				OutputDebugString("):");
			}
			OutputDebugString("\t");
			OutputDebugString(symbol->Name);
			OutputDebugString("\n");
		}
		else
		{
			OutputDebugString("\tN/A\n");
		}
		node = node->m_parent;
	}
}

StackNode* StackTree::insertChildren(StackNode* root_node, void** instruction, void** stack)
{
	StackNode* node = root_node;
	while (instruction >= stack)
	{
		StackNode* new_node = LUMIX_NEW(stack_node_allocator, StackNode)();
		node->m_first_child = new_node;
		new_node->m_parent = node;
		new_node->m_next = nullptr;
		new_node->m_first_child = nullptr;
		new_node->m_instruction = *instruction;
		node = new_node;
		--instruction;
	}
	return node;
}

StackNode* StackTree::record()
{
	static const int frames_to_capture = 256;
	void* stack[frames_to_capture];
	USHORT captured_frames_count = CaptureStackBackTrace(2, frames_to_capture, stack, 0);

	void** ptr = stack + captured_frames_count - 1;
	if (!m_root) {
		m_root = LUMIX_NEW(stack_node_allocator, StackNode)();
		m_root->m_instruction = *ptr;
		m_root->m_first_child = nullptr;
		m_root->m_next = nullptr;
		m_root->m_parent = nullptr;
		--ptr;
		return insertChildren(m_root, ptr, stack);
	}

	StackNode* node = m_root;
	while (ptr >= stack)
	{
		while (node->m_instruction != *ptr && node->m_next)
		{
			node = node->m_next;
		}
		if (node->m_instruction != *ptr)
		{
			node->m_next = LUMIX_NEW(stack_node_allocator, StackNode);
			node->m_next->m_parent = node->m_parent;
			node->m_next->m_instruction = *ptr;
			node->m_next->m_next = nullptr;
			node->m_next->m_first_child = nullptr;
			--ptr;
			return insertChildren(node->m_next, ptr, stack);
		}

		if (node->m_first_child)
		{
			--ptr;
			node = node->m_first_child;
		}
		else if (ptr != stack)
		{
			--ptr;
			return insertChildren(node, ptr, stack);
		}
		else
		{
			return node;
		}
	}

	return node;
}

static const u32 UNINITIALIZED_MEMORY_PATTERN = 0xCD;
static const u32 FREED_MEMORY_PATTERN = 0xDD;
static const u32 ALLOCATION_GUARD = 0xFDFDFDFD;

void* GuardAllocator::allocate_aligned(size_t size, size_t align) {
	const size_t pages = 1 + ((size + 4095) >> 12);
	void* mem = VirtualAlloc(nullptr, pages * 4096, MEM_RESERVE, PAGE_READWRITE);
	VirtualAlloc(mem, (pages - 1) * 4096, MEM_COMMIT, PAGE_READWRITE);

	if (align == 4096) return mem;

	u8* ptr = (u8*)mem;
	return (void*)(uintptr_t(ptr + (pages - 1) * 4096 - size) & ~size_t(align - 1));
}

void GuardAllocator::deallocate_aligned(void* ptr) {
	VirtualFree((void*)((uintptr_t)ptr & ~(size_t)4095), 0, MEM_RELEASE);
}

Allocator::Allocator(IAllocator& source)
	: m_source(source)
	, m_root(nullptr)
	, m_total_size(0)
	, m_is_fill_enabled(true)
	, m_are_guards_enabled(true)
{
	m_sentinels[0].next = &m_sentinels[1];
	m_sentinels[0].previous = nullptr;
	m_sentinels[0].stack_leaf = nullptr;
	m_sentinels[0].size = 0;
	m_sentinels[0].align = 0;

	m_sentinels[1].next = nullptr;
	m_sentinels[1].previous = &m_sentinels[0];
	m_sentinels[1].stack_leaf = nullptr;
	m_sentinels[1].size = 0;
	m_sentinels[1].align = 0;

	m_root = &m_sentinels[1];
}

void Allocator::checkLeaks()
{
	AllocationInfo* last_sentinel = &m_sentinels[1];
	if (m_root != last_sentinel)
	{
		OutputDebugString("Memory leaks detected!\n");
		AllocationInfo* info = m_root;
		while (info != last_sentinel)
		{
			StaticString<2048> tmp("\nAllocation size : ", info->size, " , memory ", (u64)(info + sizeof(info)), "\n"); //-V568
			OutputDebugString(tmp);
			m_stack_tree.printCallstack(info->stack_leaf);
			info = info->next;
		}
		debugBreak();
	}
}

Allocator::~Allocator()
{
	checkLeaks();
}

void Allocator::lock()
{
	m_mutex.enter();
}

void Allocator::unlock()
{
	m_mutex.exit();
}

void Allocator::checkGuards()
{
	if (m_are_guards_enabled) return;

	auto* info = m_root;
	while (info)
	{
		auto user_ptr = getUserPtrFromAllocationInfo(info);
		void* system_ptr = getSystemFromUser(user_ptr);
		ASSERT(*(u32*)system_ptr == ALLOCATION_GUARD);
		ASSERT(*(u32*)((u8*)user_ptr + info->size) == ALLOCATION_GUARD);

		info = info->next;
	}
}

size_t Allocator::getAllocationOffset()
{
	return sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0);
}

size_t Allocator::getNeededMemory(size_t size)
{
	return size + sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) << 1 : 0);
}

size_t Allocator::getNeededMemory(size_t size, size_t align)
{
	return size + sizeof(AllocationInfo) + (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) << 1 : 0) +
		   align;
}

Allocator::AllocationInfo* Allocator::getAllocationInfoFromSystem(void* system_ptr)
{
	return (AllocationInfo*)(m_are_guards_enabled ? (u8*)system_ptr + sizeof(ALLOCATION_GUARD)
												  : system_ptr);
}

void* Allocator::getUserPtrFromAllocationInfo(AllocationInfo* info)
{
	return ((u8*)info + sizeof(AllocationInfo));
}

Allocator::AllocationInfo* Allocator::getAllocationInfoFromUser(void* user_ptr)
{
	return (AllocationInfo*)((u8*)user_ptr - sizeof(AllocationInfo));
}

u8* Allocator::getUserFromSystem(void* system_ptr, size_t align)
{
	size_t diff = (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0) + sizeof(AllocationInfo);

	if (align) diff += (align - diff % align) % align;
	return (u8*)system_ptr + diff;
}

u8* Allocator::getSystemFromUser(void* user_ptr)
{
	AllocationInfo* info = getAllocationInfoFromUser(user_ptr);
	size_t diff = (m_are_guards_enabled ? sizeof(ALLOCATION_GUARD) : 0) + sizeof(AllocationInfo);
	if (info->align) diff += (info->align - diff % info->align) % info->align;
	return (u8*)user_ptr - diff;
}

void* Allocator::reallocate(void* user_ptr, size_t size)
{
	if (user_ptr == nullptr) return allocate(size);
	if (size == 0) return nullptr;

	void* new_data = allocate(size);
	if (!new_data) return nullptr;

	AllocationInfo* info = getAllocationInfoFromUser(user_ptr);
	memcpy(new_data, user_ptr, info->size < size ? info->size : size);

	deallocate(user_ptr);

	return new_data;
}

void* Allocator::allocate_aligned(size_t size, size_t align)
{
	void* system_ptr;
	AllocationInfo* info;
	u8* user_ptr;

	size_t system_size = getNeededMemory(size, align);

	m_mutex.enter();
	system_ptr = m_source.allocate_aligned(system_size, align);
	user_ptr = getUserFromSystem(system_ptr, align);
	info = new (NewPlaceholder(), getAllocationInfoFromUser(user_ptr)) AllocationInfo();

	info->previous = m_root->previous;
	m_root->previous->next = info;

	info->next = m_root;
	m_root->previous = info;

	m_root = info;

	m_total_size += size;
	m_mutex.exit();

	info->align = u16(align);
	info->stack_leaf = m_stack_tree.record();
	info->size = size;
	if (m_is_fill_enabled)
	{
		memset(user_ptr, UNINITIALIZED_MEMORY_PATTERN, size);
	}

	if (m_are_guards_enabled)
	{
		*(u32*)system_ptr = ALLOCATION_GUARD;
		*(u32*)((u8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) = ALLOCATION_GUARD;
	}

	return user_ptr;
}

void Allocator::deallocate_aligned(void* user_ptr)
{
	if (user_ptr)
	{
		AllocationInfo* info = getAllocationInfoFromUser(user_ptr);
		void* system_ptr = getSystemFromUser(user_ptr);
		if (m_is_fill_enabled)
		{
			memset(user_ptr, FREED_MEMORY_PATTERN, info->size);
		}

		if (m_are_guards_enabled)
		{
			ASSERT(*(u32*)system_ptr == ALLOCATION_GUARD);
			size_t system_size = getNeededMemory(info->size, info->align);
			ASSERT(*(u32*)((u8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) == ALLOCATION_GUARD);
		}

		{
			MutexGuard lock(m_mutex);
			if (info == m_root)
			{
				m_root = info->next;
			}
			info->previous->next = info->next;
			info->next->previous = info->previous;

			m_total_size -= info->size;
		} // because of the lock

		info->~AllocationInfo();

		m_source.deallocate_aligned((void*)system_ptr);
	}
}

void* Allocator::reallocate_aligned(void* user_ptr, size_t size, size_t align)
{
	if (user_ptr == nullptr) return allocate_aligned(size, align);
	if (size == 0) return nullptr;

	void* new_data = allocate_aligned(size, align);
	if (!new_data) return nullptr;

	AllocationInfo* info = getAllocationInfoFromUser(user_ptr);
	memcpy(new_data, user_ptr, info->size < size ? info->size : size);

	deallocate_aligned(user_ptr);

	return new_data;
}

void* Allocator::allocate(size_t size)
{
	void* system_ptr;
	AllocationInfo* info;
	size_t system_size = getNeededMemory(size);
	{
		MutexGuard lock(m_mutex);
		system_ptr = m_source.allocate(system_size);
		info = new (NewPlaceholder(), getAllocationInfoFromSystem(system_ptr)) AllocationInfo();

		info->previous = m_root->previous;
		m_root->previous->next = info;

		info->next = m_root;
		m_root->previous = info;

		m_root = info;

		m_total_size += size;
	} // because of the lock

	void* user_ptr = getUserFromSystem(system_ptr, 0);
	info->stack_leaf = m_stack_tree.record();
	info->size = size;
	info->align = 0;
	if (m_is_fill_enabled)
	{
		memset(user_ptr, UNINITIALIZED_MEMORY_PATTERN, size);
	}

	if (m_are_guards_enabled)
	{
		*(u32*)system_ptr = ALLOCATION_GUARD;
		*(u32*)((u8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) = ALLOCATION_GUARD;
	}

	return user_ptr;
}

void Allocator::deallocate(void* user_ptr)
{
	if (user_ptr)
	{
		AllocationInfo* info = getAllocationInfoFromUser(user_ptr);
		void* system_ptr = getSystemFromUser(user_ptr);
		if (m_is_fill_enabled)
		{
			memset(user_ptr, FREED_MEMORY_PATTERN, info->size);
		}

		if (m_are_guards_enabled)
		{
			ASSERT(*(u32*)system_ptr == ALLOCATION_GUARD);
			size_t system_size = getNeededMemory(info->size);
			ASSERT(*(u32*)((u8*)system_ptr + system_size - sizeof(ALLOCATION_GUARD)) == ALLOCATION_GUARD);
		}

		{
			MutexGuard lock(m_mutex);
			if (info == m_root)
			{
				m_root = info->next;
			}
			info->previous->next = info->next;
			info->next->previous = info->previous;

			m_total_size -= info->size;
		} // because of the lock

		info->~AllocationInfo();

		m_source.deallocate((void*)system_ptr);
	}
}

} // namespace Debug

BOOL SendFile(LPCSTR lpszSubject,
	LPCSTR lpszTo,
	LPCSTR lpszName,
	LPCSTR lpszText,
	LPCSTR lpszFullFileName)
{
	HINSTANCE hMAPI = ::LoadLibrary("mapi32.dll");
	if (!hMAPI) return FALSE;
	LPMAPISENDMAIL lpfnMAPISendMail = (LPMAPISENDMAIL)::GetProcAddress(hMAPI, "MAPISendMail");

	PathInfo fi(lpszFullFileName);

	char szFileName[MAX_PATH] = {0};
	strcat_s(szFileName, fi.m_basename);
	strcat_s(szFileName, ".");
	strcat_s(szFileName, fi.m_extension);

	char szFullFileName[MAX_PATH] = {0};
	strcat_s(szFullFileName, lpszFullFileName);

	MapiFileDesc MAPIfile = {0};
	ZeroMemory(&MAPIfile, sizeof(MapiFileDesc));
	MAPIfile.nPosition = 0xFFFFFFFF;
	MAPIfile.lpszPathName = szFullFileName;
	MAPIfile.lpszFileName = szFileName;

	char szTo[MAX_PATH] = {0};
	strcat_s(szTo, lpszTo);

	char szNameTo[MAX_PATH] = {0};
	strcat_s(szNameTo, lpszName);

	MapiRecipDesc recipient = {0};
	recipient.ulRecipClass = MAPI_TO;
	recipient.lpszAddress = szTo;
	recipient.lpszName = szNameTo;

	char szSubject[MAX_PATH] = {0};
	strcat_s(szSubject, lpszSubject);

	char szText[MAX_PATH] = {0};
	strcat_s(szText, lpszText);

	MapiMessage MAPImsg = {0};
	MAPImsg.lpszSubject = szSubject;
	MAPImsg.lpRecips = &recipient;
	MAPImsg.nRecipCount = 1;
	MAPImsg.lpszNoteText = szText;
	MAPImsg.nFileCount = 1;
	MAPImsg.lpFiles = &MAPIfile;

	ULONG nSent = lpfnMAPISendMail(0, 0, &MAPImsg, 0, 0);

	FreeLibrary(hMAPI);
	return (nSent == SUCCESS_SUCCESS || nSent == MAPI_E_USER_ABORT);
}

static void getStack(CONTEXT& context, Span<char> out)
{
	BOOL result;
	STACKFRAME64 stack;
	alignas(IMAGEHLP_SYMBOL64) char symbol_mem[sizeof(IMAGEHLP_SYMBOL64) + 256];
	IMAGEHLP_SYMBOL64* symbol = (IMAGEHLP_SYMBOL64*)symbol_mem;
	char name[256];
	copyString(out, "Crash callstack:\n");
	memset(&stack, 0, sizeof(STACKFRAME64));

	HANDLE process = GetCurrentProcess();
	HANDLE thread = GetCurrentThread();
	DWORD64 displacement = 0;
	DWORD machineType;

#ifdef _M_X64
	machineType = IMAGE_FILE_MACHINE_AMD64;
	stack.AddrPC.Offset = context.Rip;
	stack.AddrPC.Mode = AddrModeFlat;
	stack.AddrStack.Offset = context.Rsp;
	stack.AddrStack.Mode = AddrModeFlat;
	stack.AddrFrame.Offset = context.Rbp;
	stack.AddrFrame.Mode = AddrModeFlat;
#elif defined _M_IA64
	#error not supported
	machineType = IMAGE_FILE_MACHINE_IA64;
	stack.AddrPC.Offset = context.StIIP;
	stack.AddrPC.Mode = AddrModeFlat;
	stack.AddrFrame.Offset = context.IntSp;
	stack.AddrFrame.Mode = AddrModeFlat;
	stack.AddrBStore.Offset = context.RsBSP;
	stack.AddrBStore.Mode = AddrModeFlat;
	stack.AddrStack.Offset = context.IntSp;
	stack.AddrStack.Mode = AddrModeFlat;
#else
	#error not supported
	machineType = IMAGE_FILE_MACHINE_I386;
	stack.AddrPC.Offset = context.Eip;
	stack.AddrPC.Mode = AddrModeFlat;
	stack.AddrStack.Offset = context.Esp;
	stack.AddrStack.Mode = AddrModeFlat;
	stack.AddrFrame.Offset = context.Ebp;
	stack.AddrFrame.Mode = AddrModeFlat;
#endif

	do
	{
		result = StackWalk64(machineType,
			process,
			thread,
			&stack,
			&context,
			NULL,
			SymFunctionTableAccess64,
			SymGetModuleBase64,
			NULL);

		symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64);
		symbol->MaxNameLength = 255;

		BOOL sybol_valid = SymGetSymFromAddr64(process, (ULONG64)stack.AddrPC.Offset, &displacement, symbol);
		auto err = GetLastError();
		DWORD num_char = UnDecorateSymbolName(symbol->Name, (PSTR)name, 256, UNDNAME_COMPLETE);

		if (!catString(out, symbol->Name)) return;
		if (!catString(out, "\n")) return;

	} while (result);
}

static LONG WINAPI unhandledExceptionHandler(LPEXCEPTION_POINTERS info)
{
	if (!g_is_crash_reporting_enabled) return EXCEPTION_CONTINUE_SEARCH;

	HANDLE process = GetCurrentProcess();
	SymInitialize(process, nullptr, TRUE);
	debug::StackTree::refreshModuleList();

	struct CrashInfo
	{
		LPEXCEPTION_POINTERS info;
		DWORD thread_id;
	};

	auto dumper = [](void* data) -> DWORD {
		LPEXCEPTION_POINTERS info = ((CrashInfo*)data)->info;
		uintptr base = (uintptr)GetModuleHandle(NULL);
		StaticString<4096> message;
		if(info)
		{
			getStack(*info->ContextRecord, Span(message.data));
			message << "\nCode: " << (u32)info->ExceptionRecord->ExceptionCode;
			message << "\nAddress: " << (uintptr)info->ExceptionRecord->ExceptionAddress;
			message << "\nBase: " << (uintptr)base;
			os::messageBox(message);
		}
		else
		{
			message.data[0] = '\0';
		}

		char minidump_path[LUMIX_MAX_PATH];
		GetCurrentDirectory(sizeof(minidump_path), minidump_path);
		catString(minidump_path, "\\minidump.dmp");

		HANDLE process = GetCurrentProcess();
		DWORD process_id = GetProcessId(process);
		HANDLE file = CreateFile(
			minidump_path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
		MINIDUMP_TYPE minidump_type = (MINIDUMP_TYPE)(
			MiniDumpWithFullMemoryInfo | MiniDumpFilterMemory | MiniDumpWithHandleData |
			MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules);

		MINIDUMP_EXCEPTION_INFORMATION minidump_exception_info;
		minidump_exception_info.ThreadId = ((CrashInfo*)data)->thread_id;
		minidump_exception_info.ExceptionPointers = info;
		minidump_exception_info.ClientPointers = FALSE;

		MiniDumpWriteDump(process,
			process_id,
			file,
			minidump_type,
			info ? &minidump_exception_info : nullptr,
			nullptr,
			nullptr);
		CloseHandle(file);

		minidump_type = (MINIDUMP_TYPE)(MiniDumpWithFullMemory | MiniDumpWithFullMemoryInfo |
			MiniDumpFilterMemory | MiniDumpWithHandleData |
			MiniDumpWithThreadInfo | MiniDumpWithUnloadedModules);
		file = CreateFile(
			"fulldump.dmp", GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
		MiniDumpWriteDump(process,
			process_id,
			file,
			minidump_type,
			info ? &minidump_exception_info : nullptr,
			nullptr,
			nullptr);

		CloseHandle(file);

		SendFile("Lumix Studio crash",
			"SMTP:mikulas.florek@gamedev.sk",
			"Lumix Studio",
			message,
			minidump_path);
		return 0;
	};

	DWORD thread_id;
	CrashInfo crash_info = { info, GetCurrentThreadId() };
	auto handle = CreateThread(0, 0x8000, dumper, &crash_info, 0, &thread_id);
	WaitForSingleObject(handle, INFINITE);

	StaticString<4096> message;
	getStack(*info->ContextRecord, Span(message.data));
	logError(message);

	return EXCEPTION_CONTINUE_SEARCH;
}

void enableCrashReporting(bool enable)
{
	g_is_crash_reporting_enabled = enable;
}

void installUnhandledExceptionHandler()
{
	SetUnhandledExceptionFilter(unhandledExceptionHandler);
}

} // namespace Lumix


text:
'''module for heronpy streamlet API'''
__import__('pkg_resources').declare_namespace(__name__)


text:
from socket import *

# Message to send
msg = '\r\nI love computer networks!'
endmsg = '\r\n.\r\n'

# Choose a mail server (e.g. Google mail server) and call it mailserver
mailserver = 'smtp.gmail.com'

# Create socket called clientSocket and establish a TCP connection with mailserver
clientSocket = socket(AF_INET, SOCK_STREAM)

# Port number may change according to the mail server
clientSocket.connect((mailserver, 587))
recv = clientSocket.recv(1024).decode()
print(recv)
if recv[:3] != '220':
	print('220 reply not received from server.')

# Send HELO command and print server response.
heloCommand = 'HELO gmail.com\r\n'
clientSocket.send(heloCommand.encode())
recv1 = clientSocket.recv(1024).decode()
print(recv1)
if recv1[:3] != '250':
	print('250 reply not received from server.')

# Send MAIL FROM command and print server response.
mailfrom = 'MAIL FROM: <alice@gmail.com>\r\n'
clientSocket.send(mailfrom.encode())
recv2 = clientSocket.recv(1024).decode()
print(recv2)
if recv2[:3] != '250':
	print('250 reply not received from server.')

# Send RCPT TO command and print server response.
rcptto = 'RCPT TO: <bob@yahoo.com>\r\n'
clientSocket.send(rcptto.encode())
recv3 = clientSocket.recv(1024).decode()
print(recv3)
if recv3[:3] != '250':
	print('250 reply not received from server.')

# Send DATA command and print server response.
data = 'DATA\r\n'
clientSocket.send(data.encode())
recv4 = clientSocket.recv(1024).decode()
print(recv4)
if recv4[:3] != '354':
	print('354 reply not received from server.')

# Send message data.
clientSocket.send('SUBJECT: Greeting To you!\r\n'.encode())
clientSocket.send('test again'.encode())
clientSocket.send(msg.encode())

# Message ends with a single period.
clientSocket.send(endmsg.encode())
recv5 = clientSocket.recv(1024).decode()
print(recv5)
if recv5[:3] != '250':
	print('250 reply not received from server.')

# Send QUIT command and get server response.
quitcommand = 'QUIT\r\n'
clientSocket.send(quitcommand.encode())
recv6 = clientSocket.recv(1024).decode()
print(recv6)
if recv6[:3] != '221':
	print('221 reply not received from server.')


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
<title>Óñòàíîâêà » DLE » engine/modules/sitelogin.php » KALIOSTRO.NET</title>
<link href="../../css/style.css" rel="stylesheet" type="text/css" />

			DLE + vBulletin v2.2.0

        	Óñòàíîâêà » DLE » engine/modules/sitelogin.php

		1. Ïîäêëþ÷àåì è èíèöèàëèçèðóåì èíòåãðàöèþ

		Íàéòè (20):

		<textarea cols="auto" rows="3" class="find" readonly="readonly">if( ! defined( 'DATALIFEENGINE' ) ) {
    die( "Hacking attempt!" );
}</textarea>
		Íèæå äîáàâèòü :

		<textarea cols="auto" rows="4" class="add" readonly="readonly">/* ----------- DLE + vBulletin v2.2.0 ----------- */
require_once ENGINE_DIR . '/modules/dle_vs_vb.php';
$vb = new vBIntegration($db);
/* ----------- DLE + vBulletin v2.2.0 ----------- */</textarea>

		2. Âûõîäèì èç ôîðóìà

		Íàéòè (30):

		<textarea cols="auto" rows="1" class="find" readonly="readonly">if (isset($_REQUEST['action']) AND $_REQUEST['action'] == "logout") { </textarea>
		Íèæå äîáàâèòü :

		<textarea cols="auto" rows="3" class="add" readonly="readonly">/* ----------- DLE + vBulletin v2.2.0 ----------- */
$vb->Logout();
/* ----------- DLE + vBulletin v2.2.0 ----------- */</textarea>

		3. Âõîäèì íà ôîðóì

		Íàéòè (194):

		<textarea cols="auto" rows="1" class="find" readonly="readonly">?> </textarea>
		Äî âñòàâèòü :

		<textarea cols="auto" rows="3" class="addbefore" readonly="readonly">/* ----------- DLE + vBulletin v2.2.0 ----------- */
$vb->Login($member_id);
/* ----------- DLE + vBulletin v2.2.0 ----------- */</textarea>

Copyright © 2007 - 2011 kaliostro . All rights reserved.


text:
import {Graph} from '../../../graph';
import {OperatorImplementation, OperatorInitialization} from '../../../operators';
import {Tensor} from '../../../tensor';
import {ProtoUtil} from '../../../util';
import {WebGLInferenceHandler} from '../inference-handler';

export const cast: OperatorImplementation<Tensor.DataType> =
    (handler: WebGLInferenceHandler, inputs: Tensor[], to: Tensor.DataType): Tensor[] => {
      validateInputs(inputs);
      return [handler.cast(inputs[0], to)];
    };

export const parseCastAttributes: OperatorInitialization<Tensor.DataType> = (node: Graph.Node): Tensor.DataType =>
    ProtoUtil.tensorDataTypeFromProto(node.attributes.getInt('to'));

const validateInputs = (inputs: Tensor[]): void => {
  if (!inputs || inputs.length !== 1) {
    throw new Error('Cast requires 1 input.');
  }

  if (inputs[0].type === 'string') {
    throw new Error('Invalid input type.');
  }
};


text:
ParticleRenderer::ParticleRenderer(Shader* shader) : Renderer::Renderer(shader)
{
	// Generate and bind the VAO
	glGenVertexArrays(1, &VAO);
	glBindVertexArray(VAO);

	// Generate and bind the VBO
	glGenBuffers(1, &VBO_position);
	glBindBuffer(GL_ARRAY_BUFFER, VBO_position);

	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(glm::vec4), (GLvoid*)0);
	GLfloat vertices[]{
		-0.5f, -0.5f, 0.0f, 0.0f,// lower left
		0.5f, -0.5f, 1.0f, 0.0f,// lower right
		0.5f, 0.5f, 1.0f, 1.0f,// upper right
		-0.5f, 0.5f, 0.0f, 1.0f // upper left
	};
	glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
	// Generate and bind the VBO
	glGenBuffers(1, &EBO_position);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO_position);
	GLuint indices[] = {
		0, 1, 3,
		1, 2, 3,
	};
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

	// Generate and bind the VBO
	glGenBuffers(1, &VBO_particleData);
	glBindBuffer(GL_ARRAY_BUFFER, VBO_particleData);
	// Set attribute pointer for the position
	glEnableVertexAttribArray(1);// TextureID
	glEnableVertexAttribArray(2);// Color
	glEnableVertexAttribArray(3);// matrix part1
	glEnableVertexAttribArray(4);// matrix part2
	glEnableVertexAttribArray(5);// matrix part3
	glEnableVertexAttribArray(6);// matrix part4

	glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(offsetof(ParticleData, ParticleData::textureID)));
	glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(offsetof(ParticleData, ParticleData::color)));
	glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(offsetof(ParticleData, ParticleData::model) + (0 * sizeof(glm::vec4))));
	glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(offsetof(ParticleData, ParticleData::model) + (1 * sizeof(glm::vec4))));
	glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(offsetof(ParticleData, ParticleData::model) + (2 * sizeof(glm::vec4))));
	glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleData), (GLvoid*)(offsetof(ParticleData, ParticleData::model) + (3 * sizeof(glm::vec4))));

	glVertexAttribDivisor(1, 1);
	glVertexAttribDivisor(2, 1);
	glVertexAttribDivisor(3, 1);
	glVertexAttribDivisor(4, 1);
	glVertexAttribDivisor(5, 1);
	glVertexAttribDivisor(6, 1);

	// Unbind the VAO and VBO
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);
	// Fill the activeTextureArray
	for (int i = 0; i < 32; i++) {
		activeTextureArray[i] = i;
	}
}

ParticleRenderer::~ParticleRenderer()
{
	// Delete all allocated memory
	glDeleteVertexArrays(1, &VAO);
	glDeleteBuffers(1, &VBO_position);
	glDeleteBuffers(1, &EBO_position);
	glDeleteBuffers(1, &VBO_particleData);
}

void ParticleRenderer::Submit(Particle particle)
{
	// Set particle texture ID
	int id = 0;
	if (particle.textureID > 0) {
		bool found = false;
		for (; id < textureSlots.size(); id++) {
			if (particle.textureID == textureSlots[id]) {
				found = true;
				break;
			}
		}
		if (found == false) {
			if (textureSlots.size() == 32) {
				// TODO: Make a fix so that there can be more than 32 textures
				std::cout << "above 32 textures! " << std::endl;
			}
			textureSlots.push_back(particle.textureID);
		}
	}
	else {
		id = -1;
	}
	// Create the model matrix of the particle
	glm::mat4 model;
	model = glm::translate(model, glm::vec3(particle.position.x, particle.position.y, 0.0f));
	model = glm::rotate(model, particle.angle, glm::vec3(0.0f, 0.0f, 1.0f));
	model = glm::scale(model, glm::vec3(particle.width, particle.height, 0.0f));
	// Set the particle data
	ParticleData pd;
	pd.textureID = (GLfloat(id) + 1.0f);
	pd.color = particle.color;
	pd.model = model;
	particleData.push_back(pd);
}

void ParticleRenderer::Render(Camera * camera)
{
	// If there is nothing to draw
	if (particleData.size() == 0) { return; };

	shader->Use();
	shader->SetMatrix4("projection", camera->GetProjectionMatrix());
	shader->SetMatrix4("view", camera->GetViewMatrix());
	shader->SetIntArray("textures", activeTextureArray, 32);

	// Bind the VAO
	glBindVertexArray(VAO);

	for (int i = 0; i < textureSlots.size(); i++) {
		glActiveTexture(GL_TEXTURE0 + i);
		glBindTexture(GL_TEXTURE_2D, textureSlots[i]);
	}

	// Fill all of the buffers with their data
	glBindBuffer(GL_ARRAY_BUFFER, VBO_particleData);
	glBufferData(GL_ARRAY_BUFFER, particleData.size() * sizeof(ParticleData), &particleData[0], GL_DYNAMIC_DRAW);

	// Unbind the buffer
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	// draw elements
	glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0, particleData.size());

	// Unbind the VAO and texture
	glBindVertexArray(0);
	glBindTexture(GL_TEXTURE_2D, 0);

	// Clear all of the data
	particleData.clear();
	textureSlots.clear();
}


text:
  Bologne est
      une ville située dans le département de Haute-Marne en Champagne-Ardenne. Elle totalisait 1 849 habitants en 2008.

À Bologne, la valorisation moyenne à l'achat d'un appartement s'évalue à 1 035 € du m² en vente. Le prix moyen d'une maison à l'achat se situe à 895 € du m². À la location la valeur moyenne se situe à 5,82 € du m² mensuel.

À proximité de Bologne sont situées les villes de
Riaucourt localisée à 2 km, 478 habitants,
Viéville située à 4 km, 307 habitants,
Briaucourt située à 3 km, 197 habitants,
Annéville-la-Prairie située à 4 km, 72 habitants,
Brethenay localisée à 5 km, 386 habitants,
Vraincourt localisée à 4 km, 95 habitants,
 entre autres. De plus, Bologne est située à seulement dix km de Chaumont.

La commune propose de nombreux  équipements sportifs, elle dispose, entre autres, de un bassin de natation, trois terrains de tennis, deux terrains de sport et deux boucles de randonnée.

Le nombre d'habitations, à Bologne, était réparti en 2011 en 246 appartements et 735 maisons soit
 un marché relativement équilibré.


text:
'use strict';

const path = require('path');
const config = require('./config.js');
const sh = require('shelljs');
const tools = require('@singpath/tools');

sh.set('-e');

sh.echo(`NOTICE:

  Make sure to update JSPM to version "^0.17.0-beta.25".

  To update, reinstall all dependencies:

      rm -rf node_modules/ src/jspm_packages/ && npm install

  The build might freeze if you only update JSPM.

`);

// setup
tools.clean(config.build.root);
sh.echo(`Setting up "${config.build.app.root}/"...`);
sh.mkdir('-p', config.build.app.root);
sh.cp('-r', 'LICENSE', 'tools/assets/*', config.build.app.root);
sh.cp('HOSTING.md', path.join(config.build.app.root, 'README.md'));
sh.cp('database/security-rules.json', path.join(config.build.app.root, 'rules.json'));
sh.cp('database/data/init.json', path.join(config.build.app.root, 'data.json'));

// Bundles
const cmd = [
  'jspm build',
  `${config.build.app.main} - ${config.build.app.deps.names.join(' - ')}`
].join(' ');
const umdOpts = [
  '--format umd',
  `--global-name "${config.build.app.name}"`,
  `--global-deps '${JSON.stringify(config.build.app.deps.map)}'`
].join(' ');

sh.echo(`Buidling ${config.build.app.js}...`);
tools.exec(`${cmd} "${config.build.app.js}" ${umdOpts} --skip-source-maps`);

sh.echo(`Buidling ${config.build.app.minJs}...`);
tools.exec(`${cmd} "${config.build.app.minJs}" ${umdOpts} --minify`);

// Dependency tree
//
// You don't want the browser to load the source map file
// (the source map is often as big as the bundle).
// So we are stripping the source map directive in the bundle
// by stripping the last line.
sh.echo(`Removing source map directive from ${config.build.app.minJs}...`);
sh.sed('-i', /^\/\/# sourceMappingURL=.*$/, '', config.build.app.minJs);

sh.echo(`Analysing source map using ${config.build.app.minJs}...`);
tools.execPipe(
  `source-map-explorer --html "${config.build.app.minJs}" "${config.build.app.minJs}.map"`,
  {stdout: config.build.app.tree}
);

sh.echo(`open "${config.build.app.tree}" to find weight of each modules.`);

// Archive
sh.echo(`Creating archive in "${config.build.archive}".`);
tools.zip(config.build.app.root, config.build.archive).then(() => sh.echo('Archive created.'));


text:
=====================================================
Mapbox: The Mapbox Platform client library for Python
=====================================================

.. image:: https://travis-ci.org/mapbox/mapbox-sdk-py.png?branch=master
   :target: https://travis-ci.org/mapbox/mapbox-sdk-py

.. image:: https://coveralls.io/repos/mapbox/mapbox-sdk-py/badge.png
   :target: https://coveralls.io/r/mapbox/mapbox-sdk-py

A Python client for Mapbox web services

The Mapbox Python SDK is a low-level client API, not a Resource API such as the ones in `boto3 <http://aws.amazon.com/sdk-for-python/>`__ or `github3.py <https://github3py.readthedocs.org/en/master/>`__. Its methods return objects containing `HTTP responses <http://docs.python-requests.org/en/latest/api/#requests.Response>`__ from the Mapbox API.

Services
========

- **Analytics V1** `examples <./analytics.html>`__, `website <https://www.mapbox.com/api-documentation/accounts/#analytics>`__

  - API usage for services by resource.
  - available for premium and enterprise plans.

- **Directions V4** `examples <./directions.html#directions>`__, `website <https://www.mapbox.com/api-documentation/navigation/#directions>`__

  - Profiles for driving, walking, and cycling
  - GeoJSON & Polyline formatting
  - Instructions as text or HTML

- **Geocoding V5** `examples <./geocoding.html#geocoding>`__, `website <https://www.mapbox.com/api-documentation/search/#geocoding>`__

  - Forward (place names ⇢ longitude, latitude)
  - Reverse (longitude, latitude ⇢ place names)

- **Map Matching V4** `examples <./mapmatching.html#map-matching>`__, `website <https://www.mapbox.com/api-documentation/navigation/#map-matching>`__

  - Snap GPS traces to OpenStreetMap data

- **Static Maps V4** `examples <./static.html#static-maps>`__, `website <https://www.mapbox.com/api-documentation/legacy/static-classic>`__

  - Generate standalone images from existing Mapbox *mapids* (tilesets)
  - Render with GeoJSON overlays

- **Static Styles V1** `examples <./static.html#static-maps>`__, `website <https://www.mapbox.com/api-documentation/maps/#static>`__

  - Generate standalone images from existing Mapbox *styles*
  - Render with GeoJSON overlays
  - Adjust pitch and bearing, decimal zoom levels

- **Surface V4** **DEPRECATED**

- **Uploads V1** `examples <./uploads.html#uploads>`__, `website <https://www.mapbox.com/api-documentation/maps/#uploads>`__

  - Upload data to be processed and hosted by Mapbox.

- **Datasets V1** `examples <./datasets.html#datasets>`__, `website <https://www.mapbox.com/api-documentation/maps/#datasets>`__

  - Manage editable collections of GeoJSON features
  - Persistent storage for custom geographic data

- **Tilequery V4** `examples <./tilequery.html#tilequery>`__, `website <https://www.mapbox.com/api-documentation/maps/#tilequery>`__

  - Retrieve data about specific features from a vector tileset

- **Maps V4** `examples <./maps.html#maps>`__, `website <https://www.mapbox.com/api-documentation/maps/#maps>`__

  - Retrieve an image tile, vector tile, or UTFGrid in the specified format
  - Retrieve vector features from Mapbox Editor projects as GeoJSON or KML
  - Retrieve TileJSON metadata for a tileset
  - Retrieve a single marker image without any background map

Please note that there may be some lag between the release of new Mapbox web
services and releases of this package.

Installation
============

.. code:: bash

    $ pip install mapbox

Testing
=======

.. code:: bash

    $ pip install -e .[test]
    $ python -m pytest

To run the examples as integration tests on your own Mapbox account

.. code:: bash

    $ MAPBOX_ACCESS_TOKEN="MY_ACCESS_TOKEN" python -m pytest --doctest-glob='*.md' docs/*.md

See Also
========

* Command line interface: https://github.com/mapbox/mapbox-cli-py
* Javascript SDK: https://github.com/mapbox/mapbox-sdk-js

Documentation
=============

.. toctree::
   :maxdepth: 1

   access_tokens.md
   datasets.md
   geocoding.md
   matrix.md
   directions.md
   input_features.md
   static.md
   uploads.md
   analytics.md
   mapmatching.md
   static_style.md
   tilequery.md
   maps.md
   api/mapbox.rst
   api/mapbox.services.rst
   api/modules.rst

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`


text:
import DS from 'ember-data';

var Task = DS.Model.extend({
   description: DS.attr('string'),
   complete: DS.attr('boolean')
});

export default Task;


text:
<style is="custom-style">

  body {
    @apply(--paper-font-common-base);
  }

  .gray {
    color: var(--paper-grey-800);
  }

  iron-icon.error {
    color: var(--paper-red-500);
  }

  paper-toolbar paper-input {
    --paper-input-container-color: white;
    --paper-input-container-focus-color: white;
    --paper-input-container-invalid-color: green;
    --paper-input-container-input-color: white;
  }

  .loading-spinner {
    --iron-icon-height: 72px;
    --iron-icon-width: 72px;
  }

  paper-toast.error {
    --paper-toast-color: #F44336;
  }

  div.error iron-icon {
    --iron-icon-height: 72px;
    --iron-icon-width: 72px;
  }

</style>


text:
{% block header_wrapper %}
{% block header_account %}

      {% if c.userobj %}

            {% block header_account_logged %}
            {% if c.userobj.sysadmin %}

            {% endif %}

                {{ h.gravatar((c.userobj.email_hash if c and c.userobj else ''), size=22) }}
                {{ c.userobj.display_name }}

            {% set new_activities = h.new_activities() %}

 0 %}notifications-important{% endif %}">
              {% set notifications_tooltip = ngettext('Dashboard (%(num)d new item)', 'Dashboard (%(num)d new items)', new_activities) %}

                {{ new_activities }}

            {% block header_account_settings_link %}

            {% endblock %}
            {% block header_account_log_out_link %}

            {% endblock %}
            {% endblock %}

      {% else %}

            {% block header_account_notlogged %}

{% link_for _('Log in'), controller='user', action='login' %}

            {% if h.check_access('site_read') %}

{% link_for _('Register'), controller='user', action='register', class_='sub' %}

            {% endif %}
            {% endblock %}

      {% endif %}

{% endblock %}

  {% block header_debug %}
  {% if g.debug and not g.debug_supress_header %}

Controller : {{ c.controller }}
Action : {{ c.action }}

  {% endif %}
  {% endblock %}

    {# The .header-image class hides the main text and uses image replacement for the title #}
    <hgroup class="{{ g.header_class }}">

      {% block header_logo %}
        {% if g.site_logo %}

        {% else %}

            {{ g.site_title }}

          {% if g.site_description %}
{{ g.site_description }}
{% endif %}
        {% endif %}
      {% endblock %}

    </hgroup>

      {% block header_site_navigation %}

            {% block header_site_navigation_tabs %}
              {% if h.check_access('site_read') %}
                {{ h.build_nav_main(
                  ('search', _('Datasets')),
                  ('organizations_index', _('Organizations')),
                  ('group_index', _('Groups')),
                  ('about', _('About'))
                ) }}
              {% else %}
                {{ h.build_nav_main(
                  ('about', _('About'))
                ) }}
              {% endif %}
            {% endblock %}

      {% endblock %}

      {% block header_site_search %}
        {% if h.check_access('site_read') %}
          <form class="section site-search simple-input" action="{% url_for controller='package', action='search' %}" method="get">

              {{ _('Search Datasets') }}
              <input id="field-sitewide-search" type="text" name="q" placeholder="{{ _('Search') }}" />
              <button class="btn-search" type="submit">{{ _('Search') }}</button>

          </form>
        {% endif %}
      {% endblock %}

{% endblock %}


text:
define(['jquery', 'sweetAlert', 'select2', 'listItems'], function(
  $, sweetAlert, select2, EffecktListItems) {
  function createTopic() {
    if (!(this instanceof createTopic)) {
      return new createTopic();
    }
    this.$inner = $('.textarea-wrapper');
    this.$outer = $('.preview-wrapper');
    this.$modal = $('#reply-control');

    this._init();
  }

  createTopic.prototype = {
    constructor: createTopic,
    _init: function() {
      var _this = this;
      this.$toggleDiv = $('.toggle-preview');
      this.$cancel = $('.cancel');
      this.$toggler = $('.toggler');
      this.$createButton = $('.create');

      this.$toggleDiv.click(function(e) {
        _this.previewToggle();
      });

      this.$toggler.click(function(e) {
        e.preventDefault();
        _this.closeModal();
      });

      this.$cancel.click(function(e) {
        _this.closeModal();
      });

      this.$createButton.click(function(e) {
        _this.create();
      });

      _this.initCategories();
    },

    initCategories: function() {
      $("select.category-combobox").select2({
        placeholder: 'Categories...',
        ajax: {
          url: '/api/categories',
          dataType: 'json',
          delay: 0,
          data: function (params) {
            return {name: params.term}
          },
          processResults: function (data, params) {
            var result = {results: []};
            if (!data.status) {
              result.results = data.categories;
            }
            return result;
          },
          cache: true
        },
        escapeMarkup: function (markup) { return markup; },
        minimumInputLength: 0,
        templateResult: function (category) {
          if (!category.name) { return 'Loading...'; }
          var markup = '
' + category.name;
          if (category.description) {
            markup += '
' + category.description;
          }
          markup += '
';
          return $(markup)
        },
        templateSelection: function (category) {
          return category.name;
        }
      });
    },

    closeModal: function(){
      this.$modal.addClass('hide');
    },

    openModal: function(callback){
      this.$modal.removeClass('hide');
      if (typeof callback !== 'undefined') {
        callback();
      }
    },

    previewToggle: function(){
      this.$modal.toggleClass('hide-preview');
      if (this.$modal.hasClass('hide-preview') === true) {
        this.$toggleDiv.html('显示预览 »');
      } else {
        this.$toggleDiv.html('« 关闭预览');
      }
    },

    create : function(){
      var title = $('#reply-title').val();
      var _this = this;
      var params, content = [];
      var category = $('#reply-category').val();
      var items = EffecktListItems();

      $('.CodeMirror-code pre span[style]').each(
        function () {
          var text = $(this).text();
          content.push(text);
        }
      );

      if (!title.length) {
        sweetAlert({
          title: "标题没有内容",
          type: "error"
        });
        return
      }
      if (!(category && category.length)) {
        sweetAlert({
          title: "请选择分类",
          type: "error"
        });
        return
      }
      if (!content.length) {
        sweetAlert({
          title: "正文内容太少",
          type: "error"
        });
        return
      }
      params = {
        'title': title,
        'content': content.join('\n'),
        'category': category
      };
      $.ajax({
        type: 'POST',
        url: '/create',
        traditional: true,
        data: params,
        dataType: "json",
        success: function(res) {
          if (!res.ok) {
            _this.closeModal();
            items.addListItem(res.html, $('.topic-list-item:first'));
          }
        }
      });
    }
  };
  return createTopic;
});


text:
#include <folly/io/IOBuf.h>
#include <quic/server/handshake/TokenGenerator.h>

#include <folly/Range.h>
#include <quic/codec/Decode.h>

namespace {

const std::vector<std::string> kCipherContexts = {"RetryToken_V2"};

} // namespace

namespace quic {

TokenGenerator::TokenGenerator(TokenSecret secret) : cipher_(kCipherContexts) {
  std::vector<folly::ByteRange> secrets;
  secrets.emplace_back(folly::range(secret));
  cipher_.setSecrets(secrets);
}

folly::Optional<Buf> TokenGenerator::encryptToken(
    const QuicAddrValidationToken& token) {
  // Generate the retry token in plaintext
  auto plainTextToken = token.getPlaintextToken();

  // Try to encrypt it
  auto maybeEncryptedToken = cipher_.encrypt(
      std::move(plainTextToken), token.genAeadAssocData().get());
  if (!maybeEncryptedToken) {
    LOG(ERROR) << "Failed to encypt addr validation token with IP "
               << token.clientIp.str();
  }

  // If the encryption failed, this will be empty optional
  return maybeEncryptedToken;
}

uint64_t TokenGenerator::decryptToken(Buf encryptedToken, Buf aeadAssocData) {
  auto maybeDecryptedToken =
      cipher_.decrypt(std::move(encryptedToken), aeadAssocData.get());

  if (!maybeDecryptedToken) {
    return 0;
  }

  // Try to parse the decrypted token
  auto decryptedToken = (*maybeDecryptedToken).get();
  folly::io::Cursor cursor(decryptedToken);

  auto parseResult = parsePlaintextRetryOrNewToken(cursor);

  if (parseResult.hasError()) {
    LOG(ERROR) << "Failed to parse decrypted retry token";
    return 0;
  }

  return parseResult.value();
}

} // namespace quic


text:
package org.apache.hadoop.mapred;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;

/**
 * Class that contains the information regarding the Job Queues which are
 * maintained by the Hadoop Map/Reduce framework.
 *
 */

public class JobQueueInfo implements Writable {

  private String queueName = "";
  //The scheduling Information object is read back as String.
  //Once the scheduling information is set there is no way to recover it.
  private String schedulingInfo;

  /**
   * Default constructor for Job Queue Info.
   *
   */
  public JobQueueInfo() {

  }
  /**
   * Construct a new JobQueueInfo object using the queue name and the
   * scheduling information passed.
   *
   * @param queueName Name of the job queue
   * @param schedulingInfo Scheduling Information associated with the job
   * queue
   */
  public JobQueueInfo(String queueName, String schedulingInfo) {
    this.queueName = queueName;
    this.schedulingInfo = schedulingInfo;
  }

  /**
   * Set the queue name of the JobQueueInfo
   *
   * @param queueName Name of the job queue.
   */
  public void setQueueName(String queueName) {
    this.queueName = queueName;
  }

  /**
   * Get the queue name from JobQueueInfo
   *
   * @return queue name
   */
  public String getQueueName() {
    return queueName;
  }

  /**
   * Set the scheduling information associated to particular job queue
   *
   * @param schedulingInfo
   */
  public void setSchedulingInfo(String schedulingInfo) {
    this.schedulingInfo = schedulingInfo;
  }

  /**
   * Gets the scheduling information associated to particular job queue.
   * If nothing is set would return <b>"N/A"</b>
   *
   * @return Scheduling information associated to particular Job Queue
   */
  public String getSchedulingInfo() {
    if(schedulingInfo != null) {
      return schedulingInfo;
    }else {
      return "N/A";
    }
  }

  public void readFields(DataInput in) throws IOException {
    queueName = Text.readString(in);
    schedulingInfo = Text.readString(in);
  }

  public void write(DataOutput out) throws IOException {
    Text.writeString(out, queueName);
    if(schedulingInfo!= null) {
      Text.writeString(out, schedulingInfo);
    }else {
      Text.writeString(out, "N/A");
    }
  }
}


text:
extern crate regex;

#[cfg(feature = "heavyweight")]
#[macro_use] extern crate lazy_static;

/// Provides case inflections
/// - Camel case
/// - Class case
/// - Kebab case
/// - Train case
/// - Screaming snake case
/// - Table case
/// - Sentence case
/// - Snake case
/// - Pascal case
pub mod cases;
/// Provides number inflections
/// - Ordinalize
/// - Deordinalize
pub mod numbers;
/// Provides suffix inflections
/// - Foreign key
pub mod suffix;
/// Provides string inflections
/// - Deconstantize
/// - Demodulize
/// - Pluralize
/// - Singularize
#[cfg(feature = "heavyweight")]
pub mod string;

#[cfg(feature = "heavyweight")]
use cases::classcase::to_class_case;
#[cfg(feature = "heavyweight")]
use cases::classcase::is_class_case;

use cases::camelcase::to_camel_case;
use cases::camelcase::is_camel_case;

use cases::pascalcase::to_pascal_case;
use cases::pascalcase::is_pascal_case;

use cases::snakecase::to_snake_case;
use cases::snakecase::is_snake_case;

use cases::screamingsnakecase::to_screaming_snake_case;
use cases::screamingsnakecase::is_screaming_snake_case;

use cases::kebabcase::to_kebab_case;
use cases::kebabcase::is_kebab_case;

use cases::traincase::to_train_case;
use cases::traincase::is_train_case;

use cases::sentencecase::to_sentence_case;
use cases::sentencecase::is_sentence_case;

use cases::titlecase::to_title_case;
use cases::titlecase::is_title_case;

#[cfg(feature = "heavyweight")]
use cases::tablecase::to_table_case;
#[cfg(feature = "heavyweight")]
use cases::tablecase::is_table_case;

use numbers::ordinalize::ordinalize;
use numbers::deordinalize::deordinalize;

use suffix::foreignkey::to_foreign_key;
use suffix::foreignkey::is_foreign_key;

#[cfg(feature = "heavyweight")]
use string::demodulize::demodulize;
#[cfg(feature = "heavyweight")]
use string::deconstantize::deconstantize;

#[cfg(feature = "heavyweight")]
use string::pluralize::to_plural;
#[cfg(feature = "heavyweight")]
use string::singularize::to_singular;

#[allow(missing_docs)]
pub trait Inflector {

    fn to_camel_case(&self) -> String;
    fn is_camel_case(&self) -> bool;

    fn to_pascal_case(&self) -> String;
    fn is_pascal_case(&self) -> bool;

    fn to_snake_case(&self) -> String;
    fn is_snake_case(&self) -> bool;

    fn to_screaming_snake_case(&self) -> String;
    fn is_screaming_snake_case(&self) -> bool;

    fn to_kebab_case(&self) -> String;
    fn is_kebab_case(&self) -> bool;

    fn to_train_case(&self) -> String;
    fn is_train_case(&self) -> bool;

    fn to_sentence_case(&self) -> String;
    fn is_sentence_case(&self) -> bool;

    fn to_title_case(&self) -> String;
    fn is_title_case(&self) -> bool;

    fn ordinalize(&self) -> String;
    fn deordinalize(&self) -> String;

    fn to_foreign_key(&self) -> String;
    fn is_foreign_key(&self) -> bool;

    #[cfg(feature = "heavyweight")]
    fn demodulize(&self) -> String;
    #[cfg(feature = "heavyweight")]
    fn deconstantize(&self) -> String;

    #[cfg(feature = "heavyweight")]
    fn to_class_case(&self) -> String;
    #[cfg(feature = "heavyweight")]
    fn is_class_case(&self) -> bool;

    #[cfg(feature = "heavyweight")]
    fn to_table_case(&self) -> String;
    #[cfg(feature = "heavyweight")]
    fn is_table_case(&self) -> bool;
    #[cfg(feature = "heavyweight")]
    fn to_plural(&self) -> String;
    #[cfg(feature = "heavyweight")]
    fn to_singular(&self) -> String;
}

#[allow(missing_docs)]
pub trait InflectorNumbers {
    fn ordinalize(&self) -> String;
}

macro_rules! define_implementations {
    ( $slf:ident; $($imp_trait:ident => $typ:ident), *) => {
        $(
            #[inline]
            fn $imp_trait(&$slf) -> $typ {
                $imp_trait($slf)
            }
        )*
    }
}

macro_rules! define_number_implementations {
    ( $slf:ident; $($imp_trait:ident => $typ:ident), *) => {
        $(
            #[inline]
            fn $imp_trait(&$slf) -> $typ {
                $imp_trait(&$slf.to_string())
            }
        )*
    }
}

macro_rules! define_gated_implementations {
    ( $slf:ident; $($imp_trait:ident => $typ:ident), *) => {
        $(
            #[inline]
            #[cfg(feature = "heavyweight")]
            fn $imp_trait(&$slf) -> $typ {
                $imp_trait($slf)
            }
        )*
    }
}

macro_rules! implement_string_for {
    ( $trt:ident; $($typ:ident), *) => {
        $(
            impl $trt for $typ {
                define_implementations![self;
                    to_camel_case => String,
                    is_camel_case => bool,
                    to_pascal_case => String,
                    is_pascal_case => bool,
                    to_screaming_snake_case => String,
                    is_screaming_snake_case => bool,
                    to_snake_case => String,
                    is_snake_case => bool,
                    to_kebab_case => String,
                    is_kebab_case => bool,
                    to_train_case => String,
                    is_train_case => bool,
                    to_sentence_case => String,
                    is_sentence_case => bool,
                    to_title_case => String,
                    is_title_case => bool,
                    to_foreign_key => String,
                    is_foreign_key => bool,
                    ordinalize => String,
                    deordinalize => String
                ];
                define_gated_implementations![self;
                    to_class_case => String,
                    is_class_case => bool,
                    to_table_case => String,
                    is_table_case => bool,
                    to_plural => String,
                    to_singular => String,
                    demodulize => String,
                    deconstantize => String
                ];
            }
        )*
    }
}

macro_rules! implement_number_for {
    ( $trt:ident; $($typ:ident), *) => {
        $(
            impl $trt for $typ {
                define_number_implementations![self;
                    ordinalize => String
                ];
            }
        )*
    }
}

implement_string_for![
    Inflector;
    String, str
];

implement_number_for![
    InflectorNumbers;
    i8, i16, i32, i64, u8, u16, u32, u64, isize, usize, f32, f64
];

#[cfg(all(feature = "unstable", test))]
mod benchmarks {
    extern crate test;
    use self::test::Bencher;
    use ::Inflector;

    macro_rules! benchmarks {
        ( $($test_name:ident => $imp_trait:ident => $to_cast:expr), *) => {
            $(
                #[bench]
                fn $test_name(b: &mut Bencher) {
                    b.iter(|| {
                        $to_cast.$imp_trait()
                    });
                }
            )*
        }
    }

    benchmarks![
        benchmark_str_to_camel => to_camel_case => "foo_bar",
        benchmark_str_is_camel => is_camel_case => "fooBar",
        benchmark_str_to_screaming_snake => to_screaming_snake_case => "fooBar",
        benchmark_str_is_screaming_snake => is_screaming_snake_case => "FOO_BAR",
        benchmark_str_to_snake => to_snake_case => "fooBar",
        benchmark_str_is_snake => is_snake_case => "foo_bar",
        benchmark_str_to_kebab => to_kebab_case => "fooBar",
        benchmark_str_is_kebab => is_kebab_case => "foo-bar",
        benchmark_str_to_train => to_train_case => "fooBar",
        benchmark_str_is_train => is_train_case => "Foo-Bar",
        benchmark_str_to_sentence => to_sentence_case => "fooBar",
        benchmark_str_is_sentence => is_sentence_case => "Foo bar",
        benchmark_str_to_title => to_title_case => "fooBar",
        benchmark_str_is_title => is_title_case => "Foo Bar",
        benchmark_str_ordinalize  => ordinalize => "1",
        benchmark_str_deordinalize  => deordinalize => "1st",
        benchmark_str_to_foreign_key => to_foreign_key => "Foo::Bar",
        benchmark_str_is_foreign_key => is_foreign_key => "bar_id",
        benchmark_string_to_camel => to_camel_case => "foo_bar".to_string(),
        benchmark_string_is_camel => is_camel_case => "fooBar".to_string(),
        benchmark_string_to_screaming_snake => to_screaming_snake_case => "fooBar".to_string(),
        benchmark_string_is_screaming_snake => is_screaming_snake_case => "FOO_BAR".to_string(),
        benchmark_string_to_snake => to_snake_case => "fooBar".to_string(),
        benchmark_string_is_snake => is_snake_case => "foo_bar".to_string(),
        benchmark_string_to_kebab => to_kebab_case => "fooBar".to_string(),
        benchmark_string_is_kebab => is_kebab_case => "foo-bar".to_string(),
        benchmark_string_to_train => to_train_case => "fooBar".to_string(),
        benchmark_string_is_train => is_train_case => "Foo-Bar".to_string(),
        benchmark_string_to_sentence => to_sentence_case => "fooBar".to_string(),
        benchmark_string_is_sentence => is_sentence_case => "Foo bar".to_string(),
        benchmark_string_to_title => to_title_case => "fooBar".to_string(),
        benchmark_string_is_title => is_title_case => "Foo Bar".to_string(),
        benchmark_string_ordinalize  => ordinalize => "1".to_string(),
        benchmark_string_deordinalize  => deordinalize => "1st".to_string(),
        benchmark_string_to_foreign_key => to_foreign_key => "Foo::Bar".to_string(),
        benchmark_string_is_foreign_key => is_foreign_key => "bar_id".to_string()
    ];

    #[cfg(feature = "heavyweight")]
    benchmarks![
        benchmark_str_to_class => to_class_case => "foo",
        benchmark_str_is_class => is_class_case => "Foo",
        benchmark_str_to_table => to_table_case => "fooBar",
        benchmark_str_is_table => is_table_case => "foo_bars",
        benchmark_str_pluralize => to_plural => "crate",
        benchmark_str_singular => to_singular => "crates",
        benchmark_string_to_class => to_class_case => "foo".to_string(),
        benchmark_string_is_class => is_class_case => "Foo".to_string(),
        benchmark_string_to_table => to_table_case => "fooBar".to_string(),
        benchmark_string_is_table => is_table_case => "foo_bars".to_string(),
        benchmark_string_pluralize => to_plural => "crate".to_string(),
        benchmark_string_singular => to_singular => "crates".to_string(),
        benchmark_string_demodulize => demodulize => "Foo::Bar".to_string(),
        benchmark_string_deconstantize => deconstantize => "Foo::Bar".to_string(),
        benchmark_str_demodulize => demodulize => "Foo::Bar",
        benchmark_str_deconstantize => deconstantize => "Foo::Bar"
    ];
}