text:
package gob

import (
	"encoding"
	"errors"
	"io"
	"math"
	"reflect"
)

var (
	errBadUint = errors.New("gob: encoded unsigned integer out of range")
	errBadType = errors.New("gob: unknown type id or corrupted data")
	errRange   = errors.New("gob: bad data: field numbers out of bounds")
)

type decHelper func(state *decoderState, v reflect.Value, length int, ovfl error) bool

// decoderState is the execution state of an instance of the decoder. A new state
// is created for nested objects.
type decoderState struct {
	dec *Decoder
	// The buffer is stored with an extra indirection because it may be replaced
	// if we load a type during decode (when reading an interface value).
	b        *decBuffer
	fieldnum int // the last field number read.
	buf      []byte
	next     *decoderState // for free list
}

// decBuffer is an extremely simple, fast implementation of a read-only byte buffer.
// It is initialized by calling Size and then copying the data into the slice returned by Bytes().
type decBuffer struct {
	data   []byte
	offset int // Read offset.
}

func (d *decBuffer) Read(p []byte) (int, error) {
	n := copy(p, d.data[d.offset:])
	if n == 0 && len(p) != 0 {
		return 0, io.EOF
	}
	d.offset += n
	return n, nil
}

func (d *decBuffer) Drop(n int) {
	if n > d.Len() {
		panic("drop")
	}
	d.offset += n
}

// Size grows the buffer to exactly n bytes, so d.Bytes() will
// return a slice of length n. Existing data is first discarded.
func (d *decBuffer) Size(n int) {
	d.Reset()
	if cap(d.data) < n {
		d.data = make([]byte, n)
	} else {
		d.data = d.data[0:n]
	}
}

func (d *decBuffer) ReadByte() (byte, error) {
	if d.offset >= len(d.data) {
		return 0, io.EOF
	}
	c := d.data[d.offset]
	d.offset++
	return c, nil
}

func (d *decBuffer) Len() int {
	return len(d.data) - d.offset
}

func (d *decBuffer) Bytes() []byte {
	return d.data[d.offset:]
}

func (d *decBuffer) Reset() {
	d.data = d.data[0:0]
	d.offset = 0
}

// We pass the bytes.Buffer separately for easier testing of the infrastructure
// without requiring a full Decoder.
func (dec *Decoder) newDecoderState(buf *decBuffer) *decoderState {
	d := dec.freeList
	if d == nil {
		d = new(decoderState)
		d.dec = dec
		d.buf = make([]byte, uint64Size)
	} else {
		dec.freeList = d.next
	}
	d.b = buf
	return d
}

func (dec *Decoder) freeDecoderState(d *decoderState) {
	d.next = dec.freeList
	dec.freeList = d
}

func overflow(name string) error {
	return errors.New(`value for "` + name + `" out of range`)
}

// decodeUintReader reads an encoded unsigned integer from an io.Reader.
// Used only by the Decoder to read the message length.
func decodeUintReader(r io.Reader, buf []byte) (x uint64, width int, err error) {
	width = 1
	n, err := io.ReadFull(r, buf[0:width])
	if n == 0 {
		return
	}
	b := buf[0]
	if b <= 0x7f {
		return uint64(b), width, nil
	}
	n = -int(int8(b))
	if n > uint64Size {
		err = errBadUint
		return
	}
	width, err = io.ReadFull(r, buf[0:n])
	if err != nil {
		if err == io.EOF {
			err = io.ErrUnexpectedEOF
		}
		return
	}
	// Could check that the high byte is zero but it's not worth it.
	for _, b := range buf[0:width] {
		x = x<<8 | uint64(b)
	}
	width++ // +1 for length byte
	return
}

// decodeUint reads an encoded unsigned integer from state.r.
// Does not check for overflow.
func (state *decoderState) decodeUint() (x uint64) {
	b, err := state.b.ReadByte()
	if err != nil {
		error_(err)
	}
	if b <= 0x7f {
		return uint64(b)
	}
	n := -int(int8(b))
	if n > uint64Size {
		error_(errBadUint)
	}
	width, err := state.b.Read(state.buf[0:n])
	if err != nil {
		error_(err)
	}
	// Don't need to check error; it's safe to loop regardless.
	// Could check that the high byte is zero but it's not worth it.
	for _, b := range state.buf[0:width] {
		x = x<<8 | uint64(b)
	}
	return x
}

// decodeInt reads an encoded signed integer from state.r.
// Does not check for overflow.
func (state *decoderState) decodeInt() int64 {
	x := state.decodeUint()
	if x&1 != 0 {
		return ^int64(x >> 1)
	}
	return int64(x >> 1)
}

// getLength decodes the next uint and makes sure it is a possible
// size for a data item that follows, which means it must fit in a
// non-negative int and fit in the buffer.
func (state *decoderState) getLength() (int, bool) {
	n := int(state.decodeUint())
	if n < 0 || state.b.Len() < n || tooBig <= n {
		return 0, false
	}
	return n, true
}

// decOp is the signature of a decoding operator for a given type.
type decOp func(i *decInstr, state *decoderState, v reflect.Value)

// The 'instructions' of the decoding machine
type decInstr struct {
	op    decOp
	field int   // field number of the wire type
	index []int // field access indices for destination type
	ovfl  error // error message for overflow/underflow (for arrays, of the elements)
}

// ignoreUint discards a uint value with no destination.
func ignoreUint(i *decInstr, state *decoderState, v reflect.Value) {
	state.decodeUint()
}

// ignoreTwoUints discards a uint value with no destination. It's used to skip
// complex values.
func ignoreTwoUints(i *decInstr, state *decoderState, v reflect.Value) {
	state.decodeUint()
	state.decodeUint()
}

// Since the encoder writes no zeros, if we arrive at a decoder we have
// a value to extract and store.  The field number has already been read
// (it's how we knew to call this decoder).
// Each decoder is responsible for handling any indirections associated
// with the data structure.  If any pointer so reached is nil, allocation must
// be done.

// decAlloc takes a value and returns a settable value that can
// be assigned to. If the value is a pointer, decAlloc guarantees it points to storage.
// The callers to the individual decoders are expected to have used decAlloc.
// The individual decoders don't need to it.
func decAlloc(v reflect.Value) reflect.Value {
	for v.Kind() == reflect.Ptr {
		if v.IsNil() {
			v.Set(reflect.New(v.Type().Elem()))
		}
		v = v.Elem()
	}
	return v
}

// decBool decodes a uint and stores it as a boolean in value.
func decBool(i *decInstr, state *decoderState, value reflect.Value) {
	value.SetBool(state.decodeUint() != 0)
}

// decInt8 decodes an integer and stores it as an int8 in value.
func decInt8(i *decInstr, state *decoderState, value reflect.Value) {
	v := state.decodeInt()
	if v < math.MinInt8 || math.MaxInt8 < v {
		error_(i.ovfl)
	}
	value.SetInt(v)
}

// decUint8 decodes an unsigned integer and stores it as a uint8 in value.
func decUint8(i *decInstr, state *decoderState, value reflect.Value) {
	v := state.decodeUint()
	if math.MaxUint8 < v {
		error_(i.ovfl)
	}
	value.SetUint(v)
}

// decInt16 decodes an integer and stores it as an int16 in value.
func decInt16(i *decInstr, state *decoderState, value reflect.Value) {
	v := state.decodeInt()
	if v < math.MinInt16 || math.MaxInt16 < v {
		error_(i.ovfl)
	}
	value.SetInt(v)
}

// decUint16 decodes an unsigned integer and stores it as a uint16 in value.
func decUint16(i *decInstr, state *decoderState, value reflect.Value) {
	v := state.decodeUint()
	if math.MaxUint16 < v {
		error_(i.ovfl)
	}
	value.SetUint(v)
}

// decInt32 decodes an integer and stores it as an int32 in value.
func decInt32(i *decInstr, state *decoderState, value reflect.Value) {
	v := state.decodeInt()
	if v < math.MinInt32 || math.MaxInt32 < v {
		error_(i.ovfl)
	}
	value.SetInt(v)
}

// decUint32 decodes an unsigned integer and stores it as a uint32 in value.
func decUint32(i *decInstr, state *decoderState, value reflect.Value) {
	v := state.decodeUint()
	if math.MaxUint32 < v {
		error_(i.ovfl)
	}
	value.SetUint(v)
}

// decInt64 decodes an integer and stores it as an int64 in value.
func decInt64(i *decInstr, state *decoderState, value reflect.Value) {
	v := state.decodeInt()
	value.SetInt(v)
}

// decUint64 decodes an unsigned integer and stores it as a uint64 in value.
func decUint64(i *decInstr, state *decoderState, value reflect.Value) {
	v := state.decodeUint()
	value.SetUint(v)
}

// Floating-point numbers are transmitted as uint64s holding the bits
// of the underlying representation.  They are sent byte-reversed, with
// the exponent end coming out first, so integer floating point numbers
// (for example) transmit more compactly.  This routine does the
// unswizzling.
func float64FromBits(u uint64) float64 {
	var v uint64
	for i := 0; i < 8; i++ {
		v <<= 8
		v |= u & 0xFF
		u >>= 8
	}
	return math.Float64frombits(v)
}

// float32FromBits decodes an unsigned integer, treats it as a 32-bit floating-point
// number, and returns it. It's a helper function for float32 and complex64.
// It returns a float64 because that's what reflection needs, but its return
// value is known to be accurately representable in a float32.
func float32FromBits(u uint64, ovfl error) float64 {
	v := float64FromBits(u)
	av := v
	if av < 0 {
		av = -av
	}
	// +Inf is OK in both 32- and 64-bit floats.  Underflow is always OK.
	if math.MaxFloat32 < av && av <= math.MaxFloat64 {
		error_(ovfl)
	}
	return v
}

// decFloat32 decodes an unsigned integer, treats it as a 32-bit floating-point
// number, and stores it in value.
func decFloat32(i *decInstr, state *decoderState, value reflect.Value) {
	value.SetFloat(float32FromBits(state.decodeUint(), i.ovfl))
}

// decFloat64 decodes an unsigned integer, treats it as a 64-bit floating-point
// number, and stores it in value.
func decFloat64(i *decInstr, state *decoderState, value reflect.Value) {
	value.SetFloat(float64FromBits(state.decodeUint()))
}

// decComplex64 decodes a pair of unsigned integers, treats them as a
// pair of floating point numbers, and stores them as a complex64 in value.
// The real part comes first.
func decComplex64(i *decInstr, state *decoderState, value reflect.Value) {
	real := float32FromBits(state.decodeUint(), i.ovfl)
	imag := float32FromBits(state.decodeUint(), i.ovfl)
	value.SetComplex(complex(real, imag))
}

// decComplex128 decodes a pair of unsigned integers, treats them as a
// pair of floating point numbers, and stores them as a complex128 in value.
// The real part comes first.
func decComplex128(i *decInstr, state *decoderState, value reflect.Value) {
	real := float64FromBits(state.decodeUint())
	imag := float64FromBits(state.decodeUint())
	value.SetComplex(complex(real, imag))
}

// decUint8Slice decodes a byte slice and stores in value a slice header
// describing the data.
// uint8 slices are encoded as an unsigned count followed by the raw bytes.
func decUint8Slice(i *decInstr, state *decoderState, value reflect.Value) {
	n, ok := state.getLength()
	if !ok {
		errorf("bad %s slice length: %d", value.Type(), n)
	}
	if value.Cap() < n {
		value.Set(reflect.MakeSlice(value.Type(), n, n))
	} else {
		value.Set(value.Slice(0, n))
	}
	if _, err := state.b.Read(value.Bytes()); err != nil {
		errorf("error decoding []byte: %s", err)
	}
}

// decString decodes byte array and stores in value a string header
// describing the data.
// Strings are encoded as an unsigned count followed by the raw bytes.
func decString(i *decInstr, state *decoderState, value reflect.Value) {
	n, ok := state.getLength()
	if !ok {
		errorf("bad %s slice length: %d", value.Type(), n)
	}
	// Read the data.
	data := make([]byte, n)
	if _, err := state.b.Read(data); err != nil {
		errorf("error decoding string: %s", err)
	}
	value.SetString(string(data))
}

// ignoreUint8Array skips over the data for a byte slice value with no destination.
func ignoreUint8Array(i *decInstr, state *decoderState, value reflect.Value) {
	n, ok := state.getLength()
	if !ok {
		errorf("slice length too large")
	}
	b := make([]byte, n)
	state.b.Read(b)
}

// Execution engine

// The encoder engine is an array of instructions indexed by field number of the incoming
// decoder.  It is executed with random access according to field number.
type decEngine struct {
	instr    []decInstr
	numInstr int // the number of active instructions
}

// decodeSingle decodes a top-level value that is not a struct and stores it in value.
// Such values are preceded by a zero, making them have the memory layout of a
// struct field (although with an illegal field number).
func (dec *Decoder) decodeSingle(engine *decEngine, ut *userTypeInfo, value reflect.Value) {
	state := dec.newDecoderState(&dec.buf)
	defer dec.freeDecoderState(state)
	state.fieldnum = singletonField
	if state.decodeUint() != 0 {
		errorf("decode: corrupted data: non-zero delta for singleton")
	}
	instr := &engine.instr[singletonField]
	instr.op(instr, state, value)
}

// decodeStruct decodes a top-level struct and stores it in value.
// Indir is for the value, not the type.  At the time of the call it may
// differ from ut.indir, which was computed when the engine was built.
// This state cannot arise for decodeSingle, which is called directly
// from the user's value, not from the innards of an engine.
func (dec *Decoder) decodeStruct(engine *decEngine, ut *userTypeInfo, value reflect.Value) {
	state := dec.newDecoderState(&dec.buf)
	defer dec.freeDecoderState(state)
	state.fieldnum = -1
	for state.b.Len() > 0 {
		delta := int(state.decodeUint())
		if delta < 0 {
			errorf("decode: corrupted data: negative delta")
		}
		if delta == 0 { // struct terminator is zero delta fieldnum
			break
		}
		fieldnum := state.fieldnum + delta
		if fieldnum >= len(engine.instr) {
			error_(errRange)
			break
		}
		instr := &engine.instr[fieldnum]
		var field reflect.Value
		if instr.index != nil {
			// Otherwise the field is unknown to us and instr.op is an ignore op.
			field = value.FieldByIndex(instr.index)
			if field.Kind() == reflect.Ptr {
				field = decAlloc(field)
			}
		}
		instr.op(instr, state, field)
		state.fieldnum = fieldnum
	}
}

var noValue reflect.Value

// ignoreStruct discards the data for a struct with no destination.
func (dec *Decoder) ignoreStruct(engine *decEngine) {
	state := dec.newDecoderState(&dec.buf)
	defer dec.freeDecoderState(state)
	state.fieldnum = -1
	for state.b.Len() > 0 {
		delta := int(state.decodeUint())
		if delta < 0 {
			errorf("ignore decode: corrupted data: negative delta")
		}
		if delta == 0 { // struct terminator is zero delta fieldnum
			break
		}
		fieldnum := state.fieldnum + delta
		if fieldnum >= len(engine.instr) {
			error_(errRange)
		}
		instr := &engine.instr[fieldnum]
		instr.op(instr, state, noValue)
		state.fieldnum = fieldnum
	}
}

// ignoreSingle discards the data for a top-level non-struct value with no
// destination. It's used when calling Decode with a nil value.
func (dec *Decoder) ignoreSingle(engine *decEngine) {
	state := dec.newDecoderState(&dec.buf)
	defer dec.freeDecoderState(state)
	state.fieldnum = singletonField
	delta := int(state.decodeUint())
	if delta != 0 {
		errorf("decode: corrupted data: non-zero delta for singleton")
	}
	instr := &engine.instr[singletonField]
	instr.op(instr, state, noValue)
}

// decodeArrayHelper does the work for decoding arrays and slices.
func (dec *Decoder) decodeArrayHelper(state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error, helper decHelper) {
	if helper != nil && helper(state, value, length, ovfl) {
		return
	}
	instr := &decInstr{elemOp, 0, nil, ovfl}
	isPtr := value.Type().Elem().Kind() == reflect.Ptr
	for i := 0; i < length; i++ {
		if state.b.Len() == 0 {
			errorf("decoding array or slice: length exceeds input size (%d elements)", length)
		}
		v := value.Index(i)
		if isPtr {
			v = decAlloc(v)
		}
		elemOp(instr, state, v)
	}
}

// decodeArray decodes an array and stores it in value.
// The length is an unsigned integer preceding the elements.  Even though the length is redundant
// (it's part of the type), it's a useful check and is included in the encoding.
func (dec *Decoder) decodeArray(atyp reflect.Type, state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error, helper decHelper) {
	if n := state.decodeUint(); n != uint64(length) {
		errorf("length mismatch in decodeArray")
	}
	dec.decodeArrayHelper(state, value, elemOp, length, ovfl, helper)
}

// decodeIntoValue is a helper for map decoding.
func decodeIntoValue(state *decoderState, op decOp, isPtr bool, value reflect.Value, ovfl error) reflect.Value {
	instr := &decInstr{op, 0, nil, ovfl}
	v := value
	if isPtr {
		v = decAlloc(value)
	}
	op(instr, state, v)
	return value
}

// decodeMap decodes a map and stores it in value.
// Maps are encoded as a length followed by key:value pairs.
// Because the internals of maps are not visible to us, we must
// use reflection rather than pointer magic.
func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, value reflect.Value, keyOp, elemOp decOp, ovfl error) {
	if value.IsNil() {
		// Allocate map.
		value.Set(reflect.MakeMap(mtyp))
	}
	n := int(state.decodeUint())
	keyIsPtr := mtyp.Key().Kind() == reflect.Ptr
	elemIsPtr := mtyp.Elem().Kind() == reflect.Ptr
	for i := 0; i < n; i++ {
		key := decodeIntoValue(state, keyOp, keyIsPtr, allocValue(mtyp.Key()), ovfl)
		elem := decodeIntoValue(state, elemOp, elemIsPtr, allocValue(mtyp.Elem()), ovfl)
		value.SetMapIndex(key, elem)
	}
}

// ignoreArrayHelper does the work for discarding arrays and slices.
func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) {
	instr := &decInstr{elemOp, 0, nil, errors.New("no error")}
	for i := 0; i < length; i++ {
		if state.b.Len() == 0 {
			errorf("decoding array or slice: length exceeds input size (%d elements)", length)
		}
		elemOp(instr, state, noValue)
	}
}

// ignoreArray discards the data for an array value with no destination.
func (dec *Decoder) ignoreArray(state *decoderState, elemOp decOp, length int) {
	if n := state.decodeUint(); n != uint64(length) {
		errorf("length mismatch in ignoreArray")
	}
	dec.ignoreArrayHelper(state, elemOp, length)
}

// ignoreMap discards the data for a map value with no destination.
func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) {
	n := int(state.decodeUint())
	keyInstr := &decInstr{keyOp, 0, nil, errors.New("no error")}
	elemInstr := &decInstr{elemOp, 0, nil, errors.New("no error")}
	for i := 0; i < n; i++ {
		keyOp(keyInstr, state, noValue)
		elemOp(elemInstr, state, noValue)
	}
}

// decodeSlice decodes a slice and stores it in value.
// Slices are encoded as an unsigned length followed by the elements.
func (dec *Decoder) decodeSlice(state *decoderState, value reflect.Value, elemOp decOp, ovfl error, helper decHelper) {
	u := state.decodeUint()
	typ := value.Type()
	size := uint64(typ.Elem().Size())
	nBytes := u * size
	n := int(u)
	// Take care with overflow in this calculation.
	if n < 0 || uint64(n) != u || nBytes > tooBig || (size > 0 && nBytes/size != u) {
		// We don't check n against buffer length here because if it's a slice
		// of interfaces, there will be buffer reloads.
		errorf("%s slice too big: %d elements of %d bytes", typ.Elem(), u, size)
	}
	if value.Cap() < n {
		value.Set(reflect.MakeSlice(typ, n, n))
	} else {
		value.Set(value.Slice(0, n))
	}
	dec.decodeArrayHelper(state, value, elemOp, n, ovfl, helper)
}

// ignoreSlice skips over the data for a slice value with no destination.
func (dec *Decoder) ignoreSlice(state *decoderState, elemOp decOp) {
	dec.ignoreArrayHelper(state, elemOp, int(state.decodeUint()))
}

// decodeInterface decodes an interface value and stores it in value.
// Interfaces are encoded as the name of a concrete type followed by a value.
// If the name is empty, the value is nil and no value is sent.
func (dec *Decoder) decodeInterface(ityp reflect.Type, state *decoderState, value reflect.Value) {
	// Read the name of the concrete type.
	nr := state.decodeUint()
	if nr < 0 || nr > 1<<31 { // zero is permissible for anonymous types
		errorf("invalid type name length %d", nr)
	}
	if nr > uint64(state.b.Len()) {
		errorf("invalid type name length %d: exceeds input size", nr)
	}
	b := make([]byte, nr)
	state.b.Read(b)
	name := string(b)
	// Allocate the destination interface value.
	if name == "" {
		// Copy the nil interface value to the target.
		value.Set(reflect.Zero(value.Type()))
		return
	}
	if len(name) > 1024 {
		errorf("name too long (%d bytes): %.20q...", len(name), name)
	}
	// The concrete type must be registered.
	registerLock.RLock()
	typ, ok := nameToConcreteType[name]
	registerLock.RUnlock()
	if !ok {
		errorf("name not registered for interface: %q", name)
	}
	// Read the type id of the concrete value.
	concreteId := dec.decodeTypeSequence(true)
	if concreteId < 0 {
		error_(dec.err)
	}
	// Byte count of value is next; we don't care what it is (it's there
	// in case we want to ignore the value by skipping it completely).
	state.decodeUint()
	// Read the concrete value.
	v := allocValue(typ)
	dec.decodeValue(concreteId, v)
	if dec.err != nil {
		error_(dec.err)
	}
	// Assign the concrete value to the interface.
	// Tread carefully; it might not satisfy the interface.
	if !typ.AssignableTo(ityp) {
		errorf("%s is not assignable to type %s", typ, ityp)
	}
	// Copy the interface value to the target.
	value.Set(v)
}

// ignoreInterface discards the data for an interface value with no destination.
func (dec *Decoder) ignoreInterface(state *decoderState) {
	// Read the name of the concrete type.
	n, ok := state.getLength()
	if !ok {
		errorf("bad interface encoding: name too large for buffer")
	}
	b := make([]byte, n)
	_, err := state.b.Read(b)
	if err != nil {
		error_(err)
	}
	id := dec.decodeTypeSequence(true)
	if id < 0 {
		error_(dec.err)
	}
	// At this point, the decoder buffer contains a delimited value. Just toss it.
	n, ok = state.getLength()
	if !ok {
		errorf("bad interface encoding: data length too large for buffer")
	}
	state.b.Drop(n)
}

// decodeGobDecoder decodes something implementing the GobDecoder interface.
// The data is encoded as a byte slice.
func (dec *Decoder) decodeGobDecoder(ut *userTypeInfo, state *decoderState, value reflect.Value) {
	// Read the bytes for the value.
	n, ok := state.getLength()
	if !ok {
		errorf("GobDecoder: length too large for buffer")
	}
	b := make([]byte, n)
	_, err := state.b.Read(b)
	if err != nil {
		error_(err)
	}
	// We know it's one of these.
	switch ut.externalDec {
	case xGob:
		err = value.Interface().(GobDecoder).GobDecode(b)
	case xBinary:
		err = value.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary(b)
	case xText:
		err = value.Interface().(encoding.TextUnmarshaler).UnmarshalText(b)
	}
	if err != nil {
		error_(err)
	}
}

// ignoreGobDecoder discards the data for a GobDecoder value with no destination.
func (dec *Decoder) ignoreGobDecoder(state *decoderState) {
	// Read the bytes for the value.
	n, ok := state.getLength()
	if !ok {
		errorf("GobDecoder: length too large for buffer")
	}
	b := make([]byte, n)
	_, err := state.b.Read(b)
	if err != nil {
		error_(err)
	}
}

// Index by Go types.
var decOpTable = [...]decOp{
	reflect.Bool:       decBool,
	reflect.Int8:       decInt8,
	reflect.Int16:      decInt16,
	reflect.Int32:      decInt32,
	reflect.Int64:      decInt64,
	reflect.Uint8:      decUint8,
	reflect.Uint16:     decUint16,
	reflect.Uint32:     decUint32,
	reflect.Uint64:     decUint64,
	reflect.Float32:    decFloat32,
	reflect.Float64:    decFloat64,
	reflect.Complex64:  decComplex64,
	reflect.Complex128: decComplex128,
	reflect.String:     decString,
}

// Indexed by gob types.  tComplex will be added during type.init().
var decIgnoreOpMap = map[typeId]decOp{
	tBool:    ignoreUint,
	tInt:     ignoreUint,
	tUint:    ignoreUint,
	tFloat:   ignoreUint,
	tBytes:   ignoreUint8Array,
	tString:  ignoreUint8Array,
	tComplex: ignoreTwoUints,
}

// decOpFor returns the decoding op for the base type under rt and
// the indirection count to reach it.
func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) *decOp {
	ut := userType(rt)
	// If the type implements GobEncoder, we handle it without further processing.
	if ut.externalDec != 0 {
		return dec.gobDecodeOpFor(ut)
	}

	// If this type is already in progress, it's a recursive type (e.g. map[string]*T).
	// Return the pointer to the op we're already building.
	if opPtr := inProgress[rt]; opPtr != nil {
		return opPtr
	}
	typ := ut.base
	var op decOp
	k := typ.Kind()
	if int(k) < len(decOpTable) {
		op = decOpTable[k]
	}
	if op == nil {
		inProgress[rt] = &op
		// Special cases
		switch t := typ; t.Kind() {
		case reflect.Array:
			name = "element of " + name
			elemId := dec.wireType[wireId].ArrayT.Elem
			elemOp := dec.decOpFor(elemId, t.Elem(), name, inProgress)
			ovfl := overflow(name)
			helper := decArrayHelper[t.Elem().Kind()]
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.decodeArray(t, state, value, *elemOp, t.Len(), ovfl, helper)
			}

		case reflect.Map:
			keyId := dec.wireType[wireId].MapT.Key
			elemId := dec.wireType[wireId].MapT.Elem
			keyOp := dec.decOpFor(keyId, t.Key(), "key of "+name, inProgress)
			elemOp := dec.decOpFor(elemId, t.Elem(), "element of "+name, inProgress)
			ovfl := overflow(name)
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.decodeMap(t, state, value, *keyOp, *elemOp, ovfl)
			}

		case reflect.Slice:
			name = "element of " + name
			if t.Elem().Kind() == reflect.Uint8 {
				op = decUint8Slice
				break
			}
			var elemId typeId
			if tt, ok := builtinIdToType[wireId]; ok {
				elemId = tt.(*sliceType).Elem
			} else {
				elemId = dec.wireType[wireId].SliceT.Elem
			}
			elemOp := dec.decOpFor(elemId, t.Elem(), name, inProgress)
			ovfl := overflow(name)
			helper := decSliceHelper[t.Elem().Kind()]
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.decodeSlice(state, value, *elemOp, ovfl, helper)
			}

		case reflect.Struct:
			// Generate a closure that calls out to the engine for the nested type.
			ut := userType(typ)
			enginePtr, err := dec.getDecEnginePtr(wireId, ut)
			if err != nil {
				error_(err)
			}
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				// indirect through enginePtr to delay evaluation for recursive structs.
				dec.decodeStruct(*enginePtr, ut, value)
			}
		case reflect.Interface:
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.decodeInterface(t, state, value)
			}
		}
	}
	if op == nil {
		errorf("decode can't handle type %s", rt)
	}
	return &op
}

// decIgnoreOpFor returns the decoding op for a field that has no destination.
func (dec *Decoder) decIgnoreOpFor(wireId typeId) decOp {
	op, ok := decIgnoreOpMap[wireId]
	if !ok {
		if wireId == tInterface {
			// Special case because it's a method: the ignored item might
			// define types and we need to record their state in the decoder.
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.ignoreInterface(state)
			}
			return op
		}
		// Special cases
		wire := dec.wireType[wireId]
		switch {
		case wire == nil:
			errorf("bad data: undefined type %s", wireId.string())
		case wire.ArrayT != nil:
			elemId := wire.ArrayT.Elem
			elemOp := dec.decIgnoreOpFor(elemId)
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.ignoreArray(state, elemOp, wire.ArrayT.Len)
			}

		case wire.MapT != nil:
			keyId := dec.wireType[wireId].MapT.Key
			elemId := dec.wireType[wireId].MapT.Elem
			keyOp := dec.decIgnoreOpFor(keyId)
			elemOp := dec.decIgnoreOpFor(elemId)
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.ignoreMap(state, keyOp, elemOp)
			}

		case wire.SliceT != nil:
			elemId := wire.SliceT.Elem
			elemOp := dec.decIgnoreOpFor(elemId)
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.ignoreSlice(state, elemOp)
			}

		case wire.StructT != nil:
			// Generate a closure that calls out to the engine for the nested type.
			enginePtr, err := dec.getIgnoreEnginePtr(wireId)
			if err != nil {
				error_(err)
			}
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				// indirect through enginePtr to delay evaluation for recursive structs
				state.dec.ignoreStruct(*enginePtr)
			}

		case wire.GobEncoderT != nil, wire.BinaryMarshalerT != nil, wire.TextMarshalerT != nil:
			op = func(i *decInstr, state *decoderState, value reflect.Value) {
				state.dec.ignoreGobDecoder(state)
			}
		}
	}
	if op == nil {
		errorf("bad data: ignore can't handle type %s", wireId.string())
	}
	return op
}

// gobDecodeOpFor returns the op for a type that is known to implement
// GobDecoder.
func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) *decOp {
	rcvrType := ut.user
	if ut.decIndir == -1 {
		rcvrType = reflect.PtrTo(rcvrType)
	} else if ut.decIndir > 0 {
		for i := int8(0); i < ut.decIndir; i++ {
			rcvrType = rcvrType.Elem()
		}
	}
	var op decOp
	op = func(i *decInstr, state *decoderState, value reflect.Value) {
		// We now have the base type. We need its address if the receiver is a pointer.
		if value.Kind() != reflect.Ptr && rcvrType.Kind() == reflect.Ptr {
			value = value.Addr()
		}
		state.dec.decodeGobDecoder(ut, state, value)
	}
	return &op
}

// compatibleType asks: Are these two gob Types compatible?
// Answers the question for basic types, arrays, maps and slices, plus
// GobEncoder/Decoder pairs.
// Structs are considered ok; fields will be checked later.
func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool {
	if rhs, ok := inProgress[fr]; ok {
		return rhs == fw
	}
	inProgress[fr] = fw
	ut := userType(fr)
	wire, ok := dec.wireType[fw]
	// If wire was encoded with an encoding method, fr must have that method.
	// And if not, it must not.
	// At most one of the booleans in ut is set.
	// We could possibly relax this constraint in the future in order to
	// choose the decoding method using the data in the wireType.
	// The parentheses look odd but are correct.
	if (ut.externalDec == xGob) != (ok && wire.GobEncoderT != nil) ||
		(ut.externalDec == xBinary) != (ok && wire.BinaryMarshalerT != nil) ||
		(ut.externalDec == xText) != (ok && wire.TextMarshalerT != nil) {
		return false
	}
	if ut.externalDec != 0 { // This test trumps all others.
		return true
	}
	switch t := ut.base; t.Kind() {
	default:
		// chan, etc: cannot handle.
		return false
	case reflect.Bool:
		return fw == tBool
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		return fw == tInt
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
		return fw == tUint
	case reflect.Float32, reflect.Float64:
		return fw == tFloat
	case reflect.Complex64, reflect.Complex128:
		return fw == tComplex
	case reflect.String:
		return fw == tString
	case reflect.Interface:
		return fw == tInterface
	case reflect.Array:
		if !ok || wire.ArrayT == nil {
			return false
		}
		array := wire.ArrayT
		return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress)
	case reflect.Map:
		if !ok || wire.MapT == nil {
			return false
		}
		MapType := wire.MapT
		return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress)
	case reflect.Slice:
		// Is it an array of bytes?
		if t.Elem().Kind() == reflect.Uint8 {
			return fw == tBytes
		}
		// Extract and compare element types.
		var sw *sliceType
		if tt, ok := builtinIdToType[fw]; ok {
			sw, _ = tt.(*sliceType)
		} else if wire != nil {
			sw = wire.SliceT
		}
		elem := userType(t.Elem()).base
		return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress)
	case reflect.Struct:
		return true
	}
}

// typeString returns a human-readable description of the type identified by remoteId.
func (dec *Decoder) typeString(remoteId typeId) string {
	if t := idToType[remoteId]; t != nil {
		// globally known type.
		return t.string()
	}
	return dec.wireType[remoteId].string()
}

// compileSingle compiles the decoder engine for a non-struct top-level value, including
// GobDecoders.
func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
	rt := ut.user
	engine = new(decEngine)
	engine.instr = make([]decInstr, 1) // one item
	name := rt.String()                // best we can do
	if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) {
		remoteType := dec.typeString(remoteId)
		// Common confusing case: local interface type, remote concrete type.
		if ut.base.Kind() == reflect.Interface && remoteId != tInterface {
			return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType)
		}
		return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType)
	}
	op := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp))
	ovfl := errors.New(`value for "` + name + `" out of range`)
	engine.instr[singletonField] = decInstr{*op, singletonField, nil, ovfl}
	engine.numInstr = 1
	return
}

// compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded.
func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) {
	engine = new(decEngine)
	engine.instr = make([]decInstr, 1) // one item
	op := dec.decIgnoreOpFor(remoteId)
	ovfl := overflow(dec.typeString(remoteId))
	engine.instr[0] = decInstr{op, 0, nil, ovfl}
	engine.numInstr = 1
	return
}

// compileDec compiles the decoder engine for a value.  If the value is not a struct,
// it calls out to compileSingle.
func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) {
	defer catchError(&err)
	rt := ut.base
	srt := rt
	if srt.Kind() != reflect.Struct || ut.externalDec != 0 {
		return dec.compileSingle(remoteId, ut)
	}
	var wireStruct *structType
	// Builtin types can come from global pool; the rest must be defined by the decoder.
	// Also we know we're decoding a struct now, so the client must have sent one.
	if t, ok := builtinIdToType[remoteId]; ok {
		wireStruct, _ = t.(*structType)
	} else {
		wire := dec.wireType[remoteId]
		if wire == nil {
			error_(errBadType)
		}
		wireStruct = wire.StructT
	}
	if wireStruct == nil {
		errorf("type mismatch in decoder: want struct type %s; got non-struct", rt)
	}
	engine = new(decEngine)
	engine.instr = make([]decInstr, len(wireStruct.Field))
	seen := make(map[reflect.Type]*decOp)
	// Loop over the fields of the wire type.
	for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ {
		wireField := wireStruct.Field[fieldnum]
		if wireField.Name == "" {
			errorf("empty name for remote field of type %s", wireStruct.Name)
		}
		ovfl := overflow(wireField.Name)
		// Find the field of the local type with the same name.
		localField, present := srt.FieldByName(wireField.Name)
		// TODO(r): anonymous names
		if !present || !isExported(wireField.Name) {
			op := dec.decIgnoreOpFor(wireField.Id)
			engine.instr[fieldnum] = decInstr{op, fieldnum, nil, ovfl}
			continue
		}
		if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) {
			errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name)
		}
		op := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen)
		engine.instr[fieldnum] = decInstr{*op, fieldnum, localField.Index, ovfl}
		engine.numInstr++
	}
	return
}

// getDecEnginePtr returns the engine for the specified type.
func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) {
	rt := ut.user
	decoderMap, ok := dec.decoderCache[rt]
	if !ok {
		decoderMap = make(map[typeId]**decEngine)
		dec.decoderCache[rt] = decoderMap
	}
	if enginePtr, ok = decoderMap[remoteId]; !ok {
		// To handle recursive types, mark this engine as underway before compiling.
		enginePtr = new(*decEngine)
		decoderMap[remoteId] = enginePtr
		*enginePtr, err = dec.compileDec(remoteId, ut)
		if err != nil {
			delete(decoderMap, remoteId)
		}
	}
	return
}

// emptyStruct is the type we compile into when ignoring a struct value.
type emptyStruct struct{}

var emptyStructType = reflect.TypeOf(emptyStruct{})

// getIgnoreEnginePtr returns the engine for the specified type when the value is to be discarded.
func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) {
	var ok bool
	if enginePtr, ok = dec.ignorerCache[wireId]; !ok {
		// To handle recursive types, mark this engine as underway before compiling.
		enginePtr = new(*decEngine)
		dec.ignorerCache[wireId] = enginePtr
		wire := dec.wireType[wireId]
		if wire != nil && wire.StructT != nil {
			*enginePtr, err = dec.compileDec(wireId, userType(emptyStructType))
		} else {
			*enginePtr, err = dec.compileIgnoreSingle(wireId)
		}
		if err != nil {
			delete(dec.ignorerCache, wireId)
		}
	}
	return
}

// decodeValue decodes the data stream representing a value and stores it in value.
func (dec *Decoder) decodeValue(wireId typeId, value reflect.Value) {
	defer catchError(&dec.err)
	// If the value is nil, it means we should just ignore this item.
	if !value.IsValid() {
		dec.decodeIgnoredValue(wireId)
		return
	}
	// Dereference down to the underlying type.
	ut := userType(value.Type())
	base := ut.base
	var enginePtr **decEngine
	enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut)
	if dec.err != nil {
		return
	}
	value = decAlloc(value)
	engine := *enginePtr
	if st := base; st.Kind() == reflect.Struct && ut.externalDec == 0 {
		wt := dec.wireType[wireId]
		if engine.numInstr == 0 && st.NumField() > 0 &&
			wt != nil && len(wt.StructT.Field) > 0 {
			name := base.Name()
			errorf("type mismatch: no fields matched compiling decoder for %s", name)
		}
		dec.decodeStruct(engine, ut, value)
	} else {
		dec.decodeSingle(engine, ut, value)
	}
}

// decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it.
func (dec *Decoder) decodeIgnoredValue(wireId typeId) {
	var enginePtr **decEngine
	enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId)
	if dec.err != nil {
		return
	}
	wire := dec.wireType[wireId]
	if wire != nil && wire.StructT != nil {
		dec.ignoreStruct(*enginePtr)
	} else {
		dec.ignoreSingle(*enginePtr)
	}
}

func init() {
	var iop, uop decOp
	switch reflect.TypeOf(int(0)).Bits() {
	case 32:
		iop = decInt32
		uop = decUint32
	case 64:
		iop = decInt64
		uop = decUint64
	default:
		panic("gob: unknown size of int/uint")
	}
	decOpTable[reflect.Int] = iop
	decOpTable[reflect.Uint] = uop

	// Finally uintptr
	switch reflect.TypeOf(uintptr(0)).Bits() {
	case 32:
		uop = decUint32
	case 64:
		uop = decUint64
	default:
		panic("gob: unknown size of uintptr")
	}
	decOpTable[reflect.Uintptr] = uop
}

// Gob depends on being able to take the address
// of zeroed Values it creates, so use this wrapper instead
// of the standard reflect.Zero.
// Each call allocates once.
func allocValue(t reflect.Type) reflect.Value {
	return reflect.New(t).Elem()
}


text:
package com.ibm.xsp.extlib.designer.tooling.visualizations.extensionlibrary;

import org.w3c.dom.Node;

import com.ibm.designer.domino.constants.XSPAttributeNames;
import com.ibm.designer.domino.constants.XSPTagNames;
import com.ibm.xsp.extlib.designer.tooling.visualizations.AbstractCommonControlVisualizer;
import com.ibm.xsp.registry.FacesRegistry;

/**
 * This class generates the following source
 *
 *  <?xml version="1.0" encoding="UTF-8"?>
 *  <xp:view xmlns:xp="http://www.ibm.com/xsp/core">
 *
 *      <xp:table style="width:152.0px;border:none;background-color:rgb(192,192,192)">
 *
 *          <xp:tr>
 *              <xp:td style="border-style:solid;border-color:rgb(222,222,222);border-width:medium;background-color:rgb(222,222,222)">
 *                  <xp:span style="font-weight:bold">
 *                      Container 1
 *               </xp:span>
 *              </xp:td>
 *          </xp:tr>
 *
 *          <xp:tr>
 *              <xp:td style="border-style:solid;border-color:rgb(255,255,255);border-width:1px;height:auto;background-color:rgb(255,255,255)">
 *                  <xp:table style="color:rgb(16,82,182)">
 *
 *                      <xp:tr>
 *                          <xp:td style="border:none">
 *                              Item 1
 *                          </xp:td>
 *                      </xp:tr>
 *
 *                      <xp:tr>
 *                          <xp:td style="border:none">
 *                              Item 2
 *                          </xp:td>
 *                      </xp:tr>
 *
 *                      <xp:tr>
 *                          <xp:td style="border:none">
 *                              Item 3
 *                          </xp:td>
 *                      </xp:tr>
 *
 *                  </xp:table>
 *              </xp:td>
 *          </xp:tr>
 *
 *          <xp:tr>
 *              <xp:td style="border-style:solid;border-color:rgb(222,222,222);border-width:medium;background-color:rgb(222,222,222)">
 *                 Container 2
 *              </xp:td>
 *          </xp:tr>
 *
 *          <xp:tr>
 *              <xp:td style="border-style:solid;border-color:rgb(222,222,222);border-width:medium;background-color:rgb(222,222,222)">
 *                  Container 3
 *              </xp:td>
 *          </xp:tr>
 *      </xp:table>
 *
 *  </xp:view>
 *
 */
public class AccordionVisualizer extends AbstractCommonControlVisualizer{

    private static final String MENU_ITEM_1_TEXT = "Container 1"; // $NLX-AccordionVisualizer.Choice1-1$
    private static final String MENU_ITEM_2_TEXT = "Item 1"; // $NLX-AccordionVisualizer.Menu11-1$
    private static final String MENU_ITEM_3_TEXT = "Item 2"; // $NLX-AccordionVisualizer.Menu12-1$
    private static final String MENU_ITEM_4_TEXT = "Item 3"; // $NLX-AccordionVisualizer.Menu13-1$
    private static final String MENU_ITEM_5_TEXT = "Container 2"; // $NLX-AccordionVisualizer.Choice2-1$
    private static final String MENU_ITEM_6_TEXT = "Container 3"; // $NLX-AccordionVisualizer.HierarchicalChoice3-1$

    /*
     * (non-Javadoc)
     * @see com.ibm.designer.domino.xsp.api.visual.AbstractVisualizationFactory#getXSPMarkupForControl(org.w3c.dom.Node, com.ibm.designer.domino.xsp.api.visual.AbstractVisualizationFactory.IVisualizationCallback, com.ibm.xsp.registry.FacesRegistry)
     */
    @Override
    public String getXSPMarkupForControl(Node nodeToVisualize,  IVisualizationCallback callback, FacesRegistry registry) {

        StringBuilder strBuilder = new StringBuilder();

        Tag outerTableTag = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE);
        outerTableTag.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "width:152.0px;border:none;background-color:rgb(192,192,192)"); // $NON-NLS-1$

        Tag firstRow = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_ROW);
        outerTableTag.addChildTag(firstRow);

        Tag firstRowCell = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_CELL);
        firstRowCell.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "border-style:solid;border-color:rgb(222,222,222);border-width:medium;background-color:rgb(222,222,222)"); // $NON-NLS-1$
        firstRow.addChildTag(firstRowCell);

        Tag firstRowSpan = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_SPAN);
        firstRowSpan.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "font-weight:bold"); // $NON-NLS-1$
        firstRowSpan.addTextChild(MENU_ITEM_1_TEXT);
        firstRowCell.addChildTag(firstRowSpan);

        Tag secondRow = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_ROW);
        outerTableTag.addChildTag(secondRow);

        Tag secondRowCell = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_CELL);
        secondRowCell.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "border-style:solid;border-color:rgb(255,255,255);border-width:1px;height:auto;background-color:rgb(255,255,255)"); // $NON-NLS-1$
        secondRow.addChildTag(secondRowCell);

        Tag innerTableTag = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE);
        innerTableTag.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "color:rgb(16,82,182)"); // $NON-NLS-1$
        secondRowCell.addChildTag(innerTableTag);

        Tag innerTableFirstRow = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_ROW);
        innerTableTag.addChildTag(innerTableFirstRow);

        Tag innerTableFirstRowCell = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_CELL);
        innerTableFirstRowCell.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "border:none"); // $NON-NLS-1$
        innerTableFirstRowCell.addTextChild(MENU_ITEM_2_TEXT);
        innerTableFirstRow.addChildTag(innerTableFirstRowCell);

        Tag innerTableSecondRow = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_ROW);
        innerTableTag.addChildTag(innerTableSecondRow);

        Tag innerTableSecondRowCell = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_CELL);
        innerTableSecondRowCell.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "border:none"); // $NON-NLS-1$
        innerTableSecondRowCell.addTextChild(MENU_ITEM_3_TEXT);
        innerTableSecondRow.addChildTag(innerTableSecondRowCell);

        Tag innerTableThirdRow = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_ROW);
        innerTableTag.addChildTag(innerTableThirdRow);

        Tag innerTableThirdRowCell = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_CELL);
        innerTableThirdRowCell.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "border:none"); // $NON-NLS-1$
        innerTableThirdRowCell.addTextChild(MENU_ITEM_4_TEXT);
        innerTableThirdRow.addChildTag(innerTableThirdRowCell);

        Tag thirdRow = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_ROW);
        outerTableTag.addChildTag(thirdRow);

        Tag thirdRowCell = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_CELL);
        thirdRowCell.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "border-style:solid;border-color:rgb(222,222,222);border-width:medium;background-color:rgb(222,222,222)"); // $NON-NLS-1$
        thirdRowCell.addTextChild(MENU_ITEM_5_TEXT);
        thirdRow.addChildTag(thirdRowCell);

        Tag fourthRow = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_ROW);
        outerTableTag.addChildTag(fourthRow);

        Tag fourthRowCell = new Tag(XP_PREFIX, XSPTagNames.XSP_TAG_TABLE_CELL);
        fourthRowCell.addAttribute(XSPAttributeNames.XSP_ATTR_STYLE, "border-style:solid;border-color:rgb(222,222,222);border-width:medium;background-color:rgb(222,222,222)"); // $NON-NLS-1$
        fourthRowCell.addTextChild(MENU_ITEM_6_TEXT);
        fourthRow.addChildTag(fourthRowCell);

        strBuilder.append(outerTableTag.toString());
        strBuilder.append(LINE_DELIMITER);

        return strBuilder.toString();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import unittest

class TestGetTable(object):
    """
    Mocks the interface expected by raw_tiles.index.index.index_table,
    which provides "table lookup". Here, we just return static stuff
    previously set up in the test.
    """

    def __init__(self, tables, source='test'):
        from tilequeue.process import lookup_source, Source
        self.tables = tables
        # first look up source, in case it's a real one that we're testing.
        # if not, then set it to a test value
        self.source = lookup_source(source) or Source(source, source)
        assert isinstance(self.source, Source)

    def __call__(self, table_name):
        from tilequeue.query.common import Table
        return Table(self.source, self.tables.get(table_name, []))

class ConstantStorage(object):

    def __init__(self, tables):
        self.tables = tables

    def __call__(self, top_tile):
        return self.tables

class RawrTestCase(unittest.TestCase):
    """
    Base layer of the tests, providing a utility function to create a data
    fetcher with a set of mocked data.
    """

    def _make(self, min_zoom_fn, props_fn, tables, tile_pyramid,
              layer_name='testlayer', label_placement_layers={},
              min_z=10, max_z=16):
        from tilequeue.query.common import LayerInfo
        from tilequeue.query.rawr import make_rawr_data_fetcher

        layers = {layer_name: LayerInfo(min_zoom_fn, props_fn)}
        storage = ConstantStorage(tables)
        indexes_cfg = [dict(type="osm")]
        return make_rawr_data_fetcher(
            min_z, max_z, storage, layers, indexes_cfg,
            label_placement_layers=label_placement_layers)

# the call to DataFetcher.fetch_tiles wants a list of "data" dictionaries,
# each with a 'coord' key. this utility function just repackages a single
# coordinate in the way it wants.
def _wrap(coord):
    data = dict(coord=coord)
    return [data]

class TestQueryRawr(RawrTestCase):

    def test_query_simple(self):
        # just check that we can get back the mock data we put into a tile,
        # and that the indexing/fetching code respects the tile boundary and
        # min_zoom function.

        from shapely.geometry import Point
        from tilequeue.query.rawr import TilePyramid
        from tilequeue.tile import coord_to_mercator_bounds
        from tilequeue.tile import mercator_point_to_coord

        feature_min_zoom = 11

        def min_zoom_fn(shape, props, fid, meta):
            return feature_min_zoom

        shape = Point(0, 0)
        # get_table(table_name) should return a generator of rows.
        tables = TestGetTable({
            'planet_osm_point': [(0, shape.wkb, {})],
        })

        zoom = 10
        max_zoom = zoom + 5
        coord = mercator_point_to_coord(zoom, shape.x, shape.y)
        tile_pyramid = TilePyramid(zoom, coord.column, coord.row, max_zoom)

        fetch = self._make(min_zoom_fn, None, tables, tile_pyramid)

        # first, check that it can get the original item back when both the
        # min zoom filter and geometry filter are okay.
        feature_coord = mercator_point_to_coord(
            feature_min_zoom, shape.x, shape.y)
        for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
            read_rows = fetcher(
                feature_min_zoom, coord_to_mercator_bounds(feature_coord))

        self.assertEquals(1, len(read_rows))
        read_row = read_rows[0]
        self.assertEquals(0, read_row.get('__id__'))
        # query processing code expects WKB bytes in the __geometry__ column
        self.assertEquals(shape.wkb, read_row.get('__geometry__'))
        self.assertEquals({'min_zoom': 11},
                          read_row.get('__testlayer_properties__'))

        # now, check that if the min zoom or geometry filters would exclude
        # the feature then it isn't returned.
        for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
            read_rows = fetcher(zoom, coord_to_mercator_bounds(coord))
        self.assertEquals(0, len(read_rows))

        for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
            read_rows = fetcher(
                feature_min_zoom, coord_to_mercator_bounds(
                    feature_coord.left()))
        self.assertEquals(0, len(read_rows))

    def test_query_min_zoom_fraction(self):
        # test that fractional min zooms are included in their "floor" zoom
        # tile. this is to allow over-zooming of a zoom N tile until N+1,
        # where the next zoom tile kicks in.

        from shapely.geometry import Point
        from tilequeue.query.rawr import TilePyramid
        from tilequeue.tile import coord_to_mercator_bounds
        from tilequeue.tile import mercator_point_to_coord

        def min_zoom_fn(shape, props, fid, meta):
            return 11.999

        shape = Point(0, 0)
        tables = TestGetTable({
            'planet_osm_point': [(0, shape.wkb, {})]
        })

        zoom = 10
        max_zoom = zoom + 5
        coord = mercator_point_to_coord(zoom, shape.x, shape.y)
        tile_pyramid = TilePyramid(zoom, coord.column, coord.row, max_zoom)

        fetcher = self._make(min_zoom_fn, None, tables, tile_pyramid)

        # check that the fractional zoom of 11.999 means that it's included in
        # the zoom 11 tile, but not the zoom 10 one.
        feature_coord = mercator_point_to_coord(11, shape.x, shape.y)
        for fetch, _ in fetcher.fetch_tiles(_wrap(coord)):
            read_rows = fetch(11, coord_to_mercator_bounds(feature_coord))
        self.assertEquals(1, len(read_rows))

        feature_coord = feature_coord.zoomBy(-1).container()
        for fetch, _ in fetcher.fetch_tiles(_wrap(coord)):
            read_rows = fetch(10, coord_to_mercator_bounds(feature_coord))
        self.assertEquals(0, len(read_rows))

    def test_query_past_max_zoom(self):
        # check that features with a min_zoom beyond the maximum zoom are still
        # included at the maximum zoom. since this is the last zoom level we
        # generate, it must include everything.

        from shapely.geometry import Point
        from tilequeue.query.rawr import TilePyramid
        from tilequeue.tile import coord_to_mercator_bounds
        from tilequeue.tile import mercator_point_to_coord

        def min_zoom_fn(shape, props, fid, meta):
            return 20

        shape = Point(0, 0)
        tables = TestGetTable({
            'planet_osm_point': [(0, shape.wkb, {})]
        })

        zoom = 10
        max_zoom = zoom + 6
        coord = mercator_point_to_coord(zoom, shape.x, shape.y)
        tile_pyramid = TilePyramid(zoom, coord.column, coord.row, max_zoom)

        fetch = self._make(min_zoom_fn, None, tables, tile_pyramid)

        # the min_zoom of 20 should mean that the feature is included at zoom
        # 16, even though 16<20, because 16 is the "max zoom" at which all the
        # data is included.
        feature_coord = mercator_point_to_coord(16, shape.x, shape.y)
        for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
            read_rows = fetcher(16, coord_to_mercator_bounds(feature_coord))
        self.assertEquals(1, len(read_rows))

        # but it should not exist at zoom 15
        feature_coord = feature_coord.zoomBy(-1).container()
        for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
            read_rows = fetcher(10, coord_to_mercator_bounds(feature_coord))
        self.assertEquals(0, len(read_rows))

    def test_root_relation_id(self):
        # check the logic for finding a root relation ID for station complexes.

        from shapely.geometry import Point
        from tilequeue.query.rawr import TilePyramid
        from tilequeue.tile import coord_to_mercator_bounds
        from tilequeue.tile import mercator_point_to_coord

        def min_zoom_fn(shape, props, fid, meta):
            return 10

        def _test(rels, expected_root_id):
            shape = Point(0, 0)
            props = {
                'railway': 'station',
                'name': 'Foo Station',
            }
            tables = TestGetTable({
                'planet_osm_point': [(1, shape.wkb, props)],
                'planet_osm_rels': rels,
            })

            zoom = 10
            max_zoom = zoom + 6
            coord = mercator_point_to_coord(zoom, shape.x, shape.y)
            tile_pyramid = TilePyramid(zoom, coord.column, coord.row, max_zoom)

            fetch = self._make(min_zoom_fn, None, tables, tile_pyramid,
                               layer_name='pois')

            feature_coord = mercator_point_to_coord(16, shape.x, shape.y)
            for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
                read_rows = fetcher(16, coord_to_mercator_bounds(
                    feature_coord))
            self.assertEquals(1, len(read_rows))

            props = read_rows[0]['__pois_properties__']
            self.assertEquals(expected_root_id,
                              props.get('mz_transit_root_relation_id'))

        # the fixture code expects "raw" relations as if they come straight
        # from osm2pgsql. the structure is a little cumbersome, so this
        # utility function constructs it from a more readable function call.
        def _rel(id, nodes=None, ways=None, rels=None):
            way_off = len(nodes) if nodes else 0
            rel_off = way_off + (len(ways) if ways else 0)
            parts = (nodes or []) + (ways or []) + (rels or [])
            members = [""] * len(parts)
            tags = ['type', 'site']
            return (id, way_off, rel_off, parts, members, tags)

        # one level of relations - this one directly contains the station
        # node.
        _test([_rel(2, nodes=[1])], 2)

        # two levels of relations r3 contains r2 contains n1.
        _test([_rel(2, nodes=[1]), _rel(3, rels=[2])], 3)

        # asymmetric diamond pattern. r2 and r3 both contain n1, r4 contains
        # r3 and r5 contains both r4 and r2, making it the "top" relation.
        _test([
            _rel(2, nodes=[1]),
            _rel(3, nodes=[1]),
            _rel(4, rels=[3]),
            _rel(5, rels=[2, 4]),
        ], 5)

    def test_query_source(self):
        # check that the source is added to the result properties, and that
        # it overrides any existing source.

        from shapely.geometry import Point
        from tilequeue.query.rawr import TilePyramid
        from tilequeue.tile import coord_to_mercator_bounds
        from tilequeue.tile import mercator_point_to_coord

        feature_min_zoom = 11

        def min_zoom_fn(shape, props, fid, meta):
            return feature_min_zoom

        shape = Point(0, 0)
        # get_table(table_name) should return a generator of rows.
        tables = TestGetTable({
            'planet_osm_point': [(0, shape.wkb,
                                  {'source': 'originalrowsource'})],
        }, source='testingquerysource')

        zoom = 10
        max_zoom = zoom + 5
        coord = mercator_point_to_coord(zoom, shape.x, shape.y)
        tile_pyramid = TilePyramid(zoom, coord.column, coord.row, max_zoom)

        fetch = self._make(min_zoom_fn, None, tables, tile_pyramid)

        # first, check that it can get the original item back when both the
        # min zoom filter and geometry filter are okay.
        feature_coord = mercator_point_to_coord(
            feature_min_zoom, shape.x, shape.y)
        for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
            read_rows = fetcher(
                feature_min_zoom, coord_to_mercator_bounds(feature_coord))

        self.assertEquals(1, len(read_rows))
        read_row = read_rows[0]
        self.assertEquals(0, read_row.get('__id__'))
        # query processing code expects WKB bytes in the __geometry__ column
        self.assertEquals(shape.wkb, read_row.get('__geometry__'))
        self.assertEquals({'min_zoom': 11},
                          read_row.get('__testlayer_properties__'))
        self.assertEquals({'source': 'testingquerysource'},
                          read_row.get('__properties__'))

class TestLabelPlacement(RawrTestCase):

    def _test(self, layer_name, props):
        from ModestMaps.Core import Coordinate
        from tilequeue.tile import coord_to_mercator_bounds
        from shapely.geometry import box
        from tilequeue.query.rawr import TilePyramid

        top_zoom = 10
        max_zoom = top_zoom + 6

        def min_zoom_fn(shape, props, fid, meta):
            return top_zoom

        tile = Coordinate(zoom=15, column=0, row=0)
        top_tile = tile.zoomTo(top_zoom).container()
        tile_pyramid = TilePyramid(
            top_zoom, top_tile.column, top_tile.row, max_zoom)

        bounds = coord_to_mercator_bounds(tile)
        shape = box(*bounds)
        tables = TestGetTable({
            'planet_osm_polygon': [
                (1, shape.wkb, props),
            ]
        })

        label_placement_layers = {
            'polygon': set([layer_name]),
        }
        fetch = self._make(
            min_zoom_fn, None, tables, tile_pyramid, layer_name=layer_name,
            label_placement_layers=label_placement_layers)

        for fetcher, _ in fetch.fetch_tiles(_wrap(top_tile)):
            read_rows = fetcher(tile.zoom, bounds)
        return read_rows

    def test_named_item(self):
        # check that a label is generated for features in label placement
        # layers.

        from shapely import wkb

        layer_name = 'testlayer'
        read_rows = self._test(layer_name, {'name': 'Foo'})

        self.assertEquals(1, len(read_rows))

        label_prop = '__label__'
        self.assertTrue(label_prop in read_rows[0])
        point = wkb.loads(read_rows[0][label_prop])
        self.assertEqual(point.geom_type, 'Point')

class TestGeometryClipping(RawrTestCase):

    def _test(self, layer_name, tile, factor):
        from shapely.geometry import box
        from tilequeue.query.rawr import TilePyramid
        from tilequeue.tile import coord_to_mercator_bounds

        top_zoom = 10
        max_zoom = top_zoom + 6

        def min_zoom_fn(shape, props, fid, meta):
            return top_zoom

        top_tile = tile.zoomTo(top_zoom).container()
        tile_pyramid = TilePyramid(
            top_zoom, top_tile.column, top_tile.row, max_zoom)

        bounds = coord_to_mercator_bounds(tile)
        boxwidth = bounds[2] - bounds[0]
        boxheight = bounds[3] - bounds[1]
        # make shape overlap the edges of the bounds. that way we can check to
        # see if the shape gets clipped.
        shape = box(bounds[0] - factor * boxwidth,
                    bounds[1] - factor * boxheight,
                    bounds[2] + factor * boxwidth,
                    bounds[3] + factor * boxheight)

        props = {'name': 'Foo'}

        tables = TestGetTable({
            'planet_osm_polygon': [
                (1, shape.wkb, props),
            ],
        })

        fetch = self._make(
            min_zoom_fn, None, tables, tile_pyramid, layer_name=layer_name)

        for fetcher, _ in fetch.fetch_tiles(_wrap(top_tile)):
            read_rows = fetcher(tile.zoom, bounds)
        self.assertEqual(1, len(read_rows))
        return read_rows[0]

    def test_normal_layer(self):
        # check that normal layer geometries are clipped to the bounding box of
        # the tile.

        from ModestMaps.Core import Coordinate
        from tilequeue.tile import coord_to_mercator_bounds
        from shapely import wkb

        tile = Coordinate(zoom=15, column=10, row=10)
        bounds = coord_to_mercator_bounds(tile)

        read_row = self._test('testlayer', tile, 1.0)
        clipped_shape = wkb.loads(read_row['__geometry__'])
        # for normal layers, clipped shape is inside the bounds of the tile.
        x_factor = ((clipped_shape.bounds[2] - clipped_shape.bounds[0]) /
                    (bounds[2] - bounds[0]))
        y_factor = ((clipped_shape.bounds[2] - clipped_shape.bounds[0]) /
                    (bounds[2] - bounds[0]))
        self.assertAlmostEqual(1.0, x_factor)
        self.assertAlmostEqual(1.0, y_factor)

    def test_water_layer(self):
        # water layer should be clipped to the tile bounds expanded by 10%.

        from ModestMaps.Core import Coordinate
        from tilequeue.tile import coord_to_mercator_bounds
        from shapely import wkb

        tile = Coordinate(zoom=15, column=10, row=10)
        bounds = coord_to_mercator_bounds(tile)

        read_row = self._test('water', tile, 1.0)
        clipped_shape = wkb.loads(read_row['__geometry__'])
        # for water layer, the geometry should be 10% larger than the tile
        # bounds.
        x_factor = ((clipped_shape.bounds[2] - clipped_shape.bounds[0]) /
                    (bounds[2] - bounds[0]))
        y_factor = ((clipped_shape.bounds[2] - clipped_shape.bounds[0]) /
                    (bounds[2] - bounds[0]))
        self.assertAlmostEqual(1.1, x_factor)
        self.assertAlmostEqual(1.1, y_factor)

class TestNameHandling(RawrTestCase):

    def _test(self, input_layer_names, expected_layer_names):
        from shapely.geometry import Point
        from tilequeue.query.common import LayerInfo
        from tilequeue.query.rawr import make_rawr_data_fetcher
        from tilequeue.tile import coord_to_mercator_bounds
        from tilequeue.tile import mercator_point_to_coord

        top_zoom = 10
        max_zoom = top_zoom + 6

        def min_zoom_fn(shape, props, fid, meta):
            return top_zoom

        def props_fn(shape, props, fid, meta):
            return {}

        shape = Point(0, 0)
        props = {'name': 'Foo', 'name:en': 'Bar'}

        source = 'test'
        tables = TestGetTable({
            'planet_osm_point': [
                (1, shape.wkb, props),
            ],
        }, source)

        tile = mercator_point_to_coord(max_zoom, shape.x, shape.y)
        top_tile = tile.zoomTo(top_zoom).container()

        layers = {}
        for name in input_layer_names:
            layers[name] = LayerInfo(min_zoom_fn, props_fn)
        storage = ConstantStorage(tables)
        fetch = make_rawr_data_fetcher(
            top_zoom, max_zoom, storage, layers, [dict(type="osm")])

        for fetcher, _ in fetch.fetch_tiles(_wrap(top_tile)):
            read_rows = fetcher(tile.zoom, coord_to_mercator_bounds(tile))
        # the RAWR query goes over features multiple times because of the
        # indexing, so we can't rely on all the properties for one feature to
        # be all together in the same place. this loops over all the features,
        # checking that there's only really one of them and gathering together
        # all the __%s_properties__ from all the rows for further testing.
        all_props = {}
        for row in read_rows:
            self.assertEquals(1, row['__id__'])
            self.assertEquals(shape.wkb, row['__geometry__'])
            for key, val in row.items():
                if key.endswith('_properties__'):
                    self.assertFalse(key in all_props)
                    all_props[key] = val

        all_layer_names = set(expected_layer_names) | set(input_layer_names)
        for layer_name in all_layer_names:
            properties_name = '__%s_properties__' % layer_name
            self.assertTrue(properties_name in all_props)
            for key in props.keys():
                actual_name = all_props[properties_name].get(key)
                if layer_name in expected_layer_names:
                    expected_name = props.get(key)
                    self.assertEquals(
                        expected_name, actual_name,
                        msg=('expected=%r, actual=%r for key=%r'
                             % (expected_name, actual_name, key)))
                else:
                    # check the name doesn't appear anywhere else
                    self.assertEquals(
                        None, actual_name,
                        msg=('got actual=%r for key=%r, expected no value'
                             % (actual_name, key)))

    def test_name_single_layer(self):
        # in any oone of the pois, landuse or buildings layers, a name
        # by itself will be output in the same layer.
        for layer_name in ('pois', 'landuse', 'buildings'):
            self._test([layer_name], [layer_name])

    def test_precedence(self):
        # if the feature is in the pois layer, then that should get the name
        # and the other layers should not.
        self._test(['pois', 'landuse'], ['pois'])
        self._test(['pois', 'buildings'], ['pois'])
        self._test(['pois', 'landuse', 'buildings'], ['pois'])
        # otherwise, landuse should take precedence over buildings.
        self._test(['landuse', 'buildings'], ['landuse'])

class TestMeta(RawrTestCase):

    def test_meta_gate(self):
        # test that the meta is passed to the min zoom function, and that we
        # can use it to get information about the highways that a gate is
        # part of.

        from shapely.geometry import Point, LineString
        from tilequeue.query.rawr import TilePyramid
        from tilequeue.tile import coord_to_mercator_bounds
        from tilequeue.tile import mercator_point_to_coord

        feature_min_zoom = 11

        def min_zoom_fn(shape, props, fid, meta):
            self.assertIsNotNone(meta)

            # expect meta to have a source, which is a string name for the
            # source of the data.
            self.assertEquals('test', meta.source)

            # expect meta to have a list of relations, which is empty for this
            # test.
            self.assertEquals(0, len(meta.relations))

            # only do this for the node
            if fid == 0:
                # expect meta to have a list of ways, each of which is a (fid,
                # shape, props) tuple, of which only props is used.
                self.assertEquals(1, len(meta.ways))
                way_fid, way_shape, way_props = meta.ways[0]
                self.assertEquals(1, way_fid)
                self.assertEquals({'highway': 'secondary'}, way_props)

            # only set a min zoom for the node - this just simplifies the
            # checking later, as there'll only be one feature.
            return feature_min_zoom if fid == 0 else None

        shape = Point(0, 0)
        way_shape = LineString([[0, 0], [1, 1]])
        # get_table(table_name) should return a generator of rows.
        tables = TestGetTable({
            'planet_osm_point': [(0, shape.wkb, {'barrier': 'gate'})],
            'planet_osm_line': [(1, way_shape.wkb, {'highway': 'secondary'})],
            'planet_osm_ways': [(1, [0], ['highway', 'secondary'])],
        })

        zoom = 10
        max_zoom = zoom + 5
        coord = mercator_point_to_coord(zoom, shape.x, shape.y)
        tile_pyramid = TilePyramid(zoom, coord.column, coord.row, max_zoom)

        fetch = self._make(min_zoom_fn, None, tables, tile_pyramid)

        # first, check that it can get the original item back when both the
        # min zoom filter and geometry filter are okay.
        feature_coord = mercator_point_to_coord(
            feature_min_zoom, shape.x, shape.y)
        for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
            read_rows = fetcher(
                feature_min_zoom, coord_to_mercator_bounds(feature_coord))

        self.assertEquals(1, len(read_rows))
        read_row = read_rows[0]
        self.assertEquals(0, read_row.get('__id__'))
        # query processing code expects WKB bytes in the __geometry__ column
        self.assertEquals(shape.wkb, read_row.get('__geometry__'))
        self.assertEquals({'min_zoom': 11, 'barrier': 'gate'},
                          read_row.get('__testlayer_properties__'))

    def test_meta_route(self):
        # test that we can use meta in the min zoom function to find out which
        # route(s) a road is part of.

        from shapely.geometry import LineString
        from tilequeue.query.rawr import TilePyramid
        from tilequeue.tile import coord_to_mercator_bounds
        from tilequeue.tile import mercator_point_to_coord
        from tilequeue.query.common import deassoc

        feature_min_zoom = 11

        rel_tags = [
            'type', 'route',
            'route', 'road',
            'ref', '101',
        ]

        def min_zoom_fn(shape, props, fid, meta):
            self.assertIsNotNone(meta)

            # expect meta to have a source, which is a string name for the
            # source of the data.
            self.assertEquals('test', meta.source)

            # expect meta to have a list of ways, but empty for this test.
            self.assertEquals(0, len(meta.ways))

            # expect meta to have a list of relations, each of which is a dict
            # containing at least the key 'tags' mapped to a list of
            # alternating k, v suitable for passing into deassoc().
            self.assertEquals(1, len(meta.relations))
            rel = meta.relations[0]
            self.assertIsInstance(rel, dict)
            self.assertIn('tags', rel)
            self.assertEquals(deassoc(rel_tags), deassoc(rel['tags']))

            return feature_min_zoom

        shape = LineString([[0, 0], [1, 1]])
        # get_table(table_name) should return a generator of rows.
        tables = TestGetTable({
            'planet_osm_line': [(1, shape.wkb, {'highway': 'secondary'})],
            'planet_osm_rels': [(2, 0, 1, [1], [''], rel_tags)],
        })

        zoom = 10
        max_zoom = zoom + 5
        coord = mercator_point_to_coord(zoom, *shape.coords[0])
        tile_pyramid = TilePyramid(zoom, coord.column, coord.row, max_zoom)

        fetch = self._make(min_zoom_fn, None, tables, tile_pyramid)

        # first, check that it can get the original item back when both the
        # min zoom filter and geometry filter are okay.
        feature_coord = mercator_point_to_coord(
            feature_min_zoom, *shape.coords[0])
        for fetcher, _ in fetch.fetch_tiles(_wrap(coord)):
            read_rows = fetcher(
                feature_min_zoom, coord_to_mercator_bounds(feature_coord))

        self.assertEquals(1, len(read_rows))
        read_row = read_rows[0]
        self.assertEquals(1, read_row.get('__id__'))
        self.assertEquals({'min_zoom': 11, 'highway': 'secondary'},
                          read_row.get('__testlayer_properties__'))

class TestTileFootprint(unittest.TestCase):

    def test_single_tile(self):
        from tilequeue.query.rawr import _tiles
        from raw_tiles.tile import Tile
        from raw_tiles.util import bbox_for_tile

        tile = Tile(15, 5241, 12665)

        zoom = tile.z
        unpadded_bounds = bbox_for_tile(tile.z, tile.x, tile.y)
        tiles = _tiles(zoom, unpadded_bounds)

        self.assertEquals([tile], list(tiles))

    def test_multiple_tiles(self):
        from tilequeue.query.rawr import _tiles
        from raw_tiles.tile import Tile
        from raw_tiles.util import bbox_for_tile

        tile = Tile(15, 5241, 12665)

        # query at one zoom higher - should get 4 child tiles.
        zoom = tile.z + 1
        unpadded_bounds = bbox_for_tile(tile.z, tile.x, tile.y)
        tiles = list(_tiles(zoom, unpadded_bounds))

        self.assertEquals(4, len(tiles))
        for child in tiles:
            self.assertEquals(tile, child.parent())

    def test_corner_overlap(self):
        # a box around the corner of a tile should return the four
        # neighbours of that tile.
        from tilequeue.query.rawr import _tiles
        from raw_tiles.tile import Tile
        from raw_tiles.util import bbox_for_tile

        tile = Tile(15, 5241, 12665)

        zoom = tile.z
        tile_bbox = bbox_for_tile(tile.z, tile.x, tile.y)

        # extract the top left corner
        x = tile_bbox[0]
        y = tile_bbox[3]
        # make a small bounding box around that
        w = 10
        unpadded_bounds = (x - w, y - w,
                           x + w, y + w)
        tiles = set(_tiles(zoom, unpadded_bounds))

        expected = set()
        for dx in (0, -1):
            for dy in (0, -1):
                expected.add(Tile(tile.z, tile.x + dx, tile.y + dy))

        self.assertEquals(expected, tiles)

class TestBoundaries(RawrTestCase):

    def _fetch_data(self, shape_fn, source_table):
        from tilequeue.query.common import LayerInfo
        from tilequeue.query.rawr import make_rawr_data_fetcher
        from tilequeue.tile import coord_to_mercator_bounds
        from ModestMaps.Core import Coordinate

        top_zoom = 10
        max_zoom = top_zoom + 6

        def min_zoom_fn(shape, props, fid, meta):
            return top_zoom

        def props_fn(shape, props, fid, meta):
            return {'kind': 'country'}

        z, x, y = (max_zoom, 0, 0)
        tile = Coordinate(zoom=z, column=x, row=y)
        top_tile = tile.zoomTo(top_zoom).container()

        bounds = coord_to_mercator_bounds(tile)
        shape = shape_fn(bounds)

        props = {
            'name': 'Foo',
            'admin_level': '2',
            'boundary': 'administrative',
        }

        source = 'test'
        tables = TestGetTable({
            source_table: [
                (1, shape.wkb, props),
            ],
        }, source)

        layers = {
            'boundaries': LayerInfo(min_zoom_fn, props_fn),
        }
        storage = ConstantStorage(tables)
        fetch = make_rawr_data_fetcher(
            top_zoom, max_zoom, storage, layers, [dict(type="osm")])

        for fetcher, _ in fetch.fetch_tiles(_wrap(top_tile)):
            read_rows = fetcher(tile.zoom, coord_to_mercator_bounds(tile))

        return read_rows

    def test_linestrings_dropped(self):
        # test that linestrings in the RAWR tile don't make it into the tile.
        from shapely.geometry import LineString

        def _tile_diagonal(bounds):
            return LineString([
                [bounds[0], bounds[1]],
                [bounds[2], bounds[3]],
            ])

        read_rows = self._fetch_data(_tile_diagonal, 'planet_osm_line')
        self.assertEqual(read_rows, [])

    def test_boundaries_from_polygons(self):
        # check that a polygon in the RAWR tile contributes its oriented
        # (anti-clockwise) boundary to the tile data.
        from shapely.geometry import Polygon

        def _tile_triangle(bounds):
            # note: this triangle polygon is the wrong way around (clockwise,
            # rather than anti-clockwise). this is deliberate, and the code
            # should deal with it.
            return Polygon([
                [bounds[0], bounds[1]],
                [bounds[2], bounds[1]],
                [bounds[0], bounds[3]],
                [bounds[0], bounds[1]],
            ])

        read_rows = self._fetch_data(_tile_triangle, 'planet_osm_polygon')

        self.assertEqual(len(read_rows), 1)
        props = read_rows[0]['__boundaries_properties__']
        self.assertEqual(props.get('boundary'), 'administrative')
        # check no area
        self.assertIsNone(props.get('area'))

    def test_boundaries_from_multipolygons(self):
        # check that the boundary extraction code also works for multipolygons
        from shapely.geometry import Polygon, MultiPolygon

        def _tile_squares(bounds):
            # maxy      +----+
            #           | b  |
            # midy +----+----+
            #      | a  |
            # miny +----+
            #      minx midx maxx

            minx, miny, maxx, maxy = bounds
            midx = 0.5 * (minx + maxx)
            midy = 0.5 * (miny + maxy)

            a = Polygon([
                [minx, miny],
                [minx, midy],
                [midx, midy],
                [midx, miny],
                [minx, miny],
            ])

            b = Polygon([
                [midx, midy],
                [midx, maxy],
                [maxx, maxy],
                [maxx, midy],
                [midy, midy],
            ])

            return MultiPolygon([a, b])

        read_rows = self._fetch_data(_tile_squares, 'planet_osm_polygon')

        self.assertEqual(len(read_rows), 1)
        props = read_rows[0]['__boundaries_properties__']
        self.assertEqual(props.get('boundary'), 'administrative')
        # check no area
        self.assertIsNone(props.get('area'))

class TestBufferedLand(RawrTestCase):

    def test_buffered_land(self):
        # the buffered land is a polygon in the boundaries table (sort of),
        # but we shouldn't turn it into linestrings of the exterior ring. it
        # should stay as a polygon otherwise the border features won't be
        # correctly assigned maritime boundary properties, and they'll all
        # appear to be maritime boundaries. :-(
        from tilequeue.query.common import LayerInfo
        from tilequeue.query.rawr import make_rawr_data_fetcher
        from tilequeue.tile import coord_to_mercator_bounds
        from ModestMaps.Core import Coordinate
        from shapely.geometry import Polygon
        import shapely.wkb

        top_zoom = 10
        max_zoom = top_zoom + 6

        def min_zoom_fn(shape, props, fid, meta):
            return 8

        def props_fn(shape, props, fid, meta):
            props['kind'] = 'maritime'
            return props

        z, x, y = (max_zoom, 0, 0)
        tile = Coordinate(zoom=z, column=x, row=y)
        top_tile = tile.zoomTo(top_zoom).container()

        bounds = coord_to_mercator_bounds(tile)
        shape = Polygon([
            [bounds[0], bounds[1]],
            [bounds[0], bounds[3]],
            [bounds[2], bounds[1]],
            [bounds[0], bounds[1]],
        ])

        props = {
            'kind': 'maritime',
            'maritime_boundary': True,
            'source': 'tilezen.org',
            'min_zoom': 0,
        }

        source = 'tilezen.org'
        tables = TestGetTable({
            'buffered_land': [
                (1, shape.wkb, props),
            ],
        }, source)

        layers = {
            'boundaries': LayerInfo(min_zoom_fn, props_fn),
        }
        storage = ConstantStorage(tables)
        index_cfg = [{
            'type': 'simple',
            'table': 'buffered_land',
            'layer': 'boundaries',
        }]
        fetch = make_rawr_data_fetcher(
            top_zoom, max_zoom, storage, layers, index_cfg)

        for fetcher, _ in fetch.fetch_tiles(_wrap(top_tile)):
            read_rows = fetcher(tile.zoom, coord_to_mercator_bounds(tile))

        self.assertEqual(len(read_rows), 1)
        props = read_rows[0]['__boundaries_properties__']

        self.assertEqual(props.get('kind'), 'maritime')
        # check no special boundaries geometry - should just be the polygon
        self.assertIsNone(read_rows[0].get('__boundaries_geometry__'))

        shape = shapely.wkb.loads(read_rows[0]['__geometry__'])
        self.assertEqual(shape.geom_type, 'Polygon')


text:
using UnityEngine;
using UnityEditor;

using HutongGames.PlayMaker.Actions;
using HutongGames.PlayMakerEditor;

[CustomActionEditor(typeof(GetAnimatorLayerWeight))]
public class GetAnimatorLayerWeightActionEditor : OnAnimatorUpdateActionEditorBase
{

	public override bool OnGUI()
	{
		EditField("gameObject");
		EditField("layerIndex");
		EditField("layerWeight");

		bool changed = EditEveryFrameField();

		return GUI.changed || changed;
	}

}


text:
import os,sys
sys.path.append(os.getcwd().split('slps')[0]+'slps/shared/python')
import BGF
import metrics

if __name__ == "__main__":
	if len(sys.argv) != 2:
		print 'This tool calculates a HAL metric for any given BGF grammar.'
		print 'Usage:'
		print '      '+sys.argv[0]+' <bgf-input>'
		sys.exit(1)
	bgf = BGF.Grammar()
	bgf.parse(sys.argv[1])
	print int(round(metrics.HAEFF(bgf)))
	sys.exit(0)


text:
#ifndef FEEDFORWARD_CONTROLLER_H
#define FEEDFORWARD_CONTROLLER_H

#include "Controller.h"
#include "StateEstimator.h"
#include <robotics/Wrench.h>
#include <utils/SmartPointer.h>

/** @ingroup Control
 * @brief A class that adds a feedforward torque to the basic
 * control.  The necessary feedforward torque is estimated assuming the
 * robot is fixed-base.
 */
class FeedforwardController : public RobotController
{
 public:
  FeedforwardController(Robot& robot,SmartPointer<RobotController> base=NULL);
  virtual ~FeedforwardController() {}
  virtual const char* Type() const { return "FeedforwardController"; }
  virtual void Update(Real dt);
  virtual void Reset();
  virtual bool ReadState(File& f);
  virtual bool WriteState(File& f) const;

  //getters/setters
  virtual map<string,string> Settings() const;
  virtual bool GetSetting(const string& name,string& str) const;
  virtual bool SetSetting(const string& name,const string& str);

  //commands
  void ZeroForces();
  void AddForce(int link,const Vector3& f,const Vector3& worldpt);
  virtual vector<string> Commands() const;
  virtual bool SendCommand(const string& name,const string& str);

  //helpers
  void SolveTorques(Vector& torques,Real dt);

  SmartPointer<RobotController> base;
  SmartPointer<RobotStateEstimator> stateEstimator;
  bool enableGravityCompensation,enableFeedforwardAcceleration;
  Vector3 gravity;
  //external forces and moments about the link origin
  vector<Wrench> wrenches;
};

#endif


text:
using namespace llvm;

// Class destructor
ValueSymbolTable::~ValueSymbolTable() {
#ifndef NDEBUG   // Only do this in -g mode...
  for (iterator VI = vmap.begin(), VE = vmap.end(); VI != VE; ++VI)
    dbgs() << "Value still in symbol table! Type = '"
           << VI->getValue()->getType()->getDescription() << "' Name = '"
           << VI->getKeyData() << "'\n";
  assert(vmap.empty() && "Values remain in symbol table!");
#endif
}

// Insert a value into the symbol table with the specified name...
//
void ValueSymbolTable::reinsertValue(Value* V) {
  assert(V->hasName() && "Can't insert nameless Value into symbol table");

  // Try inserting the name, assuming it won't conflict.
  if (vmap.insert(V->Name)) {
    //DEBUG(dbgs() << " Inserted value: " << V->Name << ": " << *V << "\n");
    return;
  }

  // Otherwise, there is a naming conflict.  Rename this value.
  SmallString<256> UniqueName(V->getName().begin(), V->getName().end());

  // The name is too already used, just free it so we can allocate a new name.
  V->Name->Destroy();

  unsigned BaseSize = UniqueName.size();
  while (1) {
    // Trim any suffix off and append the next number.
    UniqueName.resize(BaseSize);
    raw_svector_ostream(UniqueName) << ++LastUnique;

    // Try insert the vmap entry with this suffix.
    ValueName &NewName =
      vmap.GetOrCreateValue(StringRef(UniqueName.data(),
                                      UniqueName.size()));
    if (NewName.getValue() == 0) {
      // Newly inserted name.  Success!
      NewName.setValue(V);
      V->Name = &NewName;
     //DEBUG(dbgs() << " Inserted value: " << UniqueName << ": " << *V << "\n");
      return;
    }
  }
}

void ValueSymbolTable::removeValueName(ValueName *V) {
  //DEBUG(dbgs() << " Removing Value: " << V->getKeyData() << "\n");
  // Remove the value from the symbol table.
  vmap.remove(V);
}

/// createValueName - This method attempts to create a value name and insert
/// it into the symbol table with the specified name.  If it conflicts, it
/// auto-renames the name and returns that instead.
ValueName *ValueSymbolTable::createValueName(StringRef Name, Value *V) {
  // In the common case, the name is not already in the symbol table.
  ValueName &Entry = vmap.GetOrCreateValue(Name);
  if (Entry.getValue() == 0) {
    Entry.setValue(V);
    //DEBUG(dbgs() << " Inserted value: " << Entry.getKeyData() << ": "
    //           << *V << "\n");
    return &Entry;
  }

  // Otherwise, there is a naming conflict.  Rename this value.
  SmallString<128> UniqueName(Name.begin(), Name.end());

  while (1) {
    // Trim any suffix off and append the next number.
    UniqueName.resize(Name.size());
    raw_svector_ostream(UniqueName) << ++LastUnique;

    // Try insert the vmap entry with this suffix.
    ValueName &NewName =
      vmap.GetOrCreateValue(StringRef(UniqueName.data(),
                                      UniqueName.size()));
    if (NewName.getValue() == 0) {
      // Newly inserted name.  Success!
      NewName.setValue(V);
     //DEBUG(dbgs() << " Inserted value: " << UniqueName << ": " << *V << "\n");
      return &NewName;
    }
  }
}

// dump - print out the symbol table
//
void ValueSymbolTable::dump() const {
  //DEBUG(dbgs() << "ValueSymbolTable:\n");
  for (const_iterator I = begin(), E = end(); I != E; ++I) {
    //DEBUG(dbgs() << "  '" << I->getKeyData() << "' = ");
    I->getValue()->dump();
    //DEBUG(dbgs() << "\n");
  }
}

MDSymbolTable::~MDSymbolTable() { }


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>discovery</artifactId>
        <groupId>org.inaetics.dronessimulator</groupId>
        <version>0.1</version>
        <relativePath>../pom.xml</relativePath>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.inaetics.dronessimulator.discovery</groupId>
    <artifactId>discovery-api</artifactId>
    <version>0.1</version>
    <name>Discovery API</name>

    <packaging>bundle</packaging>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>

            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Export-Package>org.inaetics.dronessimulator.discovery.api.*</Export-Package>
                    </instructions>
                </configuration>
            </plugin>

        </plugins>

        <!--<plugins>-->
            <!--<plugin>-->
                <!--<groupId>org.apache.felix</groupId>-->
                <!--<artifactId>maven-bundle-plugin</artifactId>-->

                <!--<!–Note: This probably doesn't have to be exported, because it's the API. Adding it to get rid of the "bundle-not-exported" warnings–>-->
                <!--<extensions>true</extensions>-->
                <!--<configuration>-->
                    <!--<instructions>-->
                        <!--<Export-Package>org.inaetics.dronessimulator.discovery.api</Export-Package>-->
                    <!--</instructions>-->
                <!--</configuration>-->
                <!--<!–     –>-->

            <!--</plugin>-->
            <!--<plugin>-->
                <!--<groupId>org.apache.maven.plugins</groupId>-->
                <!--<artifactId>maven-jar-plugin</artifactId>-->
                <!--<version>2.2</version>-->
                <!--<executions>-->
                    <!--<execution>-->
                        <!--<goals>-->
                            <!--<goal>test-jar</goal>-->
                        <!--</goals>-->
                    <!--</execution>-->
                <!--</executions>-->
            <!--</plugin>-->
        <!--</plugins>-->
    </build>
</project>


text:
!!! summary ""
    CoreInstallersBundle / [EagerSingletonInstaller](https://github.com/xvik/dropwizard-guicey/tree/master/src/main/java/ru/vyarus/dropwizard/guice/module/installer/feature/eager/EagerSingletonInstaller.java)

## Recognition

Detects classes annotated with `#!java @EagerSingleton` annotation and register them in guice injector.
It is equivalent of eager singleton registration `#!java bind(type).asEagerSingleton()`.

Useful in case when you have bean not injected by other beans (so guice can't register
it through aot). Normally, you would have to manually register such bean in module.

Most likely, such bean will contain initialization logic.
Ideal for cases not directly covered by installers. For example:

```java
@EagerSingleton
public class MyListener implements LifeCycle.Listener {

    @Inject
    public MyListener(Environment environment) {
        environment.lifecicle.addListener(this);
    }
}
```

Class will be recognized by eager singleton installer, environment object injected by guice and we manually register listener.

May be used in conjunction with `#!java @PostConstruct` annotations (e.g. using [ext-annotations](https://github.com/xvik/guice-ext-annotations)):
installer finds and register bean and post construct annotation could run some logic. Note: this approach is against guice philosophy and should
be used for quick prototyping only.


text:
package org.gradle.plugin.use.internal;

import org.gradle.api.initialization.dsl.ScriptHandler;
import org.gradle.api.internal.initialization.ClassLoaderScope;
import org.gradle.api.plugins.PluginAware;

// Implementation is provided by 'plugin-use' module
public interface PluginRequestApplicator {
    void applyPlugins(Iterable<? extends PluginRequest> requests, ScriptHandler scriptHandler, PluginAware target, ClassLoaderScope classLoaderScope);
}


text:
using System;
using System.IO;
using Microsoft.Build.Shared;
using Microsoft.Build.UnitTests.Shared;
using Xunit;

namespace Microsoft.Build.UnitTests
{
    public class TypeLoader_Dependencies_Tests
    {
        private static readonly string ProjectFileFolder = Path.Combine(BuildEnvironmentHelper.Instance.CurrentMSBuildToolsDirectory, "TaskWithDependency");
        private static readonly string ProjectFileName = "TaskWithDependencyTest.proj";
        private static readonly string TaskDllFileName = "TaskWithDependency.dll";
        private static readonly string DependencyDllFileName = "Dependency.dll";

        [Fact]
        public void LoadAssemblyAndDependency_InsideProjectFolder()
        {
            using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
            {
                string projectFilePath = Path.Combine(dir.Path, ProjectFileName);

                bool successfulExit;
                string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag", out successfulExit);
                Assert.True(successfulExit);

                string dllPath = Path.Combine(dir.Path, TaskDllFileName);

                CheckIfCorrectAssemblyLoaded(output, dllPath);
            }
        }

        [Fact]
        public void LoadAssemblyAndDependency_OutsideProjectFolder()
        {
            using (var dir = new FileUtilities.TempWorkingDirectory(ProjectFileFolder))
            {
                string projectFilePath = Path.Combine(dir.Path, ProjectFileName);

                string tempDir = MoveOrCopyDllsToTempDir(dir.Path, copy: false);
                var newTaskDllPath = Path.Combine(tempDir, TaskDllFileName);

                bool successfulExit;
                string output = RunnerUtilities.ExecMSBuild(projectFilePath + " /v:diag /p:AssemblyPath=" + newTaskDllPath, out successfulExit);
                Assert.True(successfulExit);

                CheckIfCorrectAssemblyLoaded(output, newTaskDllPath);
            }
        }

        /// <summary>
        /// </summary>
        /// <param name="copy"></param>
        /// <returns>Path to temporary directory</returns>
        private string MoveOrCopyDllsToTempDir(string originalDirectory, bool copy)
        {
            var originalTaskDllPath = Path.Combine(originalDirectory, TaskDllFileName);
            var originalDependencyDllPath = Path.Combine(originalDirectory, DependencyDllFileName);

            var temporaryDirectory = FileUtilities.GetTemporaryDirectory();

            var newTaskDllPath = Path.Combine(temporaryDirectory, TaskDllFileName);
            var newDependencyDllPath = Path.Combine(temporaryDirectory, DependencyDllFileName);

            Assert.True(File.Exists(originalTaskDllPath));
            Assert.True(File.Exists(originalDependencyDllPath));

            if (copy)
            {
                File.Copy(originalTaskDllPath, newTaskDllPath);
                File.Copy(originalDependencyDllPath, newDependencyDllPath);

                Assert.True(File.Exists(newTaskDllPath));
                Assert.True(File.Exists(newDependencyDllPath));
            }
            else
            {
                File.Move(originalTaskDllPath, newTaskDllPath);
                File.Move(originalDependencyDllPath, newDependencyDllPath);

                Assert.True(File.Exists(newTaskDllPath));
                Assert.True(File.Exists(newDependencyDllPath));
                Assert.False(File.Exists(originalTaskDllPath));
                Assert.False(File.Exists(originalDependencyDllPath));
            }

            return temporaryDirectory;
        }

        private void CheckIfCorrectAssemblyLoaded(string scriptOutput, string expectedAssemblyPath, bool expectedSuccess = true)
        {
            var successfulMessage = @"Using ""LogStringFromDependency"" task from assembly """ + expectedAssemblyPath + @""".";

            if (expectedSuccess)
            {
                Assert.Contains(successfulMessage, scriptOutput, StringComparison.OrdinalIgnoreCase);
            }
            else
            {
                Assert.DoesNotContain(successfulMessage, scriptOutput, StringComparison.OrdinalIgnoreCase);
            }
        }
    }
}


text:
import {app, BrowserWindow} from 'electron';
import menubar from 'menubar';

const storage = require('electron-storage');
let mb = menubar({maxWidth: 600, maxHeight: 300, minWidth: 600, minHeight: 300, icon: './sketch/logoSmallest.png' || './sketch/logoSmallest.png@2x' });

mb.on('ready', () => {
  console.log('Application is ready');
  mb.showWindow();
});

mb.on('after-create-window', () => {
  mb.window.loadURL(`file://${__dirname}/src/index.html`);
});


text:
using NUnit.Framework;

namespace Dehydrator
{
    [TestFixture]
    public class NoIdTest : EntityExtensionsTest<MockEntity2>
    {
        [SetUp]
        public void SetUp()
        {
            DehydratedRef = new MockEntity2 {Id = Entity.NoId, FriendlyName = "Bar"};
            ResolvedRef = new MockEntity2 {Id = Entity.NoId, FriendlyName = "Bar"};

            EntityWithDehydratedRefs = new MockEntity1
            {
                Id = 1,
                FriendlyName = "Foo",
                SingleRef = DehydratedRef
            };
            EntityWithResolvedRefs = new MockEntity1
            {
                Id = 1,
                FriendlyName = "Foo",
                SingleRef = ResolvedRef
            };
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <io.karim.MaterialTabs
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:background="@color/color_primary"
        app:mtSameWeightTabs="true"
        app:mtTextAllCaps="true" />

    <com.swapnil133609.zeuscontrols.elements.CustomViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using cn.bmob.io;

namespace bitkyShop.bean
{
    public class CommodityOrder : BmobTable
    {
        public String objectId;
        public BmobDouble price;
        public BmobInt count;

        //读字段信息
        public override void readFields(BmobInput input)
        {
            base.readFields(input);
            objectId = input.getString("objectId");
            price = input.getDouble("price");
            count = input.getInt("count");
        }

        //写字段信息
        public override void write(BmobOutput output, bool all)
        {
            base.write(output, all);
            output.Put("objectId", objectId);
            output.Put("price", price);
            output.Put("count", count);
        }
    }
}