text:
package thrift

import (
  "bufio"
  "bytes"
  "container/vector"
  "encoding/base64"
  "fmt"
  "io"
  "json"
  "math"
  "os"
  "strconv"
  "strings"
)

type _ParseContext int

const (
  _CONTEXT_IN_TOPLEVEL          _ParseContext = 1
  _CONTEXT_IN_LIST_FIRST        _ParseContext = 2
  _CONTEXT_IN_LIST              _ParseContext = 3
  _CONTEXT_IN_OBJECT_FIRST      _ParseContext = 4
  _CONTEXT_IN_OBJECT_NEXT_KEY   _ParseContext = 5
  _CONTEXT_IN_OBJECT_NEXT_VALUE _ParseContext = 6
)

func (p _ParseContext) String() string {
  switch p {
  case _CONTEXT_IN_TOPLEVEL:
    return "TOPLEVEL"
  case _CONTEXT_IN_LIST_FIRST:
    return "LIST-FIRST"
  case _CONTEXT_IN_LIST:
    return "LIST"
  case _CONTEXT_IN_OBJECT_FIRST:
    return "OBJECT-FIRST"
  case _CONTEXT_IN_OBJECT_NEXT_KEY:
    return "OBJECT-NEXT-KEY"
  case _CONTEXT_IN_OBJECT_NEXT_VALUE:
    return "OBJECT-NEXT-VALUE"
  }
  return "UNKNOWN-PARSE-CONTEXT"
}

/**
 * JSON protocol implementation for thrift.
 *
 * This protocol produces/consumes a simple output format
 * suitable for parsing by scripting languages.  It should not be
 * confused with the full-featured TJSONProtocol.
 *
 */
type TSimpleJSONProtocol struct {
  //TProtocolBase;
  trans TTransport

  /**
   * Stack of nested contexts that we may be in.
   */
  parseContextStack vector.IntVector
  /**
   * Stack of nested contexts that we may be in.
   */
  dumpContext vector.IntVector

  /**
   * Current context that we are in
   */
  writer TTransport
  reader *bufio.Reader
}

/**
 * Constructor
 */
func NewTSimpleJSONProtocol(t TTransport) *TSimpleJSONProtocol {
  v := &TSimpleJSONProtocol{trans: t,
    writer: t,
    reader: bufio.NewReader(t),
  }
  v.parseContextStack.Push(int(_CONTEXT_IN_TOPLEVEL))
  v.dumpContext.Push(int(_CONTEXT_IN_TOPLEVEL))
  return v
}

/**
 * Factory
 */
type TSimpleJSONProtocolFactory struct{}

func (p *TSimpleJSONProtocolFactory) GetProtocol(trans TTransport) TProtocol {
  return NewTSimpleJSONProtocol(trans)
}

func NewTSimpleJSONProtocolFactory() *TSimpleJSONProtocolFactory {
  return &TSimpleJSONProtocolFactory{}
}

var (
  JSON_COMMA                   []byte
  JSON_COLON                   []byte
  JSON_LBRACE                  []byte
  JSON_RBRACE                  []byte
  JSON_LBRACKET                []byte
  JSON_RBRACKET                []byte
  JSON_QUOTE                   byte
  JSON_QUOTE_BYTES             []byte
  JSON_NULL                    []byte
  JSON_TRUE                    []byte
  JSON_FALSE                   []byte
  JSON_INFINITY                string
  JSON_NEGATIVE_INFINITY       string
  JSON_NAN                     string
  JSON_INFINITY_BYTES          []byte
  JSON_NEGATIVE_INFINITY_BYTES []byte
  JSON_NAN_BYTES               []byte
  json_nonbase_map_elem_bytes  []byte
)

func init() {
  JSON_COMMA = []byte{','}
  JSON_COLON = []byte{':'}
  JSON_LBRACE = []byte{'{'}
  JSON_RBRACE = []byte{'}'}
  JSON_LBRACKET = []byte{'['}
  JSON_RBRACKET = []byte{']'}
  JSON_QUOTE = '"'
  JSON_QUOTE_BYTES = []byte{'"'}
  JSON_NULL = []byte{'n', 'u', 'l', 'l'}
  JSON_TRUE = []byte{'t', 'r', 'u', 'e'}
  JSON_FALSE = []byte{'f', 'a', 'l', 's', 'e'}
  JSON_INFINITY = "Infinity"
  JSON_NEGATIVE_INFINITY = "-Infinity"
  JSON_NAN = "NaN"
  JSON_INFINITY_BYTES = []byte{'I', 'n', 'f', 'i', 'n', 'i', 't', 'y'}
  JSON_NEGATIVE_INFINITY_BYTES = []byte{'-', 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y'}
  JSON_NAN_BYTES = []byte{'N', 'a', 'N'}
  json_nonbase_map_elem_bytes = []byte{']', ',', '['}
}

func JsonQuote(s string) string {
  b, _ := json.Marshal(s)
  s1 := string(b)
  return s1
}

func JsonUnquote(s string) (string, bool) {
  s1 := new(string)
  err := json.Unmarshal([]byte(s), s1)
  return *s1, err == nil
}

func (p *TSimpleJSONProtocol) WriteMessageBegin(name string, typeId TMessageType, seqId int32) TProtocolException {
  if e := p.OutputListBegin(); e != nil {
    return e
  }
  if e := p.WriteString(name); e != nil {
    return e
  }
  if e := p.WriteByte(byte(typeId)); e != nil {
    return e
  }
  if e := p.WriteI32(seqId); e != nil {
    return e
  }
  return nil
}

func (p *TSimpleJSONProtocol) WriteMessageEnd() TProtocolException {
  return p.OutputListEnd()
}

func (p *TSimpleJSONProtocol) WriteStructBegin(name string) TProtocolException {
  if e := p.OutputObjectBegin(); e != nil {
    return e
  }
  return nil
}

func (p *TSimpleJSONProtocol) WriteStructEnd() TProtocolException {
  return p.OutputObjectEnd()
}

func (p *TSimpleJSONProtocol) WriteFieldBegin(name string, typeId TType, id int16) TProtocolException {
  if e := p.WriteString(name); e != nil {
    return e
  }
  return nil
  /*
    	if e := p.OutputListBegin(); e != nil {
        return e
      }
      if e := p.WriteByte(byte(typeId)); e != nil {
        return e
      }
      return p.WriteI16(id)
  */
}

func (p *TSimpleJSONProtocol) WriteFieldEnd() TProtocolException {
  //return p.OutputListEnd()
  return nil
}

func (p *TSimpleJSONProtocol) WriteFieldStop() TProtocolException { return nil }

func (p *TSimpleJSONProtocol) WriteMapBegin(keyType TType, valueType TType, size int) TProtocolException {
  if e := p.OutputListBegin(); e != nil {
    return e
  }
  if e := p.WriteByte(byte(keyType)); e != nil {
    return e
  }
  if e := p.WriteByte(byte(valueType)); e != nil {
    return e
  }
  return p.WriteI32(int32(size))
}

func (p *TSimpleJSONProtocol) WriteMapEnd() TProtocolException {
  return p.OutputListEnd()
}

func (p *TSimpleJSONProtocol) WriteListBegin(elemType TType, size int) TProtocolException {
  return p.OutputElemListBegin(elemType, size)
}

func (p *TSimpleJSONProtocol) WriteListEnd() TProtocolException {
  return p.OutputListEnd()
}

func (p *TSimpleJSONProtocol) WriteSetBegin(elemType TType, size int) TProtocolException {
  return p.OutputElemListBegin(elemType, size)
}

func (p *TSimpleJSONProtocol) WriteSetEnd() TProtocolException {
  return p.OutputListEnd()
}

func (p *TSimpleJSONProtocol) WriteBool(b bool) TProtocolException {
  return p.OutputBool(b)
}

func (p *TSimpleJSONProtocol) WriteByte(b byte) TProtocolException {
  return p.WriteI32(int32(b))
}

func (p *TSimpleJSONProtocol) WriteI16(v int16) TProtocolException {
  return p.WriteI32(int32(v))
}

func (p *TSimpleJSONProtocol) WriteI32(v int32) TProtocolException {
  return p.OutputI64(int64(v))
}

func (p *TSimpleJSONProtocol) WriteI64(v int64) TProtocolException {
  return p.OutputI64(int64(v))
}

func (p *TSimpleJSONProtocol) WriteDouble(v float64) TProtocolException {
  return p.OutputF64(v)
}

func (p *TSimpleJSONProtocol) WriteString(v string) TProtocolException {
  return p.OutputString(v)
}

func (p *TSimpleJSONProtocol) WriteBinary(v []byte) TProtocolException {
  // JSON library only takes in a string,
  // not an arbitrary byte array, to ensure bytes are transmitted
  // efficiently we must convert this into a valid JSON string
  // therefore we use base64 encoding to avoid excessive escaping/quoting
  if e := p.OutputPreValue(); e != nil {
    return e
  }
  if _, e := p.writer.Write(JSON_QUOTE_BYTES); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  writer := base64.NewEncoder(base64.StdEncoding, p.writer)
  if _, e := writer.Write(v); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  if e := writer.Close(); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  if _, e := p.writer.Write(JSON_QUOTE_BYTES); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  return p.OutputPostValue()
}

/**
 * Reading methods.
 */

func (p *TSimpleJSONProtocol) ReadMessageBegin() (name string, typeId TMessageType, seqId int32, err TProtocolException) {
  if isNull, err := p.ParseListBegin(); isNull || err != nil {
    return name, typeId, seqId, err
  }
  if name, err = p.ReadString(); err != nil {
    return name, typeId, seqId, err
  }
  bTypeId, err := p.ReadByte()
  typeId = TMessageType(bTypeId)
  if err != nil {
    return name, typeId, seqId, err
  }
  if seqId, err = p.ReadI32(); err != nil {
    return name, typeId, seqId, err
  }
  return name, typeId, seqId, nil
}

func (p *TSimpleJSONProtocol) ReadMessageEnd() TProtocolException {
  return p.ParseListEnd()
}

func (p *TSimpleJSONProtocol) ReadStructBegin() (name string, err TProtocolException) {
  _, err = p.ParseObjectStart()
  return "", err
}

func (p *TSimpleJSONProtocol) ReadStructEnd() TProtocolException {
  return p.ParseObjectEnd()
}

func (p *TSimpleJSONProtocol) ReadFieldBegin() (string, TType, int16, TProtocolException) {
  if err := p.ParsePreValue(); err != nil {
    return "", STOP, 0, err
  }
  if p.reader.Buffered() < 1 {
    return "", STOP, 0, nil
  }
  b, _ := p.reader.Peek(1)
  if len(b) > 0 {
    switch b[0] {
    case JSON_RBRACE[0]:
      return "", STOP, 0, nil
    case JSON_QUOTE:
      p.reader.ReadByte()
      name, err := p.ParseStringBody()
      if err != nil {
        return name, STOP, 0, err
      }
      return name, GENERIC, -1, p.ParsePostValue()
      /*
         if err = p.ParsePostValue(); err != nil {
           return name, STOP, 0, err
         }
         if isNull, err := p.ParseListBegin(); isNull || err != nil {
           return name, STOP, 0, err
         }
         bType, err := p.ReadByte()
         thetype := TType(bType)
         if err != nil {
           return name, thetype, 0, err
         }
         id, err := p.ReadI16()
         return name, thetype, id, err
      */
    }
    return "", STOP, 0, NewTProtocolException(INVALID_DATA, fmt.Sprint("Expected \"}\" or '\"', but found: '", string(b), "'"))
  }
  return "", STOP, 0, NewTProtocolExceptionFromOsError(os.EOF)
}

func (p *TSimpleJSONProtocol) ReadFieldEnd() TProtocolException {
  return nil
  //return p.ParseListEnd()
}

func (p *TSimpleJSONProtocol) ReadMapBegin() (keyType TType, valueType TType, size int, e TProtocolException) {
  if isNull, e := p.ParseListBegin(); isNull || e != nil {
    return VOID, VOID, 0, e
  }

  // read keyType
  bKeyType, e := p.ReadByte()
  keyType = TType(bKeyType)
  if e != nil {
    return keyType, valueType, size, e
  }

  // read valueType
  bValueType, e := p.ReadByte()
  valueType = TType(bValueType)
  if e != nil {
    return keyType, valueType, size, e
  }

  // read size
  iSize, err := p.ReadI64()
  size = int(iSize)
  return keyType, valueType, size, err
}

func (p *TSimpleJSONProtocol) ReadMapEnd() TProtocolException {
  return p.ParseListEnd()
}

func (p *TSimpleJSONProtocol) ReadListBegin() (elemType TType, size int, e TProtocolException) {
  return p.ParseElemListBegin()
}

func (p *TSimpleJSONProtocol) ReadListEnd() TProtocolException {
  return p.ParseListEnd()
}

func (p *TSimpleJSONProtocol) ReadSetBegin() (elemType TType, size int, e TProtocolException) {
  return p.ParseElemListBegin()
}

func (p *TSimpleJSONProtocol) ReadSetEnd() TProtocolException {
  return p.ParseListEnd()
}

func (p *TSimpleJSONProtocol) ReadBool() (bool, TProtocolException) {
  var value bool
  if err := p.ParsePreValue(); err != nil {
    return value, err
  }
  b, _ := p.reader.Peek(len(JSON_FALSE))
  if len(b) > 0 {
    switch b[0] {
    case JSON_TRUE[0]:
      if string(b[0:len(JSON_TRUE)]) == string(JSON_TRUE) {
        p.reader.Read(b[0:len(JSON_TRUE)])
        value = true
      } else {
        return value, NewTProtocolException(INVALID_DATA, "Expected \"true\" but found: "+string(b))
      }
      break
    case JSON_FALSE[0]:
      if string(b[0:len(JSON_FALSE)]) == string(JSON_FALSE) {
        p.reader.Read(b[0:len(JSON_FALSE)])
        value = false
      } else {
        return value, NewTProtocolException(INVALID_DATA, "Expected \"false\" but found: "+string(b))
      }
      break
    case JSON_NULL[0]:
      if string(b[0:len(JSON_NULL)]) == string(JSON_NULL) {
        p.reader.Read(b[0:len(JSON_NULL)])
        value = false
      } else {
        return value, NewTProtocolException(INVALID_DATA, "Expected \"null\" but found: "+string(b))
      }
    default:
      return value, NewTProtocolException(INVALID_DATA, "Expected \"true\", \"false\", or \"null\" but found: "+string(b))
    }
  }
  return value, p.ParsePostValue()
}

func (p *TSimpleJSONProtocol) ReadByte() (byte, TProtocolException) {
  v, err := p.ReadI64()
  return byte(v), err
}

func (p *TSimpleJSONProtocol) ReadI16() (int16, TProtocolException) {
  v, err := p.ReadI64()
  return int16(v), err
}

func (p *TSimpleJSONProtocol) ReadI32() (int32, TProtocolException) {
  v, err := p.ReadI64()
  return int32(v), err
}

func (p *TSimpleJSONProtocol) ReadI64() (int64, TProtocolException) {
  v, _, err := p.ParseI64()
  return v, err
}

func (p *TSimpleJSONProtocol) ReadDouble() (float64, TProtocolException) {
  v, _, err := p.ParseF64()
  return v, err
}

func (p *TSimpleJSONProtocol) ReadString() (string, TProtocolException) {
  var v string
  if err := p.ParsePreValue(); err != nil {
    return v, err
  }
  b, _ := p.reader.Peek(len(JSON_NULL))
  if len(b) > 0 && b[0] == JSON_QUOTE {
    p.reader.ReadByte()
    value, err := p.ParseStringBody()
    v = value
    if err != nil {
      return v, err
    }
  } else if len(b) >= len(JSON_NULL) && string(b[0:len(JSON_NULL)]) == string(JSON_NULL) {
    _, err := p.reader.Read(b[0:len(JSON_NULL)])
    if err != nil {
      return v, NewTProtocolExceptionFromOsError(err)
    }
  } else {
    return v, NewTProtocolException(INVALID_DATA, fmt.Sprint("Expected a JSON string, found ", string(b)))
  }
  return v, p.ParsePostValue()
}

func (p *TSimpleJSONProtocol) ReadBinary() ([]byte, TProtocolException) {
  var v []byte
  if err := p.ParsePreValue(); err != nil {
    return nil, err
  }
  b, _ := p.reader.Peek(len(JSON_NULL))
  if len(b) > 0 && b[0] == JSON_QUOTE {
    p.reader.ReadByte()
    value, err := p.ParseBase64EncodedBody()
    v = value
    if err != nil {
      return v, err
    }
  } else if len(b) >= len(JSON_NULL) && string(b[0:len(JSON_NULL)]) == string(JSON_NULL) {
    _, err := p.reader.Read(b[0:len(JSON_NULL)])
    if err != nil {
      return v, NewTProtocolExceptionFromOsError(err)
    }
  } else {
    return v, NewTProtocolException(INVALID_DATA, fmt.Sprint("Expected a JSON string, found ", string(b)))
  }
  return v, p.ParsePostValue()
}

func (p *TSimpleJSONProtocol) Flush() (err TProtocolException) {
  return NewTProtocolExceptionFromOsError(p.writer.Flush())
}

func (p *TSimpleJSONProtocol) Skip(fieldType TType) (err TProtocolException) {
  return SkipDefaultDepth(p, fieldType)
}

func (p *TSimpleJSONProtocol) Transport() TTransport {
  return p.trans
}

func (p *TSimpleJSONProtocol) OutputPreValue() TProtocolException {
  cxt := _ParseContext(p.dumpContext.Last())
  switch cxt {
  case _CONTEXT_IN_LIST, _CONTEXT_IN_OBJECT_NEXT_KEY:
    if _, e := p.writer.Write(JSON_COMMA); e != nil {
      return NewTProtocolExceptionFromOsError(e)
    }
    break
  case _CONTEXT_IN_OBJECT_NEXT_VALUE:
    if _, e := p.writer.Write(JSON_COLON); e != nil {
      return NewTProtocolExceptionFromOsError(e)
    }
    break
  }
  return nil
}

func (p *TSimpleJSONProtocol) OutputPostValue() TProtocolException {
  cxt := _ParseContext(p.dumpContext.Last())
  switch cxt {
  case _CONTEXT_IN_LIST_FIRST:
    p.dumpContext.Pop()
    p.dumpContext.Push(int(_CONTEXT_IN_LIST))
    break
  case _CONTEXT_IN_OBJECT_FIRST:
    p.dumpContext.Pop()
    p.dumpContext.Push(int(_CONTEXT_IN_OBJECT_NEXT_VALUE))
    break
  case _CONTEXT_IN_OBJECT_NEXT_KEY:
    p.dumpContext.Pop()
    p.dumpContext.Push(int(_CONTEXT_IN_OBJECT_NEXT_VALUE))
    break
  case _CONTEXT_IN_OBJECT_NEXT_VALUE:
    p.dumpContext.Pop()
    p.dumpContext.Push(int(_CONTEXT_IN_OBJECT_NEXT_KEY))
    break
  }
  return nil
}

func (p *TSimpleJSONProtocol) OutputBool(value bool) TProtocolException {
  if e := p.OutputPreValue(); e != nil {
    return e
  }
  var v string
  if value {
    v = string(JSON_TRUE)
  } else {
    v = string(JSON_FALSE)
  }
  switch _ParseContext(p.dumpContext.Last()) {
  case _CONTEXT_IN_OBJECT_FIRST, _CONTEXT_IN_OBJECT_NEXT_KEY:
    v = JsonQuote(v)
  default:
  }
  if e := p.OutputStringData(v); e != nil {
    return e
  }
  return p.OutputPostValue()
}

func (p *TSimpleJSONProtocol) OutputNull() TProtocolException {
  if e := p.OutputPreValue(); e != nil {
    return e
  }
  if _, e := p.writer.Write(JSON_NULL); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  return p.OutputPostValue()
}

func (p *TSimpleJSONProtocol) OutputF64(value float64) TProtocolException {
  if e := p.OutputPreValue(); e != nil {
    return e
  }
  var v string
  if math.IsNaN(value) {
    v = string(JSON_QUOTE) + JSON_NAN + string(JSON_QUOTE)
  } else if math.IsInf(value, 1) {
    v = string(JSON_QUOTE) + JSON_INFINITY + string(JSON_QUOTE)
  } else if math.IsInf(value, -1) {
    v = string(JSON_QUOTE) + JSON_NEGATIVE_INFINITY + string(JSON_QUOTE)
  } else {
    v = strconv.Ftoa64(value, 'g', -1)
    switch _ParseContext(p.dumpContext.Last()) {
    case _CONTEXT_IN_OBJECT_FIRST, _CONTEXT_IN_OBJECT_NEXT_KEY:
      v = string(JSON_QUOTE) + v + string(JSON_QUOTE)
    default:
    }
  }
  if e := p.OutputStringData(v); e != nil {
    return e
  }
  return p.OutputPostValue()
}

func (p *TSimpleJSONProtocol) OutputI64(value int64) TProtocolException {
  if e := p.OutputPreValue(); e != nil {
    return e
  }
  v := strconv.Itoa64(value)
  switch _ParseContext(p.dumpContext.Last()) {
  case _CONTEXT_IN_OBJECT_FIRST, _CONTEXT_IN_OBJECT_NEXT_KEY:
    v = JsonQuote(v)
  default:
  }
  if e := p.OutputStringData(v); e != nil {
    return e
  }
  return p.OutputPostValue()
}

func (p *TSimpleJSONProtocol) OutputString(s string) TProtocolException {
  if e := p.OutputPreValue(); e != nil {
    return e
  }
  if e := p.OutputStringData(JsonQuote(s)); e != nil {
    return e
  }
  return p.OutputPostValue()
}

func (p *TSimpleJSONProtocol) OutputStringData(s string) TProtocolException {
  _, e := io.Copyn(p.writer, strings.NewReader(s), int64(len(s)))
  return NewTProtocolExceptionFromOsError(e)
}

func (p *TSimpleJSONProtocol) OutputObjectBegin() TProtocolException {
  if e := p.OutputPreValue(); e != nil {
    return e
  }
  if _, e := p.writer.Write(JSON_LBRACE); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  p.dumpContext.Push(int(_CONTEXT_IN_OBJECT_FIRST))
  return nil
}

func (p *TSimpleJSONProtocol) OutputObjectEnd() TProtocolException {
  if _, e := p.writer.Write(JSON_RBRACE); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  p.dumpContext.Pop()
  if e := p.OutputPostValue(); e != nil {
    return e
  }
  return nil
}

func (p *TSimpleJSONProtocol) OutputListBegin() TProtocolException {
  if e := p.OutputPreValue(); e != nil {
    return e
  }
  if _, e := p.writer.Write(JSON_LBRACKET); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  p.dumpContext.Push(int(_CONTEXT_IN_LIST_FIRST))
  return nil
}

func (p *TSimpleJSONProtocol) OutputListEnd() TProtocolException {
  if _, e := p.writer.Write(JSON_RBRACKET); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  p.dumpContext.Pop()
  if e := p.OutputPostValue(); e != nil {
    return e
  }
  return nil
}

func (p *TSimpleJSONProtocol) OutputElemListBegin(elemType TType, size int) TProtocolException {
  if e := p.OutputListBegin(); e != nil {
    return e
  }
  if e := p.WriteByte(byte(elemType)); e != nil {
    return e
  }
  if e := p.WriteI64(int64(size)); e != nil {
    return e
  }
  return nil
}

func (p *TSimpleJSONProtocol) ParsePreValue() TProtocolException {
  if e := p.readNonSignificantWhitespace(); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  cxt := _ParseContext(p.parseContextStack.Last())
  if p.reader.Buffered() < 1 {
    return nil
  }
  b, _ := p.reader.Peek(1)
  switch cxt {
  case _CONTEXT_IN_LIST:
    if len(b) > 0 {
      switch b[0] {
      case JSON_RBRACKET[0]:
        return nil
      case JSON_COMMA[0]:
        p.reader.ReadByte()
        if e := p.readNonSignificantWhitespace(); e != nil {
          return NewTProtocolExceptionFromOsError(e)
        }
        return nil
      default:
        return NewTProtocolException(INVALID_DATA, fmt.Sprint("Expected \"]\" or \",\" in list context, but found \"", string(b), "\""))
      }
    }
    break
  case _CONTEXT_IN_OBJECT_NEXT_KEY:
    if len(b) > 0 {
      switch b[0] {
      case JSON_RBRACE[0]:
        return nil
      case JSON_COMMA[0]:
        p.reader.ReadByte()
        if e := p.readNonSignificantWhitespace(); e != nil {
          return NewTProtocolExceptionFromOsError(e)
        }
        return nil
      default:
        return NewTProtocolException(INVALID_DATA, fmt.Sprint("Expected \"}\" or \",\" in object context, but found \"", string(b), "\""))
      }
    }
    break
  case _CONTEXT_IN_OBJECT_NEXT_VALUE:
    if len(b) > 0 {
      switch b[0] {
      case JSON_COLON[0]:
        p.reader.ReadByte()
        if e := p.readNonSignificantWhitespace(); e != nil {
          return NewTProtocolExceptionFromOsError(e)
        }
        return nil
      default:
        return NewTProtocolException(INVALID_DATA, fmt.Sprint("Expected \":\" in object context, but found \"", string(b), "\""))
      }
    }
    break
  }
  return nil
}

func (p *TSimpleJSONProtocol) ParsePostValue() TProtocolException {
  if e := p.readNonSignificantWhitespace(); e != nil {
    return NewTProtocolExceptionFromOsError(e)
  }
  cxt := _ParseContext(p.parseContextStack.Last())
  switch cxt {
  case _CONTEXT_IN_LIST_FIRST:
    p.parseContextStack.Pop()
    p.parseContextStack.Push(int(_CONTEXT_IN_LIST))
    break
  case _CONTEXT_IN_OBJECT_FIRST, _CONTEXT_IN_OBJECT_NEXT_KEY:
    p.parseContextStack.Pop()
    p.parseContextStack.Push(int(_CONTEXT_IN_OBJECT_NEXT_VALUE))
    break
  case _CONTEXT_IN_OBJECT_NEXT_VALUE:
    p.parseContextStack.Pop()
    p.parseContextStack.Push(int(_CONTEXT_IN_OBJECT_NEXT_KEY))
    break
  }
  return nil
}

func (p *TSimpleJSONProtocol) readNonSignificantWhitespace() os.Error {
  for p.reader.Buffered() > 0 {
    b, _ := p.reader.Peek(1)
    if len(b) < 1 {
      return nil
    }
    switch b[0] {
    case ' ', '\r', '\n', '\t':
      p.reader.ReadByte()
      continue
    default:
      break
    }
    break
  }
  return nil
}

func (p *TSimpleJSONProtocol) ParseStringBody() (string, TProtocolException) {
  line, err := p.reader.ReadString(JSON_QUOTE)
  if err != nil {
    return "", NewTProtocolExceptionFromOsError(err)
  }
  l := len(line)
  // count number of escapes to see if we need to keep going
  i := 1
  for ; i < l; i++ {
    if line[l-i-1] != '\\' {
      break
    }
  }
  if i&0x01 == 1 {
    v, ok := JsonUnquote(string(JSON_QUOTE) + line)
    if !ok {
      return "", NewTProtocolExceptionFromOsError(err)
    }
    return v, nil
  }
  s, err := p.ParseQuotedStringBody()
  if err != nil {
    return "", NewTProtocolExceptionFromOsError(err)
  }
  str := string(JSON_QUOTE) + line + s
  v, ok := JsonUnquote(str)
  if !ok {
    return "", NewTProtocolException(INVALID_DATA, "Unable to parse as JSON string "+str)
  }
  return v, nil
}

func (p *TSimpleJSONProtocol) ParseQuotedStringBody() (string, TProtocolException) {
  line, err := p.reader.ReadString(JSON_QUOTE)
  if err != nil {
    return "", NewTProtocolExceptionFromOsError(err)
  }
  l := len(line)
  // count number of escapes to see if we need to keep going
  i := 1
  for ; i < l; i++ {
    if line[l-i-1] != '\\' {
      break
    }
  }
  if i&0x01 == 1 {
    return line, nil
  }
  s, err := p.ParseQuotedStringBody()
  if err != nil {
    return "", NewTProtocolExceptionFromOsError(err)
  }
  v := line + s
  return v, nil
}

func (p *TSimpleJSONProtocol) ParseBase64EncodedBody() ([]byte, TProtocolException) {
  line, err := p.reader.ReadBytes(JSON_QUOTE)
  if err != nil {
    return line, NewTProtocolExceptionFromOsError(err)
  }
  line2 := line[0 : len(line)-1]
  l := len(line2)
  output := make([]byte, base64.StdEncoding.DecodedLen(l))
  n, err := base64.StdEncoding.Decode(output, line2)
  return output[0:n], NewTProtocolExceptionFromOsError(err)
}

func (p *TSimpleJSONProtocol) ParseI64() (int64, bool, TProtocolException) {
  if err := p.ParsePreValue(); err != nil {
    return 0, false, err
  }
  var value int64
  var isnull bool
  b, _ := p.reader.Peek(len(JSON_NULL))
  if len(b) >= len(JSON_NULL) && string(b) == string(JSON_NULL) {
    p.reader.Read(b[0:len(JSON_NULL)])
    isnull = true
  } else {
    num, err := p.readNumeric()
    isnull = (num == nil)
    if !isnull {
      value = num.Int64()
    }
    if err != nil {
      return value, isnull, err
    }
  }
  return value, isnull, p.ParsePostValue()
}

func (p *TSimpleJSONProtocol) ParseF64() (float64, bool, TProtocolException) {
  if err := p.ParsePreValue(); err != nil {
    return 0, false, err
  }
  var value float64
  var isnull bool
  b, _ := p.reader.Peek(len(JSON_NULL))
  if len(b) >= len(JSON_NULL) && string(b) == string(JSON_NULL) {
    p.reader.Read(b[0:len(JSON_NULL)])
    isnull = true
  } else {
    num, err := p.readNumeric()
    isnull = (num == nil)
    if !isnull {
      value = num.Float64()
    }
    if err != nil {
      return value, isnull, err
    }
  }
  return value, isnull, p.ParsePostValue()
}

func (p *TSimpleJSONProtocol) ParseObjectStart() (bool, TProtocolException) {
  if err := p.ParsePreValue(); err != nil {
    return false, err
  }
  b, _ := p.reader.Peek(len(JSON_NULL))
  if len(b) > 0 && b[0] == JSON_LBRACE[0] {
    p.reader.ReadByte()
    p.parseContextStack.Push(int(_CONTEXT_IN_OBJECT_FIRST))
    return false, nil
  } else if len(b) >= len(JSON_NULL) && string(b[0:len(JSON_NULL)]) == string(JSON_NULL) {
    return true, nil
  }
  return false, NewTProtocolException(INVALID_DATA, fmt.Sprint("Expected '{' or null, but found '", string(b), "'"))
}

func (p *TSimpleJSONProtocol) ParseObjectEnd() TProtocolException {
  if isNull, err := p.readIfNull(); isNull || err != nil {
    return err
  }
  cxt := _ParseContext(p.parseContextStack.Last())
  if cxt != _CONTEXT_IN_OBJECT_FIRST && cxt != _CONTEXT_IN_OBJECT_NEXT_KEY {
    return NewTProtocolException(INVALID_DATA, fmt.Sprint("Expected to be in the Object Context, but not in Object Context"))
  }
  line, err := p.reader.ReadString(JSON_RBRACE[0])
  if err != nil {
    return NewTProtocolExceptionFromOsError(err)
  }
  for _, char := range line {
    switch char {
    default:
      return NewTProtocolException(INVALID_DATA, fmt.Sprint("Expecting end of object \"}\", but found: \"", line, "\""))
    case ' ', '\n', '\r', '\t', '}':
      break
    }
  }
  p.parseContextStack.Pop()
  return p.ParsePostValue()
}

func (p *TSimpleJSONProtocol) ParseListBegin() (bool, TProtocolException) {
  if e := p.ParsePreValue(); e != nil {
    return false, e
  }
  b, e := p.reader.Peek(len(JSON_NULL))
  if e == nil && len(b) >= 1 && b[0] == JSON_LBRACKET[0] {
    p.parseContextStack.Push(int(_CONTEXT_IN_LIST_FIRST))
    p.reader.ReadByte()
    return false, nil
  } else if e == nil && len(b) >= len(JSON_NULL) && string(b) == string(JSON_NULL) {
    return true, nil
  }
  return false, NewTProtocolException(INVALID_DATA, fmt.Sprintf("Expected 'null' or '{', received '%q'", b))
}

func (p *TSimpleJSONProtocol) ParseElemListBegin() (elemType TType, size int, e TProtocolException) {
  if isNull, e := p.ParseListBegin(); isNull || e != nil {
    return VOID, 0, e
  }
  bElemType, err := p.ReadByte()
  elemType = TType(bElemType)
  if err != nil {
    return elemType, size, err
  }
  nSize, err2 := p.ReadI64()
  size = int(nSize)
  return elemType, size, err2
}

func (p *TSimpleJSONProtocol) ParseListEnd() TProtocolException {
  if isNull, err := p.readIfNull(); isNull || err != nil {
    return err
  }
  if _ParseContext(p.parseContextStack.Last()) != _CONTEXT_IN_LIST {
    return NewTProtocolException(INVALID_DATA, "Expected to be in the List Context, but not in List Context")
  }
  line, err := p.reader.ReadString(JSON_RBRACKET[0])
  if err != nil {
    return NewTProtocolExceptionFromOsError(err)
  }
  for _, char := range line {
    switch char {
    default:
      return NewTProtocolException(INVALID_DATA, fmt.Sprint("Expecting end of list \"]\", but found: \"", line, "\""))
    case ' ', '\n', '\r', '\t', int(JSON_RBRACKET[0]):
      break
    }
  }
  p.parseContextStack.Pop()
  return p.ParsePostValue()
}

func (p *TSimpleJSONProtocol) readSingleValue() (interface{}, TType, TProtocolException) {
  e := p.readNonSignificantWhitespace()
  if e != nil {
    return nil, VOID, NewTProtocolExceptionFromOsError(e)
  }
  b, e := p.reader.Peek(10)
  if len(b) > 0 {
    c := b[0]
    switch c {
    case JSON_NULL[0]:
      buf := make([]byte, len(JSON_NULL))
      _, e := p.reader.Read(buf)
      if e != nil {
        return nil, VOID, NewTProtocolExceptionFromOsError(e)
      }
      if string(JSON_NULL) != string(buf) {
        e := NewTProtocolException(INVALID_DATA, "Expected '"+string(JSON_NULL)+"' but found '"+string(buf)+"' while parsing JSON.")
        return nil, VOID, e
      }
      return nil, VOID, nil
    case JSON_QUOTE:
      p.reader.ReadByte()
      v, e := p.ParseStringBody()
      if e != nil {
        return v, UTF8, NewTProtocolExceptionFromOsError(e)
      }
      if v == JSON_INFINITY {
        return INFINITY, DOUBLE, nil
      } else if v == JSON_NEGATIVE_INFINITY {
        return NEGATIVE_INFINITY, DOUBLE, nil
      } else if v == JSON_NAN {
        return NAN, DOUBLE, nil
      }
      return v, UTF8, nil
    case JSON_TRUE[0]:
      buf := make([]byte, len(JSON_TRUE))
      _, e := p.reader.Read(buf)
      if e != nil {
        return true, BOOL, NewTProtocolExceptionFromOsError(e)
      }
      if string(JSON_TRUE) != string(buf) {
        e := NewTProtocolException(INVALID_DATA, "Expected '"+string(JSON_TRUE)+"' but found '"+string(buf)+"' while parsing JSON.")
        return true, BOOL, NewTProtocolExceptionFromOsError(e)
      }
      return true, BOOL, nil
    case JSON_FALSE[0]:
      buf := make([]byte, len(JSON_FALSE))
      _, e := p.reader.Read(buf)
      if e != nil {
        return false, BOOL, NewTProtocolExceptionFromOsError(e)
      }
      if string(JSON_FALSE) != string(buf) {
        e := NewTProtocolException(INVALID_DATA, "Expected '"+string(JSON_FALSE)+"' but found '"+string(buf)+"' while parsing JSON.")
        return false, BOOL, NewTProtocolExceptionFromOsError(e)
      }
      return false, BOOL, nil
    case JSON_LBRACKET[0]:
      _, e := p.reader.ReadByte()
      return make([]interface{}, 0), LIST, NewTProtocolExceptionFromOsError(e)
    case JSON_LBRACE[0]:
      _, e := p.reader.ReadByte()
      return make(map[string]interface{}), STRUCT, NewTProtocolExceptionFromOsError(e)
    case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-', JSON_INFINITY[0], JSON_NAN[0]:
      // assume numeric
      v, e := p.readNumeric()
      return v, DOUBLE, e
    default:
      return nil, VOID, NewTProtocolException(INVALID_DATA, "Expected element in list but found '"+string(c)+"' while parsing JSON.")
    }
  }
  return nil, VOID, NewTProtocolException(INVALID_DATA, "Cannot read a single element while parsing JSON.")

}

func (p *TSimpleJSONProtocol) readIfNull() (bool, TProtocolException) {
  cont := true
  for p.reader.Buffered() > 0 && cont {
    b, _ := p.reader.Peek(1)
    if len(b) < 1 {
      return false, nil
    }
    switch b[0] {
    default:
      return false, nil
    case JSON_NULL[0]:
      cont = false
      break
    case ' ', '\n', '\r', '\t':
      p.reader.ReadByte()
      break
    }
  }
  if p.reader.Buffered() == 0 {
    return false, nil
  }
  b, _ := p.reader.Peek(len(JSON_NULL))
  if string(b) == string(JSON_NULL) {
    p.reader.Read(b[0:len(JSON_NULL)])
    return true, nil
  }
  return false, nil
}

func (p *TSimpleJSONProtocol) readQuoteIfNext() {
  if p.reader.Buffered() < 1 {
    return
  }
  b, _ := p.reader.Peek(1)
  if len(b) > 0 && b[0] == JSON_QUOTE {
    p.reader.ReadByte()
  }
}

func (p *TSimpleJSONProtocol) readNumeric() (Numeric, TProtocolException) {
  isNull, err := p.readIfNull()
  if isNull || err != nil {
    return NUMERIC_NULL, err
  }
  hasDecimalPoint := false
  nextCanBeSign := true
  hasE := false
  MAX_LEN := 40
  buf := bytes.NewBuffer(make([]byte, 0, MAX_LEN))
  continueFor := true
  inQuotes := false
  for continueFor {
    c, err := p.reader.ReadByte()
    if err != nil {
      if err == os.EOF {
        break
      }
      return NUMERIC_NULL, NewTProtocolExceptionFromOsError(err)
    }
    switch c {
    case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
      buf.WriteByte(c)
      nextCanBeSign = false
    case '.':
      if hasDecimalPoint {
        return NUMERIC_NULL, NewTProtocolException(INVALID_DATA, fmt.Sprintf("Unable to parse number with multiple decimal points '%s.'", buf.String()))
      }
      if hasE {
        return NUMERIC_NULL, NewTProtocolException(INVALID_DATA, fmt.Sprintf("Unable to parse number with decimal points in the exponent '%s.'", buf.String()))
      }
      buf.WriteByte(c)
      hasDecimalPoint, nextCanBeSign = true, false
    case 'e', 'E':
      if hasE {
        return NUMERIC_NULL, NewTProtocolException(INVALID_DATA, fmt.Sprintf("Unable to parse number with multiple exponents '%s%c'", buf.String(), c))
      }
      buf.WriteByte(c)
      hasE, nextCanBeSign = true, true
    case '-', '+':
      if !nextCanBeSign {
        return NUMERIC_NULL, NewTProtocolException(INVALID_DATA, fmt.Sprint("Negative sign within number"))
      }
      buf.WriteByte(c)
      nextCanBeSign = false
    case ' ', 0, '\t', '\n', '\r', JSON_RBRACE[0], JSON_RBRACKET[0], JSON_COMMA[0], JSON_COLON[0]:
      p.reader.UnreadByte()
      continueFor = false
    case JSON_NAN[0]:
      if buf.Len() == 0 {
        buffer := make([]byte, len(JSON_NAN))
        buffer[0] = c
        _, e := p.reader.Read(buffer[1:])
        if e != nil {
          return NUMERIC_NULL, NewTProtocolExceptionFromOsError(e)
        }
        if JSON_NAN != string(buffer) {
          e := NewTProtocolException(INVALID_DATA, "Expected '"+JSON_NAN+"' but found '"+string(buffer)+"' while parsing JSON.")
          return NUMERIC_NULL, e
        }
        if inQuotes {
          p.readQuoteIfNext()
        }
        return NAN, nil
      } else {
        return NUMERIC_NULL, NewTProtocolException(INVALID_DATA, fmt.Sprintf("Unable to parse number starting with character '%c'", c))
      }
    case JSON_INFINITY[0]:
      if buf.Len() == 0 || (buf.Len() == 1 && buf.Bytes()[0] == '+') {
        buffer := make([]byte, len(JSON_INFINITY))
        buffer[0] = c
        _, e := p.reader.Read(buffer[1:])
        if e != nil {
          return NUMERIC_NULL, NewTProtocolExceptionFromOsError(e)
        }
        if JSON_INFINITY != string(buffer) {
          e := NewTProtocolException(INVALID_DATA, "Expected '"+JSON_INFINITY+"' but found '"+string(buffer)+"' while parsing JSON.")
          return NUMERIC_NULL, e
        }
        if inQuotes {
          p.readQuoteIfNext()
        }
        return INFINITY, nil
      } else if buf.Len() == 1 && buf.Bytes()[0] == JSON_NEGATIVE_INFINITY[0] {
        buffer := make([]byte, len(JSON_NEGATIVE_INFINITY))
        buffer[0] = JSON_NEGATIVE_INFINITY[0]
        buffer[1] = c
        _, e := p.reader.Read(buffer[2:])
        if e != nil {
          return NUMERIC_NULL, NewTProtocolExceptionFromOsError(e)
        }
        if JSON_NEGATIVE_INFINITY != string(buffer) {
          e := NewTProtocolException(INVALID_DATA, "Expected '"+JSON_NEGATIVE_INFINITY+"' but found '"+string(buffer)+"' while parsing JSON.")
          return NUMERIC_NULL, e
        }
        if inQuotes {
          p.readQuoteIfNext()
        }
        return NEGATIVE_INFINITY, nil
      } else {
        return NUMERIC_NULL, NewTProtocolException(INVALID_DATA, fmt.Sprintf("Unable to parse number starting with character '%c' due to existing buffer %s", c, buf.String()))
      }
    case JSON_QUOTE:
      if !inQuotes {
        inQuotes = true
      } else {
        break
      }
    default:
      return NUMERIC_NULL, NewTProtocolException(INVALID_DATA, fmt.Sprintf("Unable to parse number starting with character '%c'", c))
    }
  }
  if buf.Len() == 0 {
    return NUMERIC_NULL, NewTProtocolException(INVALID_DATA, fmt.Sprint("Unable to parse number from empty string ''"))
  }
  return NewNumericFromJSONString(buf.String(), false), nil
}


text:
<!doctype html>

    <title>Code coverage report for app/Containers/App/state.js</title>
    <meta charset="utf-8" />
    <link rel="stylesheet" href="../../../prettify.css" />
    <link rel="stylesheet" href="../../../base.css" />
    <meta name="viewport" content="width=device-width, initial-scale=1">

      All files / app/Containers/App state.js

        0%
        Statements
        0/5

        100%
        Branches
        0/0

        100%
        Functions
        0/0

        0%
        Lines
        0/4

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

import {config} from '../../config'
const {title} = config()

const state = {
  title: title,
  communityId: '',
  uploadToken: '',
  pathnameChange: true,
  pathnameCurrent: '',
  permissions: [],
  permissionsCurrent: 5,
  selectChannels: [],
  selectColumns: [],
  selectLabels: [],
  selectedChannel: undefined,
  selectedColumn: undefined,
  selectedLabels: undefined,
}

export default state

  Code coverage
  generated by istanbul at Mon Sep 18 2017 17:44:25 GMT+0800 (CST)

redpajama_set_name: RedPajamaGithub


text:
package de.northernstars.dummy;

import java.math.BigInteger;
import java.util.LinkedList;
import java.util.NoSuchElementException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import de.hanneseilers.jftdiserial.core.Baudrates;
import de.hanneseilers.jftdiserial.core.DataBits;
import de.hanneseilers.jftdiserial.core.FTDISerial;
import de.hanneseilers.jftdiserial.core.Parity;
import de.hanneseilers.jftdiserial.core.SerialDevice;
import de.hanneseilers.jftdiserial.core.StopBits;
import de.hanneseilers.jftdiserial.core.interfaces.SerialDataRecievedListener;

public class Dummy implements SerialDataRecievedListener {

	private static final byte DUMMY_REQUEST = (byte) 0xb7;
	private static final byte PROTOCOL_START = (byte) 0xb8;

	public static final int TIMEOUT = 5000;
	public static final int TIMEOUT_MAX_MULTIPLIER = 3;
	private static final int CONNECT_MAX_TRIES = 3;
	private static final long CONNECT_TRIES_DELAY = 500;

	private FTDISerial serial;
	private LinkedList<Byte> dataBuffer = new LinkedList<Byte>();
	private Logger log = LogManager.getLogger();
	private boolean connected = false;

	/**
	 * Default Constructor
	 */
	public Dummy() {
		serial = new FTDISerial(Baudrates.BAUD_115200, DataBits.DATABITS_8, StopBits.STOPBIT_1, Parity.NONE, TIMEOUT);
		serial.addSerialDataRecievedListener(this);
	}

	/**
	 * Automatic connect
	 * @return {@code true} if successful, {@code false} otherwise.
	 */
	public boolean autoConnect(){
		return autoSelectDriver() && autoSelectDevice();
	}

	/**
	 * Disconnects from Dummy
	 * @return	{@code true} if connected to Dummy, {@code false} otherwise.
	 */
	public boolean disconnect(){
		serial.removeAllSerialDataRecievedListener();
		connected = false;
		return serial.disconnect();
	}

	/**
	 * @return {@code true} if connected to Dummy, {@code false} otherwise.
	 */
	public boolean isConnected(){
		return serial.isConnected() && connected;
	}

	/**
	 * Auto connecting to library.
	 * @return	{@code true} if successful, {@code false} otherwise.
	 */
	private boolean autoSelectDriver(){
		for( String libName : serial.getAvailableLibNames() ){
			if( libName.toLowerCase().contains("rxtx") ){
				log.debug("Selected lib: {}", libName);
				serial.selectLibByName(libName);
				return true;
			}
		}

		log.error("Could not load rxtx library.");
		return false;
	}

	/**
	 * Auto selecting device.
	 * @return	{@code true} if successfully, {@code false} otherwise.
	 */
	private boolean autoSelectDevice(){
		for( SerialDevice device : serial.getAvailableDevices() ){

			log.info("Connecting to {} ...", device);

			if( serial.connect(device) ){

				int vTries = 0;

				// try to connect
				while( vTries < CONNECT_MAX_TRIES  ){
					serial.write(DUMMY_REQUEST);

					try{
						if( read() == DUMMY_REQUEST){
							log.info("Connected!");
							connected = true;
							return true;
						}
					} catch(NoSuchElementException err){
						log.warn("Connection request to {} timed out.", device);

						try {
							Thread.sleep(CONNECT_TRIES_DELAY);
						} catch (InterruptedException e) {}
					}
				}

				log.error("Could not connect to {}", device);
			}
		}

		return false;
	}

	/**
	 * Tries to read a data byte from buffer or throws Execption if timed out.
	 * @return		First data {@link Byte} from buffer
	 * @throws NoSuchElementException
	 */
	private byte read() throws NoSuchElementException{
		return read(false);
	}

	/**
	 * Tries to read a data byte from buffer or throws Execption if timed out.
	 * @param longTimeout	{@link Boolean} to switch between normal timeout {@code false}
	 * 				or multiple timeout {@code true} time.
	 * @return		First data {@link Byte} from buffer
	 * @throws NoSuchElementException
	 */
	private synchronized byte read(boolean longTimeout) throws NoSuchElementException{
		long t1 = System.currentTimeMillis();

		while( System.currentTimeMillis()-t1 < TIMEOUT
				|| (longTimeout && System.currentTimeMillis()-t1 < TIMEOUT*TIMEOUT_MAX_MULTIPLIER) ){
			synchronized (dataBuffer) {
				try{
					return dataBuffer.pop();
				} catch( NoSuchElementException err ){}
			}
		}

		throw new NoSuchElementException("Timed out");
	}

	@Override
	public void serialDataRecieved(byte data) {
		synchronized (dataBuffer) {
			dataBuffer.add(data);
		}
	}

	/**
	 * Write data to servo
	 * @param aServo	{@link Servos} to write data to.
	 * @param aValue	{@link Byte} value to write to servo.
	 * @return			{@code true} if successful, {@code false} otherwise.
	 */
	public boolean setServoPosition(Servos aServo, byte aValue){
		if( isConnected() ){
			try{
				serial.write( PROTOCOL_START );
				serial.write( aServo.dataByte );
				serial.write( aValue );
				if( read() == aServo.dataByte  ){
					return true;
				}
			} catch (NoSuchElementException e){}
		}

		return false;
	}

	/**
	 * Open Dummys hand
	 * @return	{@code true} if successful, {@code false} otherwise.
	 */
	public boolean openHand(){
		if( isConnected() ){
			try{
				serial.write( PROTOCOL_START );
				serial.write( Commands.OPEN_HAND.dataByte );
				return read() == Commands.OPEN_HAND.dataByte;
			} catch (NoSuchElementException e){}
		}
		return false;
	}

	/**
	 * Close Dummys hand
	 * @return	{@code true} if successful, {@code false} otherwise.
	 */
	public boolean closeHand(){
		if( isConnected() ){
			try{
				serial.write( PROTOCOL_START );
				serial.write( Commands.CLOSE_HAND.dataByte );
				return read() == Commands.CLOSE_HAND.dataByte;
			} catch (NoSuchElementException e){}
		}
		return false;
	}

	/**
	 * Sets Dummy into a predefined position
	 * @param aPosition	{@link Positions} to set Dummy into
	 * @return			{@code true} if successful, {@code false} otherwise.
	 */
	public boolean setDummyPosition(Positions aPosition){
		if( isConnected() ){
			try{
				serial.write( PROTOCOL_START );
				serial.write( aPosition.dataByte );
				return read() == aPosition.dataByte;
			} catch (NoSuchElementException e){}
		}
		return false;
	}

	/**
	 * Sets servo speed low {@link Byte}
	 * @param aValue	{@link BigInteger} speed value
	 * @return			{@code true} if successful, {@code false} otherwise.
	 */
	public boolean setServoSpeed(BigInteger aValue){
		if( isConnected() ){
			try{
				serial.write( PROTOCOL_START );
				serial.write( Commands.SET_SERVO_SPEED.dataByte );
				serial.write( aValue.shiftRight(24).byteValue() );
				serial.write( aValue.shiftRight(16).byteValue() );
				serial.write( aValue.shiftRight(8).byteValue() );
				serial.write( aValue.byteValue() );
				if( read() == Commands.SET_SERVO_SPEED.dataByte ){
					return true;
				}
			} catch (NoSuchElementException e){}

		}
		return false;
	}

	/**
	 * Gets servo speed
	 * @return	Lowest {@link Byte} of servo speed
	 */
	public BigInteger getServoSpeed(){
		if( isConnected()){
			try{
				serial.write( PROTOCOL_START );
				serial.write( Commands.GET_SERVO_SPEED.dataByte );
				byte b0 = read();
				byte b1 = read();
				byte b2 = read();
				byte b3 = read();
				BigInteger b = new BigInteger(
						new byte[]{b3, b2, b1, b0});

				if( read() == Commands.GET_SERVO_SPEED.dataByte ){
					return b;
				}
			} catch (NoSuchElementException e){}

		}
		return new BigInteger("0");
	}

}


text: Rails.application.config.session_store :cookie_store, key: '_pi_base_session'


text:
from django.db import models
import reddit_analysis as ra

class User(models.Model):
    username = models.CharField(max_length=50)
    count = models.IntegerField()


text:
<?php

/**
 * @category   Payment Gateway
 * @package    Adyen_Payment
 * @author     Adyen
 * @property   Adyen B.V
 * @copyright  Copyright (c) 2014 Adyen BV (http://www.adyen.com)
 */
class Adyen_Payment_Model_Resource_Adyen_Event_Collection
    extends Mage_Core_Model_Resource_Db_Collection_Abstract
{
    protected function _construct()
    {
        $this->_init('adyen/adyen_event');
        $this->setItemObjectClass('adyen/event');
    }
}


text:
using System;
using MementoExample.AOP;

namespace MementoExample {
    internal class Program {
        private static void Main(string[] args) {
            var superHero = new SuperHero();
            var memento = ((IMemento) superHero);

            superHero.Age = 12;
            superHero.Name = "Bruce Wayne";
            Console.WriteLine(superHero);
            memento.Save();

            superHero.Age = 34;
            superHero.Name = "Batman";
            Console.WriteLine(superHero);
            memento.Save();

            superHero.Age = 41;
            superHero.Name = "Dark Knight";
            Console.WriteLine(superHero);

            memento.Undo();
            Console.WriteLine("Undo " + superHero);
            memento.Undo();
            Console.WriteLine("Undo " + superHero);
            memento.Undo();
            Console.WriteLine("Undo " + superHero);
            memento.Undo();
            Console.WriteLine("Undo " + superHero);
            memento.Undo();
            Console.WriteLine("Undo " + superHero);

            Console.ReadLine();

        }
    }
}


text:
package org.heaven7.scrap.databinding.expression.base;

import org.heaven7.scrap.databinding.expression.IExpressionVisitor;

/**
 * Created by heaven7 on 2015/8/12.
 */
public class BooleanExpr extends BaseExpr {

    private boolean value;

    @Override
    public <R, A> R accept(IExpressionVisitor<R, A> visitor, A arg) {
        return visitor.visit(this,arg);
    }

    public boolean isTrue() {
        return value;
    }
    public void setValue(boolean value) {
        this.value = value;
    }
}


text:
drop table if exists users;
drop table if exists line_items;
drop table if exists orders;
drop table if exists products;

create table products (
 id              int           not null auto_increment,
 title           varchar(100)  not null,
 description     text          not null,
 image_url       varchar(200)  not null,
 price           decimal(10,2) not null,
 date_available  datetime      not null,
 primary key (id)
);

/*START:orders*/
create table orders (
 id              int           not null auto_increment,
 name            varchar(100)  not null,
 email           varchar(255)  not null,
 address         text          not null,
 pay_type        char(10)      not null,
 shipped_at	 datetime      null,
 primary key (id)
);
/*END:orders*/

create table line_items (
  id              int           not null auto_increment,
  product_id	  int 	        not null,
  order_id        int           not null,
  quantity	  int           not null default 0,
  unit_price	  decimal(10,2) not null,
  constraint fk_items_product   foreign key (product_id) references products(id),
  constraint fk_items_order     foreign key (order_id) references orders(id),
  primary key (id)
);

create table users (
  id              int           not null auto_increment,
  name		  varchar(100)  not null,
  hashed_password char(40)      null,
  primary key (id)
);

insert into users values(null, 'dave', 'e5e9fa1ba31ecd1ae84f75caaa474f3a663f05f4');


text:
namespace {
const char* kTestingUsername = "fake_username";
}  // namespace

class OneClickSigninSyncStarterTest : public testing::Test {
 public:
  OneClickSigninSyncStarterTest()
      : sync_starter_(NULL),
        failed_count_(0),
        succeeded_count_(0) {}

  // testing::Test:
  virtual void SetUp() OVERRIDE {
    testing::Test::SetUp();

    // Create the sign in manager required by OneClickSigninSyncStarter.
    TestingProfile::Builder builder;
    builder.AddTestingFactory(
        SigninManagerFactory::GetInstance(),
        &OneClickSigninSyncStarterTest::BuildSigninManager);
    profile_ = builder.Build();

    SigninManagerBase* signin_manager = static_cast<FakeSigninManager*>(
        SigninManagerFactory::GetForProfile(profile_.get()));

    // Disable sync to simplify the creation of a OneClickSigninSyncStarter.
    CommandLine::ForCurrentProcess()->AppendSwitch(switches::kDisableSync);

    signin_manager->Initialize(profile_.get(), NULL);
    signin_manager->SetAuthenticatedUsername(kTestingUsername);
  }

  void Callback(OneClickSigninSyncStarter::SyncSetupResult result) {
    if (result == OneClickSigninSyncStarter::SYNC_SETUP_SUCCESS)
      ++succeeded_count_;
    else
      ++failed_count_;
  }

 protected:
  void CreateSyncStarter(OneClickSigninSyncStarter::Callback callback) {
    sync_starter_ = new OneClickSigninSyncStarter(
        profile_.get(),
        NULL,
        kTestingUsername,
        std::string(),
        "refresh_token",
        OneClickSigninSyncStarter::SYNC_WITH_DEFAULT_SETTINGS,
        NULL,
        OneClickSigninSyncStarter::NO_CONFIRMATION,
        callback);
  }

  content::TestBrowserThreadBundle thread_bundle_;

  scoped_ptr<TestingProfile> profile_;

  // Deletes itself when SigninFailed() or SigninSuccess() is called.
  OneClickSigninSyncStarter* sync_starter_;

  // Number of times that the callback is called with SYNC_SETUP_FAILURE.
  int failed_count_;

  // Number of times that the callback is called with SYNC_SETUP_SUCCESS.
  int succeeded_count_;

 private:
  static KeyedService* BuildSigninManager(content::BrowserContext* profile) {
    return new FakeSigninManager(static_cast<Profile*>(profile));
  }

  DISALLOW_COPY_AND_ASSIGN(OneClickSigninSyncStarterTest);
};

// Verifies that the callback is invoked when sync setup fails.
TEST_F(OneClickSigninSyncStarterTest, CallbackSigninFailed) {
  CreateSyncStarter(base::Bind(&OneClickSigninSyncStarterTest::Callback,
                               base::Unretained(this)));
  sync_starter_->SigninFailed(GoogleServiceAuthError(
      GoogleServiceAuthError::REQUEST_CANCELED));
  EXPECT_EQ(1, failed_count_);
  EXPECT_EQ(0, succeeded_count_);
}

// Verifies that there is no crash when the callback is NULL.
TEST_F(OneClickSigninSyncStarterTest, CallbackNull) {
  CreateSyncStarter(OneClickSigninSyncStarter::Callback());
  sync_starter_->SigninFailed(GoogleServiceAuthError(
      GoogleServiceAuthError::REQUEST_CANCELED));
  EXPECT_EQ(0, failed_count_);
  EXPECT_EQ(0, succeeded_count_);
}


text:
package com.sun.corba.se.PortableActivationIDL.RepositoryPackage;

/**
* com/sun/corba/se/PortableActivationIDL/RepositoryPackage/ServerDef.java .
* Generated by the IDL-to-Java compiler (portable), version "3.2"
* from c:/re/workspace/8-2-build-windows-amd64-cygwin/jdk8u112/7884/corba/src/share/classes/com/sun/corba/se/PortableActivationIDL/activation.idl
* Thursday, September 22, 2016 9:33:08 PM PDT
*/

public final class ServerDef implements org.omg.CORBA.portable.IDLEntity
{
  public String applicationName = null;

  // serverName values.
  public String serverName = null;

  // Class name of server's main class.
  public String serverClassPath = null;

  // class path used to run the server.
  public String serverArgs = null;

  // arguments passed to the server
  public String serverVmArgs = null;

  // arguments passed to the server's Java VM1
  public boolean isInstalled = false;

  public ServerDef ()
  {
  } // ctor

  public ServerDef (String _applicationName, String _serverName, String _serverClassPath, String _serverArgs, String _serverVmArgs, boolean _isInstalled)
  {
    applicationName = _applicationName;
    serverName = _serverName;
    serverClassPath = _serverClassPath;
    serverArgs = _serverArgs;
    serverVmArgs = _serverVmArgs;
    isInstalled = _isInstalled;
  } // ctor

} // class ServerDef


text:
#ifndef _MOVIE_DOC_H_
#define _MOVIE_DOC_H_

#define DOC_GMOVIE "pygame backend module that wraps the ffmpeg library to play video files"

#define DOC_GMOVIEMOVIE "pygame._movie.Movie(filename, surface=None): returns Movie or None\nIf the optional surface argument is a surface, then the movie will output to that surface instead of using overlays."

#define DOC_GMOVIEMOVIEPLAY "pygame._movie.Movie.play(loops=0): return None\nplays the video file loops+1 times."

#define DOC_GMOVIEMOVIESTOP "pygame._movie.Movie.stop(): return None\nstops the video file and returns it to timestamp o."

#define DOC_GMOVIEMOVIEPAUSE "pygame._movie.Movie.pause(): return None\npauses video file at that very moment or unpauses the video file."

#define DOC_GMOVIEMOVIEREWIND "pygame._movie.Movie.rewind(): return None\nsame as stop()"

#define DOC_GMOVIEMOVIERESIZE "pygame._movie.Movie.resize(width, height): return None\nresizes the video screen. If a surface has been provided, then resize will not work, to prevent image corruption issues.\nYou would need to provide a new surface to change the size."

#define DOC_GMOVIEMOVIEPAUSED "pygame._movie.Movie.paused: return bool\nchecks if the movie file has been paused"

#define DOC_GMOVIEMOVIEPLAYING "pygame._movie.Movie.playing: return bool\nchecks if the movie file is playing. True even when paused, but false when stop has been called."

#define DOC_GMOVIEMOVIEWIDTH   "pygame._movie.Movie.width: Gets or sets the width\nGet or set the width of the screen for the video playback"

#define DOC_GMOVIEMOVIEHEIGHT  "pygame._movie.Movie.height: Gets or sets the height\nGet or set the height of the screen for the video playback"

#define DOC_GMOVIEMOVIESURFACE "pygame._movie.Movie.surface: Gets or sets the surface to which the video is displayed on."

#define DOC_GMOVIEMOVIEFINISHED "pygame._movie.Movie.finished: Indicates when the video is played.\n If using multiple plays, this is not a reliable member to use, as when a video ends, regardless of if there are further plays, the finished member is triggered."

#define DOC_GMOVIEMOVIEYTOP  "pygame._movie.Movie.ytop: Gets or sets the ytop of the display rect\nThis sets the distance between the image and the top of the window. Increase it to move the image down, or decrease it to move the image up."

#define DOC_GMOVIEMOVIEXLEFT "pygame._movie.Movie.xleft: Gets or sets the xleft of the display rect\nThis sets the distance between the image and the left of the window. Increase it to move the image right, or decrease it to move the image left."

#define DOC_GMOVIEMOVIEEASY_SEEK "pygame._movie.Movie.easy_seek(second, minute, hour, reverse): return None\nThis is a non-relative seek, instead seeking to the h:mm:ss timestamp on the video as given. All arguments are needed."

#define DOC_GMOVIEMOVIESHIFT "pygame._movie.Movie.shift(ytop, xleft): return None\nShift the video image up, left, right, or down. Default values are 0,0."

#endif /*_MOVIE_DOC_H_*/


text:
package Gui;

import Atvaizdavimas.Controller.Mouse;
import Atvaizdavimas.Drawers.OpenGL.OpenGL;
import Classes.Map;
import Classes.Point;
import Classes.ShortestEdgeMap;
import Intefaces.IMap;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class MainForm extends JFrame{
    private JButton drawButton;
    private JButton loadButton;
    private JButton generateButton;
    private JPanel MainPanel;
    private JTextField pointNumberField;
    private JLabel loadErrorText;
    private JLabel generateErrorText;
    private JComboBox algorithmBox;
    private JLabel algorithmLabel;
    private JPanel OpenGLPanel;
    private JDesktopPane desktopPane;
    private IMap defaultMap = new Map();
    private IMap edgeMap = new ShortestEdgeMap();

    private IMap map;

    public MainForm(){
        super("Grafai");

        setContentPane(MainPanel);
        pack();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        generateErrorText.setVisible(false);
        loadErrorText.setVisible(false);

        // graph drawing
        drawButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                String selectedAlgorithm = algorithmBox.getSelectedItem().toString();

                if(selectedAlgorithm.equals("Kriskal"))
                {
                    map = defaultMap;

                    System.out.print(defaultMap);
                    System.out.println(String.format("================= %15s: %4.2f =================", "Medzio ilgis Dijkstra", defaultMap.TreeSize()));
                }
                else if(selectedAlgorithm.equals("Prim"))
                {
                    map = edgeMap;

                    System.out.print(edgeMap);
                    System.out.println(String.format("================= %15s: %4.2f =================","Medzio ilgis salinimas", edgeMap.TreeSize()));
                }

                OpenGL drawer = new OpenGL();
                drawer.setMap(map);
                desktopPane.removeAll();
                addGraph(drawer.getCanvas());
                new Mouse(drawer);
            }
        });

        // graph loading from file
        loadButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser fc = new JFileChooser();
                int returnVal = fc.showOpenDialog(MainForm.this);

                if (returnVal == JFileChooser.APPROVE_OPTION) {
                    File file = fc.getSelectedFile();
                    boolean noError;

                    defaultMap = new Map();
                    edgeMap = new ShortestEdgeMap();

                    noError = defaultMap.readFromFile(file);

                    if(noError){
                        defaultMap.generateTree(0);
                        defaultMap.returnTree();

                        edgeMap.setPoints(defaultMap.getPoints());
                        edgeMap.generateTree(0);
                        edgeMap.returnTree();

                        drawButton.setEnabled(true);
                        loadErrorText.setVisible(false);
                    }
                    else
                    {
                        loadErrorText.setVisible(true);
                        drawButton.setEnabled(false);
                    }
                }
            }
        });

        // graph generation
        generateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    int numPoints = Integer.parseInt(pointNumberField.getText());
                    defaultMap = new Map();
                    edgeMap = new ShortestEdgeMap();

                    defaultMap.generateMap(numPoints);
                    defaultMap.generateTree(0);
                    defaultMap.returnTree();

                    edgeMap.setPoints(defaultMap.getPoints());
                    //edgeMap.generateMap(numPoints);
                    edgeMap.generateTree(0);
                    edgeMap.returnTree();

                    drawButton.setEnabled(true);
                    generateErrorText.setVisible(false);

                } catch (NumberFormatException name)
                {
                    generateErrorText.setVisible(true);
                    drawButton.setEnabled(false);
                }
            }
        });

        setVisible(true);
    }

    public void addGraph(OpenGL canvas)
    {
        final JInternalFrame Frame = new JInternalFrame();
        Frame.setVisible(true);
        Frame.setSize(710, 500);
        Frame.setLocation(-5,-28);
        Frame.setTitle("Grafas");
        Frame.add(canvas, BorderLayout.CENTER);
        Frame.setVisible(true);
        desktopPane.add(Frame);
    }
}


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('payments', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='PledgeStandardPayment',
            fields=[
                ('payment_ptr', models.OneToOneField(auto_created=True, on_delete=django.db.models.deletion.CASCADE, parent_link=True, primary_key=True, serialize=False, to='payments.Payment')),
            ],
            options={
                'abstract': False,
            },
            bases=('payments.payment',),
        ),
    ]


text:
#include "astutil.h"
#include "expr.h"
#include "passes.h"
#include "resolution.h"
#include "stmt.h"
#include "symbol.h"

static bool
refNecessary(SymExpr* se,
             Map<Symbol*,Vec<SymExpr*>*>& defMap,
             Map<Symbol*,Vec<SymExpr*>*>& useMap) {
  Vec<SymExpr*>* defs = defMap.get(se->var);
  if (defs && defs->n > 1)
    return true;
  for_uses(use, useMap, se->var) {
    if (CallExpr* call = toCallExpr(use->parentExpr)) {
      if (FnSymbol* fn = call->isResolved()) {
        ArgSymbol* formal = actual_to_formal(use);
        if (formal->defPoint->getFunction()->_this == formal)
          return true;
        if (formal->intent == INTENT_INOUT || formal->intent == INTENT_OUT)
          return true;
        if (formal->type->symbol->hasFlag(FLAG_REF) &&
            (fn->hasFlag(FLAG_ALLOW_REF) ||
             formal->hasFlag(FLAG_WRAP_WRITTEN_FORMAL)))
          return true;
      } else if (call->isPrimitive(PRIM_MOVE)) {
        if (refNecessary(toSymExpr(call->get(1)), defMap, useMap))
          return true;
      } else if (call->isPrimitive(PRIM_GET_MEMBER) ||
                 call->isPrimitive(PRIM_GET_SVEC_MEMBER)) {
        CallExpr* move = toCallExpr(call->parentExpr);
        INT_ASSERT(move);
        INT_ASSERT(move->isPrimitive(PRIM_MOVE));
        if (refNecessary(toSymExpr(move->get(1)), defMap, useMap))
          return true;
      } else if (call->isPrimitive(PRIM_SET_MEMBER)) {
        if (!call->get(2)->typeInfo()->refType)
          return true;
      } else if (call->isPrimitive(PRIM_RETURN) ||
                 call->isPrimitive(PRIM_YIELD)) {
        return true;
      } else if (call->isPrimitive(PRIM_WIDE_GET_LOCALE) ||
                 call->isPrimitive(PRIM_WIDE_GET_NODE)) {
        // If we are extracting a field from the wide pointer, we need to keep it as a pointer.
        // Dereferencing would be premature.
        return true;
      } else if (call->isPrimitive(PRIM_DEREF) &&
                 isRecordWrappedType(se->var->type->getValType())) {
        // Heuristic: if we are dereferencing an array reference,
        // that reference may still be needed.
        Expr* callParent = call->parentExpr;
        INT_ASSERT(callParent);
        if (CallExpr* callParentCall = toCallExpr(callParent)) {
          if (callParentCall->isPrimitive(PRIM_MOVE)) {
            INT_ASSERT(call == callParentCall->get(2));
            SymExpr* dest = toSymExpr(callParentCall->get(1));
            INT_ASSERT(dest);
            if (dest->var->hasFlag(FLAG_COERCE_TEMP))
              return true;
          }
        }
      }
    }
  }
  return false;
}

static void callGetterForValueReturn()
{
  //
  // change call of reference function to value function
  //
  Map<Symbol*,Vec<SymExpr*>*> defMap;
  Map<Symbol*,Vec<SymExpr*>*> useMap;
  buildDefUseMaps(defMap, useMap);
  forv_Vec(CallExpr, call, gCallExprs) {
    if (FnSymbol* fn = call->isResolved()) {
      if (FnSymbol* copy = fn->valueFunction) {
        if (CallExpr* move = toCallExpr(call->parentExpr)) {
          INT_ASSERT(move->isPrimitive(PRIM_MOVE));
          SymExpr* se = toSymExpr(move->get(1));
          INT_ASSERT(se);
          SET_LINENO(move);
          if (!refNecessary(se, defMap, useMap)) {
            SymExpr* base = toSymExpr(call->baseExpr);
            base->var = copy;
            VarSymbol* tmp = newTemp(copy->retType);
            // Danger, Will Robinson! We are about to take the address of this
            // temporary.  The temporary must remain in-scope for as long as
            // anything referred to in the return value of the original 'fn'.
            // We need to select a scope that contains all uses of the original
            // LHS se, and put the declaration for our temp variable there --
            // to make sure that the deref temp does not go out of scope before
            // references to it do.  Note #1.
            // For now, we just use the declaration scope of the original se.
            se->var->defPoint->insertAfter(new DefExpr(tmp));
#ifndef HILDE_MM
            // Why is this here?
            // Marking variables for autocopy/autodestroy ought to be done in
            // one place once and for all.  Is this that place?
            if (requiresImplicitDestroy(call)) {
              tmp->addFlag(FLAG_INSERT_AUTO_COPY);
              tmp->addFlag(FLAG_INSERT_AUTO_DESTROY);
            }
#endif
            if (useMap.get(se->var) && useMap.get(se->var)->n > 0) {
              move->insertAfter(new CallExpr(PRIM_MOVE, se->var,
                                  new CallExpr(PRIM_ADDR_OF, tmp)));
            } else {
              se->var->defPoint->remove();
            }
            se->var = tmp;
          }
        } else
          INT_FATAL(call, "unexpected case");
      }
    }
  }
  freeDefUseMaps(defMap, useMap);
}

static void removeRefsToWrappedTypes()
{
  //
  // remove references to array wrapper records, domain wrapper
  // records, and iterator records; otherwise we can end up returning
  // a reference to a location that is on the stack
  //
  forv_Vec(DefExpr, def, gDefExprs) {
    if (!isTypeSymbol(def->sym) && def->sym->type) {
      if (Type* vt = def->sym->getValType()) {
        if (isRecordWrappedType(vt)) {
          def->sym->type = vt;
        }
      }
      if (FnSymbol* fn = toFnSymbol(def->sym)) {
        if (Type* vt = fn->retType->getValType()) {
          if (isRecordWrappedType(vt)) {
            fn->retType = vt;
            fn->retTag = RET_VALUE;
          }
        }
      }
    }
  }
  forv_Vec(CallExpr, call, gCallExprs) {
    if (call->isPrimitive(PRIM_DEREF) ||
        call->isPrimitive(PRIM_ADDR_OF)) {
      Type* vt = call->get(1)->typeInfo();
      if (isReferenceType(vt))
        vt = vt->getValType();
      if (isRecordWrappedType(vt))
        call->replace(call->get(1)->remove());
    }
    if (call->isPrimitive(PRIM_GET_MEMBER)) {
      Type* vt = call->get(2)->getValType();
      if (isRecordWrappedType(vt))
        call->primitive = primitives[PRIM_GET_MEMBER_VALUE];
    }
    if (call->isPrimitive(PRIM_GET_SVEC_MEMBER)) {
      Type* tupleType = call->get(1)->getValType();
      Type* vt = tupleType->getField("x1")->getValType();
      if (isRecordWrappedType(vt))
        call->primitive = primitives[PRIM_GET_SVEC_MEMBER_VALUE];
    }
    if (call->isPrimitive(PRIM_ARRAY_GET)) {
      Type* vt = call->getValType();
      if (isRecordWrappedType(vt))
        call->primitive = primitives[PRIM_ARRAY_GET_VALUE];
    }
  }
}

// Look for and replace the pattern:
//  ('move' ref_tmp ('addr of' var1))
//  ('move' var2 ('deref' ref_tmp))
// with
//  ('move' var2 var1)
//
static void removeRefDerefPairs()
{
  // Walk all "addr of" primitives.
  forv_Vec(CallExpr, call, gCallExprs)
  {
    if (! call->isPrimitive(PRIM_ADDR_OF))
      continue;

    // Ignore calls that are not in the tree.
    if (! call->parentExpr)
      continue;

    // Get the statement-level expression containing this primitive.
    CallExpr* addrOfStmt = toCallExpr(call->getStmtExpr());
    INT_ASSERT(addrOfStmt);
    INT_ASSERT(addrOfStmt->isPrimitive(PRIM_MOVE));

    // Get the next statement.
    if (CallExpr* derefStmt = toCallExpr(addrOfStmt->next))
    {
      // Make sure it is a move
      if (! derefStmt->isPrimitive(PRIM_MOVE))
        continue;

      // See if it contains a deref
      if (CallExpr* deref = toCallExpr(derefStmt->get(2)))
      {
        // Make sure it is a deref primitive
        if (! deref->isPrimitive(PRIM_DEREF))
          continue;

        // See if its arg is the LHS of the addrOfStmt
        SymExpr* derefArg = toSymExpr(deref->get(1));
        INT_ASSERT(derefArg);
        SymExpr* refTmp = toSymExpr(addrOfStmt->get(1));
        INT_ASSERT(refTmp);
        if (derefArg->var == refTmp->var)
        {
          // Bingo.  Let's do the transformation.

          // Actually, we leave the deref in place in case there are other uses
          // of the refTmp.  But we replace the deref call with
          // the (non-ref) operand of the 'addr of' primitive.

          SymExpr* addrOfArg = toSymExpr(call->get(1));
          // We expect the argument of the "addr of" primitive to be a SymExpr.
          INT_ASSERT(addrOfArg);

          SET_LINENO(derefStmt);
          deref->replace(new SymExpr(addrOfArg->var));
        }
      }
    }
  }
}

//
// Replace getter calls with setter calls where the return type is only read.
// Also convert some references to values, to get required semantics.
//
void cullOverReferences() {
  callGetterForValueReturn();
  removeRefsToWrappedTypes();
  removeRefDerefPairs();
}

//########################################################################
//# NOTES
//#
//# Note #1: In places where the return value of a setter is immediately
//# dereferenced, we get code that looks like this:
//#      (875642 'move' tmp[954861](875648 call dsiAccess[875924] call_tmp[875634] i[875526]))
//#      (954865 'move' call_tmp[875531](954863 'addr of' tmp[954861]))
//#      (875650 'move' ret[875535](875652 'deref' call_tmp[875531]))
//# i.e. a getter followed by 'addr of' followed by 'deref'.
//# A later pass apparently knows how to collapse this out, but it creates
//# problems for AMM (as implemented).  It would probably be good to follow
//# the setter -> getter replacement with a pass that looks for this kind of
//# no-op and removes them.
//#