text:
package xsd

import (
	"encoding/xml"
	"fmt"
	"regexp"
	"strconv"
	"strings"
	"time"

	"aqwari.net/xml/internal/dependency"
	"aqwari.net/xml/xmltree"
)

func hasCycle(root *xmltree.Element, visited map[*xmltree.Element]struct{}) bool {
	if visited == nil {
		visited = make(map[*xmltree.Element]struct{})
	}
	visited[root] = struct{}{}
	for i := range root.Children {
		el := &root.Children[i]
		if _, ok := visited[el]; ok {
			return true
		}
		visited[el] = struct{}{}
		if hasCycle(el, visited) {
			return true
		}
	}
	delete(visited, root)
	return false
}

// A Ref contains the canonical namespace of a schema document, and
// possibly a URI to retrieve the document from. It is not required
// for XML Schema documents to provide the location of schema that
// they import; it is expected that all well-known schema namespaces
// are available to the consumer of a schema beforehand.
type Ref struct {
	Namespace, Location string
}

// Imports reads an XML document containing one or more <schema>
// elements and returns a list of canonical XML name spaces that
// the schema imports or includes, along with a URL for the schema,
// if provided.
func Imports(data []byte) ([]Ref, error) {
	var result []Ref

	root, err := xmltree.Parse(data)
	if err != nil {
		return nil, err
	}

	for _, v := range root.Search(schemaNS, "import") {
		s := Ref{v.Attr("", "namespace"), v.Attr("", "schemaLocation")}
		result = append(result, s)
	}

	var schema []*xmltree.Element
	if (root.Name == xml.Name{schemaNS, "schema"}) {
		schema = []*xmltree.Element{root}
	} else {
		schema = root.Search(schemaNS, "schema")
	}

	for _, tree := range schema {
		ns := tree.Attr("", "targetNamespace")
		for _, v := range tree.Search(schemaNS, "include") {
			s := Ref{ns, v.Attr("", "schemaLocation")}
			result = append(result, s)
		}
	}

	return result, nil
}

// Normalize reads XML schema documents and returns xml trees
// for each schema with the following properties:
//
// * various XSD shorthand, such as omitting <complexContent>,
//   are expanded into their canonical forms.
// * all links are dereferenced by merging the linked element.
// * all types have names. For anonymous types, unique (per
//   namespace) names of the form "_anon1", "_anon2", etc are
//   generated, and the attribute "_isAnonymous" is set to
//   "true".
//
// Because one document may contain more than one schema, the
// number of trees returned by Normalize may not equal the
// number of arguments.
func Normalize(docs ...[]byte) ([]*xmltree.Element, error) {
	docs = append(docs, StandardSchema...)
	result := make([]*xmltree.Element, 0, len(docs))

	for _, data := range docs {
		root, err := xmltree.Parse(data)
		if err != nil {
			return nil, err
		}
		if (root.Name == xml.Name{schemaNS, "schema"}) {
			result = append(result, root)
		} else {
			result = append(result, root.Search(schemaNS, "schema")...)
		}
	}
	for _, root := range result {
		attributeDefaultType(root)
		elementDefaultType(root)
		copyEltNamesToAnonTypes(root)
	}
	typeCounter := 0
	for _, root := range result {
		if err := nameAnonymousTypes(root, &typeCounter); err != nil {
			return nil, err
		}
		if err := setChoicesOptional(root); err != nil {
			return nil, err
		}
	}
	for _, root := range result {
		expandComplexShorthand(root)
	}
	if err := flattenRef(result); err != nil {
		return nil, err
	}
	return result, nil
}

// Parse reads XML documents containing one or more <schema>
// elements. The returned slice has one Schema for every <schema>
// element in the documents. Parse will not fetch schema used in
// <import> or <include> statements; use the Imports function to
// find any additional schema documents required for a schema.
func Parse(docs ...[]byte) ([]Schema, error) {
	var (
		result = make([]Schema, 0, len(docs))
		parsed = make(map[string]Schema, len(docs))
		types  = make(map[xml.Name]Type)
	)

	schema, err := Normalize(docs...)
	if err != nil {
		return nil, err
	}

	for _, root := range schema {
		tns := root.Attr("", "targetNamespace")
		s := Schema{TargetNS: tns, Types: make(map[xml.Name]Type)}
		if err := s.parse(root); err != nil {
			return nil, err
		}
		parsed[tns] = s
	}

	for _, s := range parsed {
		for _, t := range s.Types {
			types[XMLName(t)] = t
		}
	}

	for _, root := range schema {
		s := parsed[root.Attr("", "targetNamespace")]
		if err := s.resolvePartialTypes(types); err != nil {
			return nil, err
		}
		err := s.addElementTypeAliases(root, types)
		if err != nil {
			return nil, err
		}
		s.propagateMixedAttr()
		result = append(result, s)
	}
	result = append(result, builtinSchema)
	return result, nil
}

func parseType(name xml.Name) Type {
	builtin, err := ParseBuiltin(name)
	if err != nil {
		return linkedType(name)
	}
	return builtin
}

func anonTypeName(n int, ns string) xml.Name {
	return xml.Name{ns, fmt.Sprintf("_anon%d", n)}
}

/* Convert
<element name="foo">
  <complexType>
  ...
  </complexType>
</element>

to

<element name="foo" type="foo">
  <complexType name="foo">
  ...
  </complexType>
</element>
*/
func copyEltNamesToAnonTypes(root *xmltree.Element) {
	used := make(map[xml.Name]struct{})
	tns := root.Attr("", "targetNamespace")

	namedTypes := and(isType, hasAttr("", "name"))
	for _, el := range root.SearchFunc(namedTypes) {
		used[el.ResolveDefault(el.Attr("", "name"), tns)] = struct{}{}
	}

	eltWithAnonType := and(
		or(isElem(schemaNS, "element"), isElem(schemaNS, "attribute")),
		hasAttr("", "name"),
		hasAnonymousType)

	for _, el := range root.SearchFunc(eltWithAnonType) {
		// Make sure we can use this element's name
		xmlname := el.ResolveDefault(el.Attr("", "name"), tns)
		if _, ok := used[xmlname]; ok {
			continue
		}
		used[xmlname] = struct{}{}
		for i, t := range el.Children {
			if !isAnonymousType(&t) {
				continue
			}
			t.SetAttr("", "name", el.Attr("", "name"))
			el.SetAttr("", "type", el.Prefix(xmlname))

			el.Children = append(el.Children[:i], el.Children[i+1:]...)
			el.Content = nil
			root.Children = append(root.Children, t)
			break
		}
	}
}

// Inside a <xs:choice>, set all children to optional
// If child is a <xs:sequence> set its children to optional
func setChoicesOptional(root *xmltree.Element) error {

	for _, el := range root.SearchFunc(isElem(schemaNS, "choice")) {
		for i := 0; i < len(el.Children); i++ {
			t := el.Children[i]

			if t.Name.Space == schemaNS && t.Name.Local == "sequence" {
				for j := 0; j < len(t.Children); j++ {
					t2 := t.Children[j]
					t2.SetAttr("", "minOccurs", "0")
					t.Children[j] = t2
				}
			} else {
				t.SetAttr("", "minOccurs", "0")
			}

			el.Children[i] = t
		}
	}

	return nil
}

/*
Convert

  <xs:complexType name="foo" base="xs:anyType"/>
    <xs:sequence>
      <xs:element name="a">
        <xs:simpleType base="xs:int">
          ...
        </xs:simpleType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>

to

  <xs:complexType name="foo" base="xs:anyType"/>
    <xs:sequence>
      <xs:element name="a">
        <xs:simpleType name="_anon1" _isAnonymous="true" base="xs:int">
          ...
        </xs:simpleType>
      </xs:element>
    </xs:sequence>
  </xs:complexType>
*/
func nameAnonymousTypes(root *xmltree.Element, typeCounter *int) error {
	var (
		updateAttr string
		accum      bool
	)
	targetNS := root.Attr("", "targetNamespace")
	for _, el := range root.SearchFunc(hasAnonymousType) {
		if el.Name.Space != schemaNS {
			continue
		}
		switch el.Name.Local {
		case "element", "attribute":
			updateAttr = "type"
			accum = false
		case "list":
			updateAttr = "itemType"
			accum = false
		case "restriction":
			updateAttr = "base"
			accum = false
		case "union":
			updateAttr = "memberTypes"
			accum = true
		default:
			return fmt.Errorf("Did not expect <%s> to have an anonymous type",
				el.Prefix(el.Name))
		}
		for i := 0; i < len(el.Children); i++ {
			t := el.Children[i]

			if !isAnonymousType(&t) {
				continue
			}
			*typeCounter++

			name := anonTypeName(*typeCounter, targetNS)
			qname := el.Prefix(name)

			t.SetAttr("", "name", name.Local)
			t.SetAttr("", "_isAnonymous", "true")
			if accum {
				qname = el.Attr("", updateAttr) + " " + qname
			}
			el.SetAttr("", updateAttr, qname)
			el.Children = append(el.Children[:i], el.Children[i+1:]...)
			el.Content = nil
			root.Children = append(root.Children, t)
			if !accum {
				break
			}
		}
	}
	return nil
}

/*

Dereference all ref= links within a document.

  <attribute name="id" type="xsd:ID" />
  <complexType name="MyType">
    <attribute ref="tns:id" />
  </complexType>

becomes

  <complexType name="MyType">
    <attribute name="id" type="xsd:ID" />
  </complexType>

*/
func flattenRef(schema []*xmltree.Element) error {
	var (
		depends = new(dependency.Graph)
		index   = indexSchema(schema)
	)
	for id, el := range index.eltByID {
		if el.Attr("", "ref") == "" {
			continue
		}
		name := el.Resolve(el.Attr("", "ref"))
		if dep, ok := index.ElementID(name, el.Name); !ok {
			return fmt.Errorf("could not find ref %s in %s",
				el.Attr("", "ref"), el)
		} else {
			depends.Add(id, dep)
		}
	}
	depends.Flatten(func(id int) {
		el := index.eltByID[id]
		if el.Attr("", "ref") == "" {
			return
		}
		ref := el.Resolve(el.Attr("", "ref"))
		real, ok := index.ByName(ref, el.Name)
		if !ok {
			panic("bug building dep tree; missing " + el.Attr("", "ref"))
		}
		*el = *deref(el, real)
	})
	for ns, doc := range schema {
		unpackGroups(doc)
		if hasCycle(doc, nil) {
			return fmt.Errorf("cycle detected after flattening references "+
				"in schema %d:\n%s", ns, xmltree.MarshalIndent(doc, "", "  "))
		}
	}
	return nil
}

// Flatten a reference to an XML element, returning the full XML
// object.
func deref(ref, real *xmltree.Element) *xmltree.Element {
	el := new(xmltree.Element)
	el.Scope = ref.Scope
	el.Name = real.Name
	el.StartElement.Attr = append([]xml.Attr{}, real.StartElement.Attr...)
	el.Content = append([]byte{}, real.Content...)
	el.Children = append([]xmltree.Element{}, real.Children...)

	// Some attributes can contain a qname, and must be converted to use the
	// xmlns prefixes in ref's scope.
	hasQName := map[xml.Name]bool{
		xml.Name{"", "type"}: true,
	}
	for i, attr := range el.StartElement.Attr {
		if hasQName[attr.Name] {
			xmlname := real.Resolve(attr.Value)
			attr.Value = ref.Prefix(xmlname)
			el.StartElement.Attr[i] = attr
		}
	}
	// If there are child elements, rather than checking all children
	// for xmlns conversion, we can just import the xmlns prefixes
	if len(el.Children) > 0 {
		el.Scope = *real.JoinScope(&ref.Scope)
	}

	// Attributes added to the reference overwrite attributes in the
	// referenced element.
	for _, attr := range ref.StartElement.Attr {
		if (attr.Name != xml.Name{"", "ref"}) {
			el.SetAttr(attr.Name.Space, attr.Name.Local, attr.Value)
		}
	}

	return el
}

// After dereferencing groups and attributeGroups, we need to
// unpack them within their parent elements.
func unpackGroups(doc *xmltree.Element) {
	isGroup := or(isElem(schemaNS, "group"), isElem(schemaNS, "attributeGroup"))
	hasGroups := hasChild(isGroup)

	for _, el := range doc.SearchFunc(hasGroups) {
		children := make([]xmltree.Element, 0, len(el.Children))
		for _, c := range el.Children {
			if isGroup(&c) {
				children = append(children, c.Children...)
			} else {
				children = append(children, c)
			}
		}
		el.Children = children
	}
}

// a complex type defined without any simpleContent or
// complexContent is interpreted as shorthand for complex
// content that restricts anyType.
func expandComplexShorthand(root *xmltree.Element) {
	isComplexType := isElem(schemaNS, "complexType")

Loop:
	for _, el := range root.SearchFunc(isComplexType) {
		newChildren := make([]xmltree.Element, 0, len(el.Children))
		restrict := xmltree.Element{
			Scope:    el.Scope,
			Children: make([]xmltree.Element, 0, len(el.Children)),
		}

		for _, child := range el.Children {
			if child.Name.Space != schemaNS {
				newChildren = append(newChildren, child)
				continue
			}
			switch child.Name.Local {
			case "annotation":
				newChildren = append(newChildren, child)
				continue
			case "simpleContent", "complexContent":
				continue Loop
			}
			restrict.Children = append(restrict.Children, child)
		}
		restrict.Name.Space = schemaNS
		restrict.Name.Local = "restriction"
		restrict.SetAttr("", "base", restrict.Prefix(AnyType.Name()))

		content := xmltree.Element{
			Scope:    el.Scope,
			Children: []xmltree.Element{restrict},
		}
		content.Name.Space = schemaNS
		content.Name.Local = "complexContent"

		el.Content = nil
		el.Children = append(newChildren, content)
	}
}

func (s *Schema) addElementTypeAliases(root *xmltree.Element, types map[xml.Name]Type) error {
	for _, el := range root.Children {
		if (el.Name != xml.Name{schemaNS, "element"}) {
			continue
		}
		name := el.ResolveDefault(el.Attr("", "name"), s.TargetNS)
		ref := el.Resolve(el.Attr("", "type"))
		if ref.Local == "" || name.Local == "" {
			continue
		}
		if _, ok := s.Types[name]; !ok {
			if t, ok := s.lookupType(linkedType(ref), types); !ok {
				return fmt.Errorf("could not lookup type %s for element %s",
					el.Prefix(ref), el.Prefix(name))
			} else {
				s.Types[name] = t
			}
		}
	}
	return nil
}

// Propagate the "mixed" attribute of a type appropriately to
// all types derived from it.  For the propagation rules, see
// https://www.w3.org/TR/xmlschema-1/#coss-ct. That Definition is written
// for a computer, so I've translated the relevant portion into plain
// English. My translation may be incorrect; check the reference if you
// think so. The rules are as follows:
//
// 	- When extending a complex type, the derived type *must* be mixed iff
//    the base type is mixed.
// 	- When restricting a complex type, the derived type *may* be mixed iff
//    the base type is mixed.
// 	- The builtin "xs:anyType" is mixed.
//
// This package extends the concept of "Mixed" to apply to complex types
// with simpleContent. This is done because Mixed is used as an indicator
// that the user should care about the chardata content in a type.
func (s *Schema) propagateMixedAttr() {
	for _, t := range s.Types {
		propagateMixedAttr(t, Base(t), 0)
	}
}

func propagateMixedAttr(t, b Type, depth int) {
	const maxDepth = 1000
	if b == nil || depth > maxDepth {
		return
	}
	// Mixed attr needs to "bubble up" from the bottom, so we
	// recurse to do this backwards.
	propagateMixedAttr(b, Base(b), depth+1)

	c, ok := t.(*ComplexType)
	if !ok || c.Mixed {
		return
	}
	switch b := b.(type) {
	case Builtin:
		if b == AnyType {
			c.Mixed = c.Mixed || c.Extends
		}
	case *ComplexType:
		if c.Extends {
			c.Mixed = b.Mixed
		}
	case *SimpleType:
		c.Mixed = true
	default:
		panic(fmt.Sprintf("unexpected %T", b))
	}
}

// 3.2.2 XML Representation of Attribute Declaration Schema Components
//
// Specifies that attributes without a type default to anySimpleType.
//
// http://www.w3.org/TR/xmlschema-1/#cAttribute_Declarations
func attributeDefaultType(root *xmltree.Element) {
	var (
		isAttr    = isElem(schemaNS, "attribute")
		hasNoType = hasAttrValue("", "type", "")
		anyType   = xml.Name{Space: schemaNS, Local: "anySimpleType"}
	)
	for _, el := range root.SearchFunc(and(isAttr, hasNoType)) {
		el.SetAttr("", "type", el.Prefix(anyType))
	}
}

// 3.3.2 XML Representation of Element Declaration Schema Components
//
// Elements types default to anyType
//
// https://www.w3.org/TR/xmlschema-1/#Element_Declaration_details
func elementDefaultType(root *xmltree.Element) {
	var (
		isElement = isElem(schemaNS, "element")
		hasNoType = hasAttrValue("", "type", "")
		anyType   = xml.Name{Space: schemaNS, Local: "anyType"}
	)
	for _, el := range root.SearchFunc(and(isElement, hasNoType)) {
		el.SetAttr("", "type", el.Prefix(anyType))
	}
}

func (s *Schema) parse(root *xmltree.Element) error {
	return s.parseTypes(root)
}

func (s *Schema) parseTypes(root *xmltree.Element) (err error) {
	defer catchParseError(&err)
	tns := root.Attr("", "targetNamespace")

	for _, el := range root.Search(schemaNS, "complexType") {
		t := s.parseComplexType(el)
		s.Types[t.Name] = t
	}
	for _, el := range root.Search(schemaNS, "simpleType") {
		t := s.parseSimpleType(el)
		s.Types[t.Name] = t
	}
	s.Types[xml.Name{tns, "_self"}] = s.parseSelfType(root)
	return err
}

func (s *Schema) parseSelfType(root *xmltree.Element) *ComplexType {
	self := *root
	self.Content = nil
	self.Children = nil
	for _, el := range root.Children {
		if (el.Name == xml.Name{schemaNS, "element"}) {
			self.Children = append(self.Children, el)
		}
	}
	newdoc := self
	self.Name.Local = "complexType"
	self.SetAttr("", "name", "_self")
	newdoc.Children = []xmltree.Element{self}
	expandComplexShorthand(&newdoc)
	return s.parseComplexType(&newdoc.Children[0])
}

// http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/structures.html#element-complexType
func (s *Schema) parseComplexType(root *xmltree.Element) *ComplexType {
	var t ComplexType
	var doc annotation
	t.Name = root.ResolveDefault(root.Attr("", "name"), s.TargetNS)
	t.Abstract = parseBool(root.Attr("", "abstract"))
	t.Mixed = parseBool(root.Attr("", "mixed"))

	// We set this special attribute in a pre-processing step.
	t.Anonymous = (root.Attr("", "_isAnonymous") == "true")

	walk(root, func(el *xmltree.Element) {
		switch el.Name.Local {
		case "annotation":
			doc = doc.append(parseAnnotation(el))
		case "simpleContent":
			t.parseSimpleContent(s.TargetNS, el)
		case "complexContent":
			t.parseComplexContent(s.TargetNS, el)
		default:
			stop("unexpected element " + el.Name.Local)
		}
	})
	t.Doc += string(doc)
	return &t
}

// simpleContent indicates that the content model of the new type
// contains only character data and no elements
func (t *ComplexType) parseSimpleContent(ns string, root *xmltree.Element) {
	var doc annotation

	t.Mixed = true
	walk(root, func(el *xmltree.Element) {
		switch el.Name.Local {
		case "annotation":
			doc = doc.append(parseAnnotation(el))
		case "restriction":
			t.Base = parseType(el.Resolve(el.Attr("", "base")))
		case "extension":
			t.Base = parseType(el.Resolve(el.Attr("", "base")))
			t.Extends = true
			for _, v := range el.Search(schemaNS, "attribute") {
				t.Attributes = append(t.Attributes, parseAttribute(ns, v))
			}
		}
	})
	t.Doc += string(doc)
}

// The complexContent element signals that we intend to restrict or extend
// the content model of a complex type.
func (t *ComplexType) parseComplexContent(ns string, root *xmltree.Element) {
	var doc annotation
	if mixed := root.Attr("", "mixed"); mixed != "" {
		t.Mixed = parseBool(mixed)
	}
	walk(root, func(el *xmltree.Element) {
		switch el.Name.Local {
		case "extension":
			t.Extends = true
			fallthrough
		case "restriction":
			t.Base = parseType(el.Resolve(el.Attr("", "base")))

			for _, v := range el.Search(schemaNS, "any") {
				t.Elements = append(t.Elements, parseAnyElement(ns, v))
				break
			}

			usedElt := make(map[xml.Name]int)
			for _, v := range el.Search(schemaNS, "element") {
				elt := parseElement(ns, v)
				if existing, ok := usedElt[elt.Name]; !ok {
					usedElt[elt.Name] = len(t.Elements)
					t.Elements = append(t.Elements, elt)
				} else {
					t.Elements[existing] = joinElem(t.Elements[existing], elt)
				}
			}

			for _, v := range el.Search(schemaNS, "attribute") {
				t.Attributes = append(t.Attributes, parseAttribute(ns, v))
			}
		case "annotation":
			doc = doc.append(parseAnnotation(el))
		default:
			stop("unexpected element " + el.Name.Local)
		}
	})
	t.Doc += string(doc)
}

func joinElem(a, b Element) Element {
	if a.Doc != "" {
		a.Doc += "\n"
	}
	a.Doc += b.Doc
	a.Abstract = a.Abstract && b.Abstract
	a.Plural = a.Plural || b.Plural
	a.Optional = a.Optional || b.Optional
	a.Nillable = a.Nillable || b.Nillable

	if a.Default != b.Default {
		a.Default = ""
	}

	return a
}

func parseInt(s string) int {
	s = strings.TrimSpace(s)
	switch s {
	case "":
		return 0
	case "unbounded":
		return -1
	}
	n, err := strconv.Atoi(s)
	if err != nil {
		stop(err.Error())
	}
	return n
}

// https://www.w3.org/TR/xmlschema-2/#decimal
func parseDecimal(s string) float64 {
	s = strings.TrimSpace(s)
	switch s {
	case "":
		return 0
	}
	n, err := strconv.ParseFloat(s, 64)
	if err != nil {
		stop(err.Error())
	}
	return n
}

func parseBool(s string) bool {
	switch s {
	case "", "0", "false":
		return false
	case "1", "true":
		return true
	}
	stop("Invalid boolean value " + s)
	return false
}

func parsePlural(el *xmltree.Element) bool {
	if min := parseInt(el.Attr("", "minOccurs")); min > 1 {
		return true
	} else if max := parseInt(el.Attr("", "maxOccurs")); max < 0 || max > 1 {
		return true
	}
	return false
}

func parseAnyElement(ns string, el *xmltree.Element) Element {
	var base Type = AnyType
	typeattr := el.Attr("", "type")
	if typeattr != "" {
		base = parseType(el.Resolve(typeattr))
	}
	return Element{
		Plural:   parsePlural(el),
		Type:     base,
		Wildcard: true,
	}
}

func parseElement(ns string, el *xmltree.Element) Element {
	var doc annotation
	e := Element{
		Name:     el.ResolveDefault(el.Attr("", "name"), ns),
		Type:     parseType(el.Resolve(el.Attr("", "type"))),
		Default:  el.Attr("", "default"),
		Abstract: parseBool(el.Attr("", "abstract")),
		Nillable: parseBool(el.Attr("", "nillable")),
		Plural:   parsePlural(el),
		Scope:    el.Scope,
	}
	if el.Attr("", "type") == "" {
		e.Type = AnyType
	}
	if x := el.Attr("", "minOccurs"); x != "" && parseInt(x) == 0 {
		e.Optional = true
	} else if e.Default != "" {
		e.Optional = true
	}
	walk(el, func(el *xmltree.Element) {
		if el.Name.Local == "annotation" {
			doc = doc.append(parseAnnotation(el))
		}
	})
	t, ok := e.Type.(linkedType)
	if ok {
		e.Name.Space = t.Space
	}
	e.Doc = string(doc)
	e.Attr = el.StartElement.Attr
	return e
}

func parseAttribute(ns string, el *xmltree.Element) Attribute {
	var a Attribute
	var doc annotation
	// Non-QName xml attributes explicitly do *not* have a namespace.
	if name := el.Attr("", "name"); strings.Contains(name, ":") {
		a.Name = el.Resolve(el.Attr("", "name"))
	} else {
		a.Name.Local = name
	}
	a.Name.Space = ns
	a.Type = parseType(el.Resolve(el.Attr("", "type")))
	a.Default = el.Attr("", "default")
	a.Scope = el.Scope
	a.Optional = el.Attr("", "use") != "required"

	walk(el, func(el *xmltree.Element) {
		if el.Name.Local == "annotation" {
			doc = doc.append(parseAnnotation(el))
		}
	})
	a.Doc = string(doc)
	// Other attributes could be useful later. One such attribute is
	// wsdl:arrayType.
	a.Attr = el.StartElement.Attr
	return a
}

func (s *Schema) parseSimpleType(root *xmltree.Element) *SimpleType {
	var t SimpleType
	var doc annotation

	t.Name = root.ResolveDefault(root.Attr("", "name"), s.TargetNS)
	t.Anonymous = (root.Attr("", "_isAnonymous") == "true")
	walk(root, func(el *xmltree.Element) {
		switch el.Name.Local {
		case "restriction":
			t.Base = parseType(el.Resolve(el.Attr("", "base")))
			t.Restriction = parseSimpleRestriction(el, t.Base)
		case "list":
			t.Base = parseType(el.Resolve(el.Attr("", "itemType")))
			t.List = true
		case "union":
			for _, name := range strings.Fields(el.Attr("", "memberTypes")) {
				type_ := parseType(el.Resolve(name))
				t.Union = append(t.Union, type_)
				t.Base = AnySimpleType
			}
		case "annotation":
			doc = doc.append(parseAnnotation(el))
		}
	})
	t.Doc = string(doc)
	return &t
}

func parseAnnotation(el *xmltree.Element) (doc annotation) {
	if err := xmltree.Unmarshal(el, &doc); err != nil {
		stop(err.Error())
	}
	return doc
}

func parseSimpleRestriction(root *xmltree.Element, base Type) Restriction {
	var r Restriction
	var doc annotation
	// Most of the restrictions on a simpleType are suited for
	// validating input. This package is not a validator; we assume
	// that the server sends valid data, and that it will tell us if
	// our data is wrong. As such, most of the fields here are
	// ignored.
	walk(root, func(el *xmltree.Element) {
		switch el.Name.Local {
		case "enumeration":
			r.Enum = append(r.Enum, el.Attr("", "value"))
		case "minExclusive", "minInclusive":
			r.MinDate, r.Min = parseMinMaxRestriction(el, base)
		case "maxExclusive", "maxInclusive":
			r.MaxDate, r.Max = parseMinMaxRestriction(el, base)
		case "length":
			r.Length = parseInt(el.Attr("", "value"))
		case "maxLength":
			r.MaxLength = parseInt(el.Attr("", "value"))
		case "minLength":
			r.MinLength = parseInt(el.Attr("", "value"))
		case "pattern":
			// We don't fully implement XML Schema's pattern language, and
			// we don't want to stop a parse because of this. Instead, if we
			// cannot compile a regex, we'll add the error msg to the annotation
			// for this restriction.
			pat := el.Attr("", "value")
			if r.Pattern != nil {
				pat = r.Pattern.String() + "|" + pat
			}
			reg, err := parsePattern(pat)
			if err != nil {
				msg := fmt.Sprintf("This type must conform to the pattern %q, but the XSD library could not parse the regular expression. (%v)", pat, err)
				doc = doc.append(annotation(msg))
			}
			r.Pattern = reg
		case "whiteSpace":
			break // TODO(droyo)
		case "fractionDigits":
			r.Precision = parseInt(el.Attr("", "value"))
			if r.Precision < 0 {
				stop("Invalid fractionDigits value " + el.Attr("", "value"))
			}
		case "annotation":
			doc = doc.append(parseAnnotation(el))
		case "totalDigits":
			r.TotalDigits = parseInt(el.Attr("", "value"))
		}
	})
	r.Doc = string(doc)
	return r
}

// For minInclusive, minExclusive, maxInclusive and maxExclusive restrictions
func parseMinMaxRestriction(el *xmltree.Element, base Type) (time.Time, float64) {
	var date time.Time
	var decimal float64
	if v, ok := base.(Builtin); ok {
		var format string
		if v == Date {
			format = "2006-01-02"
		} else if v == DateTime {
			format = time.RFC3339
		}

		if format != "" {
			d, err := time.Parse(format, el.Attr("", "value"))
			if err != nil {
				stop(err.Error())
			}
			date = d
		} else {
			decimal = parseDecimal(el.Attr("", "value"))
		}
	} else if _, ok := base.(linkedType); ok {
		// The base of the linked type is unknown, try to parse dates and decimals
		d, err := time.Parse("2006-01-02", el.Attr("", "value"))
		if err != nil {
			d, err := time.Parse(time.RFC3339, el.Attr("", "value"))
			if err != nil {
				decimal = parseDecimal(el.Attr("", "value"))
			}
			date = d
		}
		date = d
	} else {
		decimal = parseDecimal(el.Attr("", "value"))
	}
	return date, decimal
}

// XML Schema defines its own flavor of regular expressions here:
//
// http://www.w3.org/TR/xmlschema-0/#regexAppendix
//
// For now, they are similar enough to RE2 expressions that we will
// just try and compile them as RE2 expressions. If anyone wants to
// transpile XML Schema patterns to RE2 expressions, be my guest :)
func parsePattern(pat string) (*regexp.Regexp, error) {
	return regexp.Compile(pat)
}

// Resolve all linkedTypes in a schema, so that all types are based
// on a SimpleType, ComplexType, or a Builtin. Also resolve the types
// of all Attributes and Elements.
func (s *Schema) resolvePartialTypes(types map[xml.Name]Type) error {
	for name, t := range s.Types {
		var (
			ref linkedType
			ok  bool
		)
		switch t := t.(type) {
		case Builtin:
			continue
		case *ComplexType:
			if t.Base != nil {
				ref, ok = t.Base.(linkedType)
				if ok {
					base, ok := s.lookupType(ref, types)
					if !ok {
						return fmt.Errorf("complexType %s: could not find base type %s in namespace %s",
							name.Local, ref.Local, ref.Space)
					}
					t.Base = base
				}
			}

			for i, e := range t.Elements {
				ref, ok := e.Type.(linkedType)
				if !ok {
					continue
				}
				base, ok := s.lookupType(ref, types)
				if !ok {
					return fmt.Errorf("complexType %s: could not find type %q in namespace %s for element %s",
						name.Local, ref.Local, ref.Space, e.Name.Local)
				}
				e.Type = base
				t.Elements[i] = e
			}
			for i, a := range t.Attributes {
				ref, ok := a.Type.(linkedType)
				if !ok {
					continue
				}
				base, ok := s.lookupType(ref, types)
				if !ok {
					return fmt.Errorf("complexType %s: could not find type %s in namespace %s for attribute %s",
						name.Local, ref.Local, ref.Space, a.Name.Local)
				}
				a.Type = base
				t.Attributes[i] = a
			}
		case *SimpleType:
			if t.Base != nil {
				ref, ok = t.Base.(linkedType)
				if ok {
					base, ok := s.lookupType(ref, types)
					if !ok {
						return fmt.Errorf("simpleType %s: could not find base type %s in namespace %s",
							name.Local, ref.Local, ref.Space)
					}
					t.Base = base
				}
			}

			for i, u := range t.Union {
				ref, ok := u.(linkedType)
				if !ok {
					continue
				}
				real, ok := s.lookupType(ref, types)
				if !ok {
					return fmt.Errorf("simpleType %s: could not find union memberType %s in namespace %s",
						name.Local, ref.Local, ref.Space)
				}
				t.Union[i] = real
			}
		default:
			// This should never happen, the parse function should only add
			// *SimpleType or *ComplexType to the Types map.
			panic(fmt.Sprintf("Unexpected type %s (%T) in Schema.Types map", name.Local, t))
		}
	}
	return nil
}

func (s *Schema) lookupType(name linkedType, ext map[xml.Name]Type) (Type, bool) {
	if b, err := ParseBuiltin(xml.Name(name)); err == nil {
		return b, true
	}
	if v, ok := ext[xml.Name(name)]; ok {
		return v, true
	}
	v, ok := s.Types[xml.Name(name)]
	return v, ok
}


text:
Entreprise

{{entreprise.nom}}

            {{entreprise.type}}

                fingerprint
                {{entreprise.domaine}}

                home
                {{entreprise.site_web}}

                supervisor_account
                {{entreprise.nb_employes}} Employés

                euro_symbol
                {{entreprise.chiffre_d_affaires}} €

Sites

Contacts

        Statistiques

                    work Stages

                    group Entretiens

                  <canvas baseChart
                          [datasets]="radarChartData"
                          [labels]="radarChartLabels"
                          [chartType]="radarChartType"
                          (chartHover)="chartHovered($event)"
                          (chartClick)="chartClicked($event)"></canvas>

                <input id="input-3" name="input-3" class="rating rating-loading" value="3.5" data-show-clear="false" data-show-caption="false" data-readonly="true" data-size="sm">

                    ST20

                    ST40

                    ST50

                    ST20

                    ST40

                    ST50

{{getNoteGenerale(stage)}}

                                account_circle {{stage.etudiant_id.nom}} {{stage.etudiant_id.prenom}}

                        {{stage.commentaire_recommendation}}

{{getNoteGenerale(stage)}}

                                account_circle {{stage.etudiant_id.nom}} {{stage.etudiant_id.prenom}}

                        {{stage.commentaire_recommendation}}

{{getNoteGenerale(stage)}}

                                account_circle {{stage.etudiant_id.nom}} {{stage.etudiant_id.prenom}}

                        {{stage.commentaire_recommendation}}

                  <canvas id="canvasDoughnut"></canvas>

                  <canvas id="lineChart" width="50" height="50"></canvas>

                <input id="input-4" name="input-4" class="rating rating-loading" value="1" data-show-clear="false" data-show-caption="false" data-readonly="true" data-size="sm">

                    ST20

                    ST40

                    ST50

                    ST20

                    ST40

                    ST50

{{getNoteGeneraleEntretien(entretien)}}

                                account_circle {{entretien.etudiant_id.nom}} {{entretien.etudiant_id.prenom}}

                              {{entretien.deroulement}}

{{getNoteGeneraleEntretien(entretien)}}

                                account_circle {{entretien.etudiant_id.nom}} {{entretien.etudiant_id.prenom}}

                        {{entretien.deroulement}}

{{getNoteGeneraleEntretien(entretien)}}

                                account_circle {{entretien.etudiant_id.nom}} {{entretien.etudiant_id.prenom}}

                        {{entretien.deroulement}}

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            clear
          </button>

Informations complémentaires sur le stage

{{stage.etudiant_id.nom}} {{stage.etudiant_id.prenom}}

                  {{stage.etudiant_id.branche}}
                  {{stage.etudiant_id.filiere}}

                      Appréciations du stage

                        Note Générale

{{getNoteGenerale(stage)}}

                        Dirigeants

{{stage.dirigeants}}

                        Structure et organisation

{{stage.structure_organisation}}

                        Integration

{{stage.integration_cdt_travail}}

                        Rémunération

{{stage.remuneration_aventages}}

                        Opportunités

{{stage.opportunites_carriere}}

                      Stage {{stage.type_stage}}

                      Sujet

                    {{stage.sujet}}

                      Sem.

                    {{stage.semestre}}

                      Tuteur

                    {{stage.tuteur}}

                      Salaire

                    {{stage.remuneration}} €

                      Commentaires & recommandations

                    {{stage.commentaire_recommendation}}

                      Documents

                    Rapport de stage
                    insert_drive_file

                    Soutenance de stage
                    insert_drive_file

            <button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Fermer</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            clear
          </button>

Informations complémentaires sur le stage

{{stage.etudiant_id.nom}} {{stage.etudiant_id.prenom}}

                  {{stage.etudiant_id.branche}}
                  {{stage.etudiant_id.filiere}}

                      Appréciations du stage

                        Note Générale

{{getNoteGenerale(stage)}}

                        Dirigeants

{{stage.dirigeants}}

                        Structure et organisation

{{stage.structure_organisation}}

                        Integration

{{stage.integration_cdt_travail}}

                        Rémunération

{{stage.remuneration_aventages}}

                        Opportunités

{{stage.opportunites_carriere}}

                      Stage {{stage.type_stage}}

                      Sujet

                    {{stage.sujet}}

                      Sem.

                    {{stage.semestre}}

                      Tuteur

                    {{stage.tuteur}}

                      Salaire

                    {{stage.remuneration}} €

                      Commentaires & recommandations

                    {{stage.commentaire_recommendation}}

                      Documents

                    Rapport de stage
                    insert_drive_file

                    Soutenance de stage
                    insert_drive_file

            <button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Fermer</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            clear
          </button>

Informations complémentaires sur le stage

{{stage.etudiant_id.nom}} {{stage.etudiant_id.prenom}}

                  {{stage.etudiant_id.branche}}
                  {{stage.etudiant_id.filiere}}

                      Appréciations du stage

                        Note Générale

{{getNoteGenerale(stage)}}

                        Dirigeants

{{stage.dirigeants}}

                        Structure et organisation

{{stage.structure_organisation}}

                        Integration

{{stage.integration_cdt_travail}}

                        Rémunération

{{stage.remuneration_aventages}}

                        Opportunités

{{stage.opportunites_carriere}}

                      Stage {{stage.type_stage}}

                      Sujet

                    {{stage.sujet}}

                      Sem.

                    {{stage.semestre}}

                      Tuteur

                    {{stage.tuteur}}

                      Salaire

                    {{stage.remuneration}} €

                      Commentaires & recommandations

                    {{stage.commentaire_recommendation}}

                      Documents

                    Rapport de stage
                    insert_drive_file

                    Soutenance de stage
                    insert_drive_file

            <button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Fermer</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            clear
          </button>

Informations complémentaires sur l'entretien

{{entretien.etudiant_id.nom}} {{entretien.etudiant_id.nom}}

                  {{entretien.etudiant_id.branche}}
                  {{entretien.etudiant_id.filiere}}

                      Appréciations de l'entretien

                        Note Générale

{{getNoteGeneraleEntretien(entretien)}}

                        Difficulté

{{entretien.difficultee}}

                        Expérience personnelle

{{entretien.appreciation}}

                      Déroulement de l'entretien

                    {{entretien.deroulement}}

                    Résultats

                      Proposition de stage

                      done

                      clear

                      Proposition acceptée

                      done

                      clear

                      Documents

                    Curriculum Vitae
                    insert_drive_file

                    Lettre de motivation
                    insert_drive_file

            <button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Fermer</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            clear
          </button>

Informations complémentaires sur l'entretien

{{entretien.etudiant_id.nom}} {{entretien.etudiant_id.nom}}

                  {{entretien.etudiant_id.branche}}
                  {{entretien.etudiant_id.filiere}}

                      Appréciations de l'entretien

                        Note Générale

{{getNoteGeneraleEntretien(entretien)}}

                        Difficulté

{{entretien.difficultee}}

                        Expérience personnelle

{{entretien.appreciation}}

                      Déroulement de l'entretien

                    {{entretien.deroulement}}

                    Résultats

                      Proposition de stage

                      done

                      clear

                      Proposition acceptée

                      done

                      clear

                      Documents

                    Curriculum Vitae
                    insert_drive_file

                    Lettre de motivation
                    insert_drive_file

            <button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Fermer</button>

            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            clear
          </button>

Informations complémentaires sur l'entretien

{{entretien.etudiant_id.nom}} {{entretien.etudiant_id.nom}}

                  {{entretien.etudiant_id.branche}}
                  {{entretien.etudiant_id.filiere}}

                      Appréciations de l'entretien

                        Note Générale

{{getNoteGeneraleEntretien(entretien)}}

                        Difficulté

{{entretien.difficultee}}

                        Expérience personnelle

{{entretien.appreciation}}

                      Déroulement de l'entretien

                    {{entretien.deroulement}}

                    Résultats

                      Proposition de stage

                      done

                      clear

                      Proposition acceptée

                      done

                      clear

                      Documents

                    Curriculum Vitae
                    insert_drive_file

                    Lettre de motivation
                    insert_drive_file

            <button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Fermer</button>

redpajama_set_name: RedPajamaGithub


text:
using namespace v8::internal;
using namespace v8::internal::compiler;

// TODO(titzer): generate a large set of deterministic inputs for these tests.
class TyperTest : public TypedGraphTest {
 public:
  TyperTest()
      : TypedGraphTest(3),
        types_(zone(), isolate(), random_number_generator()),
        javascript_(zone()) {
    context_node_ = graph()->NewNode(common()->Parameter(2), graph()->start());
    rng_ = random_number_generator();

    integers.push_back(0);
    integers.push_back(0);
    integers.push_back(-1);
    integers.push_back(+1);
    integers.push_back(-V8_INFINITY);
    integers.push_back(+V8_INFINITY);
    for (int i = 0; i < 5; ++i) {
      double x = rng_->NextInt();
      integers.push_back(x);
      x *= rng_->NextInt();
      if (!IsMinusZero(x)) integers.push_back(x);
    }

    int32s.push_back(0);
    int32s.push_back(0);
    int32s.push_back(-1);
    int32s.push_back(+1);
    int32s.push_back(kMinInt);
    int32s.push_back(kMaxInt);
    for (int i = 0; i < 10; ++i) {
      int32s.push_back(rng_->NextInt());
    }
  }

  Types<Type, Type*, Zone> types_;
  JSOperatorBuilder javascript_;
  Node* context_node_;
  v8::base::RandomNumberGenerator* rng_;
  std::vector<double> integers;
  std::vector<double> int32s;

  Type* TypeBinaryOp(const Operator* op, Type* lhs, Type* rhs) {
    Node* p0 = Parameter(0);
    Node* p1 = Parameter(1);
    NodeProperties::SetBounds(p0, Bounds(lhs));
    NodeProperties::SetBounds(p1, Bounds(rhs));
    Node* n = graph()->NewNode(op, p0, p1, context_node_, graph()->start(),
                               graph()->start());
    return NodeProperties::GetBounds(n).upper;
  }

  Type* RandomRange(bool int32 = false) {
    std::vector<double>& numbers = int32 ? int32s : integers;
    double i = numbers[rng_->NextInt(static_cast<int>(numbers.size()))];
    double j = numbers[rng_->NextInt(static_cast<int>(numbers.size()))];
    return NewRange(i, j);
  }

  Type* NewRange(double i, double j) {
    if (i > j) std::swap(i, j);
    return Type::Range(i, j, zone());
  }

  double RandomInt(double min, double max) {
    switch (rng_->NextInt(4)) {
      case 0:
        return min;
      case 1:
        return max;
      default:
        break;
    }
    if (min == +V8_INFINITY) return +V8_INFINITY;
    if (max == -V8_INFINITY) return -V8_INFINITY;
    if (min == -V8_INFINITY && max == +V8_INFINITY) {
      return rng_->NextInt() * static_cast<double>(rng_->NextInt());
    }
    double result = nearbyint(min + (max - min) * rng_->NextDouble());
    if (IsMinusZero(result)) return 0;
    if (std::isnan(result)) return rng_->NextInt(2) ? min : max;
    DCHECK(min <= result && result <= max);
    return result;
  }

  double RandomInt(Type::RangeType* range) {
    return RandomInt(range->Min(), range->Max());
  }

  // Careful, this function runs O(max_width^5) trials.
  template <class BinaryFunction>
  void TestBinaryArithOpCloseToZero(const Operator* op, BinaryFunction opfun,
                                    int max_width) {
    const int min_min = -2 - max_width / 2;
    const int max_min = 2 + max_width / 2;
    for (int width = 0; width < max_width; width++) {
      for (int lmin = min_min; lmin <= max_min; lmin++) {
        for (int rmin = min_min; rmin <= max_min; rmin++) {
          Type* r1 = NewRange(lmin, lmin + width);
          Type* r2 = NewRange(rmin, rmin + width);
          Type* expected_type = TypeBinaryOp(op, r1, r2);

          for (int x1 = lmin; x1 < lmin + width; x1++) {
            for (int x2 = rmin; x2 < rmin + width; x2++) {
              double result_value = opfun(x1, x2);
              Type* result_type = Type::Constant(
                  isolate()->factory()->NewNumber(result_value), zone());
              EXPECT_TRUE(result_type->Is(expected_type));
            }
          }
        }
      }
    }
  }

  template <class BinaryFunction>
  void TestBinaryArithOp(const Operator* op, BinaryFunction opfun) {
    TestBinaryArithOpCloseToZero(op, opfun, 8);
    for (int i = 0; i < 100; ++i) {
      Type::RangeType* r1 = RandomRange()->AsRange();
      Type::RangeType* r2 = RandomRange()->AsRange();
      Type* expected_type = TypeBinaryOp(op, r1, r2);
      for (int i = 0; i < 10; i++) {
        double x1 = RandomInt(r1);
        double x2 = RandomInt(r2);
        double result_value = opfun(x1, x2);
        Type* result_type = Type::Constant(
            isolate()->factory()->NewNumber(result_value), zone());
        EXPECT_TRUE(result_type->Is(expected_type));
      }
    }
  }

  template <class BinaryFunction>
  void TestBinaryCompareOp(const Operator* op, BinaryFunction opfun) {
    for (int i = 0; i < 100; ++i) {
      Type::RangeType* r1 = RandomRange()->AsRange();
      Type::RangeType* r2 = RandomRange()->AsRange();
      Type* expected_type = TypeBinaryOp(op, r1, r2);
      for (int i = 0; i < 10; i++) {
        double x1 = RandomInt(r1);
        double x2 = RandomInt(r2);
        bool result_value = opfun(x1, x2);
        Type* result_type =
            Type::Constant(result_value ? isolate()->factory()->true_value()
                                        : isolate()->factory()->false_value(),
                           zone());
        EXPECT_TRUE(result_type->Is(expected_type));
      }
    }
  }

  template <class BinaryFunction>
  void TestBinaryBitOp(const Operator* op, BinaryFunction opfun) {
    for (int i = 0; i < 100; ++i) {
      Type::RangeType* r1 = RandomRange(true)->AsRange();
      Type::RangeType* r2 = RandomRange(true)->AsRange();
      Type* expected_type = TypeBinaryOp(op, r1, r2);
      for (int i = 0; i < 10; i++) {
        int32_t x1 = static_cast<int32_t>(RandomInt(r1));
        int32_t x2 = static_cast<int32_t>(RandomInt(r2));
        double result_value = opfun(x1, x2);
        Type* result_type = Type::Constant(
            isolate()->factory()->NewNumber(result_value), zone());
        EXPECT_TRUE(result_type->Is(expected_type));
      }
    }
  }

  Type* RandomSubtype(Type* type) {
    Type* subtype;
    do {
      subtype = types_.Fuzz();
    } while (!subtype->Is(type));
    return subtype;
  }

  void TestBinaryMonotonicity(const Operator* op) {
    for (int i = 0; i < 50; ++i) {
      Type* type1 = types_.Fuzz();
      Type* type2 = types_.Fuzz();
      Type* type = TypeBinaryOp(op, type1, type2);
      Type* subtype1 = RandomSubtype(type1);
      ;
      Type* subtype2 = RandomSubtype(type2);
      ;
      Type* subtype = TypeBinaryOp(op, subtype1, subtype2);
      EXPECT_TRUE(subtype->Is(type));
    }
  }
};

namespace {

int32_t shift_left(int32_t x, int32_t y) { return x << y; }
int32_t shift_right(int32_t x, int32_t y) { return x >> y; }
int32_t bit_or(int32_t x, int32_t y) { return x | y; }
int32_t bit_and(int32_t x, int32_t y) { return x & y; }
int32_t bit_xor(int32_t x, int32_t y) { return x ^ y; }

}  // namespace

//------------------------------------------------------------------------------
// Soundness
//   For simplicity, we currently only test soundness on expression operators
//   that have a direct equivalent in C++.  Also, testing is currently limited
//   to ranges as input types.

TEST_F(TyperTest, TypeJSAdd) {
  TestBinaryArithOp(javascript_.Add(), std::plus<double>());
}

TEST_F(TyperTest, TypeJSSubtract) {
  TestBinaryArithOp(javascript_.Subtract(), std::minus<double>());
}

TEST_F(TyperTest, TypeJSMultiply) {
  TestBinaryArithOp(javascript_.Multiply(), std::multiplies<double>());
}

TEST_F(TyperTest, TypeJSDivide) {
  TestBinaryArithOp(javascript_.Divide(), std::divides<double>());
}

TEST_F(TyperTest, TypeJSModulus) {
  TestBinaryArithOp(javascript_.Modulus(), modulo);
}

TEST_F(TyperTest, TypeJSBitwiseOr) {
  TestBinaryBitOp(javascript_.BitwiseOr(), bit_or);
}

TEST_F(TyperTest, TypeJSBitwiseAnd) {
  TestBinaryBitOp(javascript_.BitwiseAnd(), bit_and);
}

TEST_F(TyperTest, TypeJSBitwiseXor) {
  TestBinaryBitOp(javascript_.BitwiseXor(), bit_xor);
}

TEST_F(TyperTest, TypeJSShiftLeft) {
  TestBinaryBitOp(javascript_.ShiftLeft(), shift_left);
}

TEST_F(TyperTest, TypeJSShiftRight) {
  TestBinaryBitOp(javascript_.ShiftRight(), shift_right);
}

TEST_F(TyperTest, TypeJSLessThan) {
  TestBinaryCompareOp(javascript_.LessThan(), std::less<double>());
}

TEST_F(TyperTest, TypeJSLessThanOrEqual) {
  TestBinaryCompareOp(javascript_.LessThanOrEqual(), std::less_equal<double>());
}

TEST_F(TyperTest, TypeJSGreaterThan) {
  TestBinaryCompareOp(javascript_.GreaterThan(), std::greater<double>());
}

TEST_F(TyperTest, TypeJSGreaterThanOrEqual) {
  TestBinaryCompareOp(javascript_.GreaterThanOrEqual(),
                      std::greater_equal<double>());
}

TEST_F(TyperTest, TypeJSEqual) {
  TestBinaryCompareOp(javascript_.Equal(), std::equal_to<double>());
}

TEST_F(TyperTest, TypeJSNotEqual) {
  TestBinaryCompareOp(javascript_.NotEqual(), std::not_equal_to<double>());
}

// For numbers there's no difference between strict and non-strict equality.
TEST_F(TyperTest, TypeJSStrictEqual) {
  TestBinaryCompareOp(javascript_.StrictEqual(), std::equal_to<double>());
}

TEST_F(TyperTest, TypeJSStrictNotEqual) {
  TestBinaryCompareOp(javascript_.StrictNotEqual(),
                      std::not_equal_to<double>());
}

//------------------------------------------------------------------------------
// Monotonicity

// List should be in sync with JS_SIMPLE_BINOP_LIST.
#define JSBINOP_LIST(V) \
  V(Equal)              \
  V(NotEqual)           \
  V(StrictEqual)        \
  V(StrictNotEqual)     \
  V(LessThan)           \
  V(GreaterThan)        \
  V(LessThanOrEqual)    \
  V(GreaterThanOrEqual) \
  V(BitwiseOr)          \
  V(BitwiseXor)         \
  V(BitwiseAnd)         \
  V(ShiftLeft)          \
  V(ShiftRight)         \
  V(ShiftRightLogical)  \
  V(Add)                \
  V(Subtract)           \
  V(Multiply)           \
  V(Divide)             \
  V(Modulus)

#define TEST_FUNC(name)                         \
  TEST_F(TyperTest, Monotonicity_##name) {      \
    TestBinaryMonotonicity(javascript_.name()); \
  }
JSBINOP_LIST(TEST_FUNC)
#undef TEST_FUNC

//------------------------------------------------------------------------------
// Regression tests

TEST_F(TyperTest, TypeRegressInt32Constant) {
  int values[] = {-5, 10};
  for (auto i : values) {
    Node* c = graph()->NewNode(common()->Int32Constant(i));
    Type* type = NodeProperties::GetBounds(c).upper;
    EXPECT_TRUE(type->Is(NewRange(i, i)));
  }
}


text:
package render

import (
	"bytes"
	"fmt"
	"github.com/apache/thrift/lib/go/thrift"
)

// (needed to ensure safety because of naive import list construction.)
var _ = thrift.ZERO
var _ = fmt.Printf
var _ = bytes.Equal

type RenderService interface {
	Ping() (r string, err error)
	// Parameters:
	//  - Tplname
	//  - KeyMap
	RenderTpl(tplname string, keyMap map[string]string) (r string, err error)
}

type RenderServiceClient struct {
	Transport       thrift.TTransport
	ProtocolFactory thrift.TProtocolFactory
	InputProtocol   thrift.TProtocol
	OutputProtocol  thrift.TProtocol
	SeqId           int32
}

func NewRenderServiceClientFactory(t thrift.TTransport, f thrift.TProtocolFactory) *RenderServiceClient {
	return &RenderServiceClient{Transport: t,
		ProtocolFactory: f,
		InputProtocol:   f.GetProtocol(t),
		OutputProtocol:  f.GetProtocol(t),
		SeqId:           0,
	}
}

func NewRenderServiceClientProtocol(t thrift.TTransport, iprot thrift.TProtocol, oprot thrift.TProtocol) *RenderServiceClient {
	return &RenderServiceClient{Transport: t,
		ProtocolFactory: nil,
		InputProtocol:   iprot,
		OutputProtocol:  oprot,
		SeqId:           0,
	}
}

func (p *RenderServiceClient) Ping() (r string, err error) {
	if err = p.sendPing(); err != nil {
		return
	}
	return p.recvPing()
}

func (p *RenderServiceClient) sendPing() (err error) {
	oprot := p.OutputProtocol
	if oprot == nil {
		oprot = p.ProtocolFactory.GetProtocol(p.Transport)
		p.OutputProtocol = oprot
	}
	p.SeqId++
	if err = oprot.WriteMessageBegin("Ping", thrift.CALL, p.SeqId); err != nil {
		return
	}
	args := RenderServicePingArgs{}
	if err = args.Write(oprot); err != nil {
		return
	}
	if err = oprot.WriteMessageEnd(); err != nil {
		return
	}
	return oprot.Flush()
}

func (p *RenderServiceClient) recvPing() (value string, err error) {
	iprot := p.InputProtocol
	if iprot == nil {
		iprot = p.ProtocolFactory.GetProtocol(p.Transport)
		p.InputProtocol = iprot
	}
	method, mTypeId, seqId, err := iprot.ReadMessageBegin()
	if err != nil {
		return
	}
	if method != "Ping" {
		err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "Ping failed: wrong method name")
		return
	}
	if p.SeqId != seqId {
		err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "Ping failed: out of sequence response")
		return
	}
	if mTypeId == thrift.EXCEPTION {
		error0 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception")
		var error1 error
		error1, err = error0.Read(iprot)
		if err != nil {
			return
		}
		if err = iprot.ReadMessageEnd(); err != nil {
			return
		}
		err = error1
		return
	}
	if mTypeId != thrift.REPLY {
		err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "Ping failed: invalid message type")
		return
	}
	result := RenderServicePingResult{}
	if err = result.Read(iprot); err != nil {
		return
	}
	if err = iprot.ReadMessageEnd(); err != nil {
		return
	}
	value = result.GetSuccess()
	return
}

// Parameters:
//  - Tplname
//  - KeyMap
func (p *RenderServiceClient) RenderTpl(tplname string, keyMap map[string]string) (r string, err error) {
	if err = p.sendRenderTpl(tplname, keyMap); err != nil {
		return
	}
	return p.recvRenderTpl()
}

func (p *RenderServiceClient) sendRenderTpl(tplname string, keyMap map[string]string) (err error) {
	oprot := p.OutputProtocol
	if oprot == nil {
		oprot = p.ProtocolFactory.GetProtocol(p.Transport)
		p.OutputProtocol = oprot
	}
	p.SeqId++
	if err = oprot.WriteMessageBegin("RenderTpl", thrift.CALL, p.SeqId); err != nil {
		return
	}
	args := RenderServiceRenderTplArgs{
		Tplname: tplname,
		KeyMap:  keyMap,
	}
	if err = args.Write(oprot); err != nil {
		return
	}
	if err = oprot.WriteMessageEnd(); err != nil {
		return
	}
	return oprot.Flush()
}

func (p *RenderServiceClient) recvRenderTpl() (value string, err error) {
	iprot := p.InputProtocol
	if iprot == nil {
		iprot = p.ProtocolFactory.GetProtocol(p.Transport)
		p.InputProtocol = iprot
	}
	method, mTypeId, seqId, err := iprot.ReadMessageBegin()
	if err != nil {
		return
	}
	if method != "RenderTpl" {
		err = thrift.NewTApplicationException(thrift.WRONG_METHOD_NAME, "RenderTpl failed: wrong method name")
		return
	}
	if p.SeqId != seqId {
		err = thrift.NewTApplicationException(thrift.BAD_SEQUENCE_ID, "RenderTpl failed: out of sequence response")
		return
	}
	if mTypeId == thrift.EXCEPTION {
		error2 := thrift.NewTApplicationException(thrift.UNKNOWN_APPLICATION_EXCEPTION, "Unknown Exception")
		var error3 error
		error3, err = error2.Read(iprot)
		if err != nil {
			return
		}
		if err = iprot.ReadMessageEnd(); err != nil {
			return
		}
		err = error3
		return
	}
	if mTypeId != thrift.REPLY {
		err = thrift.NewTApplicationException(thrift.INVALID_MESSAGE_TYPE_EXCEPTION, "RenderTpl failed: invalid message type")
		return
	}
	result := RenderServiceRenderTplResult{}
	if err = result.Read(iprot); err != nil {
		return
	}
	if err = iprot.ReadMessageEnd(); err != nil {
		return
	}
	value = result.GetSuccess()
	return
}

type RenderServiceProcessor struct {
	processorMap map[string]thrift.TProcessorFunction
	handler      RenderService
}

func (p *RenderServiceProcessor) AddToProcessorMap(key string, processor thrift.TProcessorFunction) {
	p.processorMap[key] = processor
}

func (p *RenderServiceProcessor) GetProcessorFunction(key string) (processor thrift.TProcessorFunction, ok bool) {
	processor, ok = p.processorMap[key]
	return processor, ok
}

func (p *RenderServiceProcessor) ProcessorMap() map[string]thrift.TProcessorFunction {
	return p.processorMap
}

func NewRenderServiceProcessor(handler RenderService) *RenderServiceProcessor {

	self4 := &RenderServiceProcessor{handler: handler, processorMap: make(map[string]thrift.TProcessorFunction)}
	self4.processorMap["Ping"] = &renderServiceProcessorPing{handler: handler}
	self4.processorMap["RenderTpl"] = &renderServiceProcessorRenderTpl{handler: handler}
	return self4
}

func (p *RenderServiceProcessor) Process(iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
	name, _, seqId, err := iprot.ReadMessageBegin()
	if err != nil {
		return false, err
	}
	if processor, ok := p.GetProcessorFunction(name); ok {
		return processor.Process(seqId, iprot, oprot)
	}
	iprot.Skip(thrift.STRUCT)
	iprot.ReadMessageEnd()
	x5 := thrift.NewTApplicationException(thrift.UNKNOWN_METHOD, "Unknown function "+name)
	oprot.WriteMessageBegin(name, thrift.EXCEPTION, seqId)
	x5.Write(oprot)
	oprot.WriteMessageEnd()
	oprot.Flush()
	return false, x5

}

type renderServiceProcessorPing struct {
	handler RenderService
}

func (p *renderServiceProcessorPing) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
	args := RenderServicePingArgs{}
	if err = args.Read(iprot); err != nil {
		iprot.ReadMessageEnd()
		x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
		oprot.WriteMessageBegin("Ping", thrift.EXCEPTION, seqId)
		x.Write(oprot)
		oprot.WriteMessageEnd()
		oprot.Flush()
		return false, err
	}

	iprot.ReadMessageEnd()
	result := RenderServicePingResult{}
	var retval string
	var err2 error
	if retval, err2 = p.handler.Ping(); err2 != nil {
		x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing Ping: "+err2.Error())
		oprot.WriteMessageBegin("Ping", thrift.EXCEPTION, seqId)
		x.Write(oprot)
		oprot.WriteMessageEnd()
		oprot.Flush()
		return true, err2
	} else {
		result.Success = &retval
	}
	if err2 = oprot.WriteMessageBegin("Ping", thrift.REPLY, seqId); err2 != nil {
		err = err2
	}
	if err2 = result.Write(oprot); err == nil && err2 != nil {
		err = err2
	}
	if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
		err = err2
	}
	if err2 = oprot.Flush(); err == nil && err2 != nil {
		err = err2
	}
	if err != nil {
		return
	}
	return true, err
}

type renderServiceProcessorRenderTpl struct {
	handler RenderService
}

func (p *renderServiceProcessorRenderTpl) Process(seqId int32, iprot, oprot thrift.TProtocol) (success bool, err thrift.TException) {
	args := RenderServiceRenderTplArgs{}
	if err = args.Read(iprot); err != nil {
		iprot.ReadMessageEnd()
		x := thrift.NewTApplicationException(thrift.PROTOCOL_ERROR, err.Error())
		oprot.WriteMessageBegin("RenderTpl", thrift.EXCEPTION, seqId)
		x.Write(oprot)
		oprot.WriteMessageEnd()
		oprot.Flush()
		return false, err
	}

	iprot.ReadMessageEnd()
	result := RenderServiceRenderTplResult{}
	var retval string
	var err2 error
	if retval, err2 = p.handler.RenderTpl(args.Tplname, args.KeyMap); err2 != nil {
		x := thrift.NewTApplicationException(thrift.INTERNAL_ERROR, "Internal error processing RenderTpl: "+err2.Error())
		oprot.WriteMessageBegin("RenderTpl", thrift.EXCEPTION, seqId)
		x.Write(oprot)
		oprot.WriteMessageEnd()
		oprot.Flush()
		return true, err2
	} else {
		result.Success = &retval
	}
	if err2 = oprot.WriteMessageBegin("RenderTpl", thrift.REPLY, seqId); err2 != nil {
		err = err2
	}
	if err2 = result.Write(oprot); err == nil && err2 != nil {
		err = err2
	}
	if err2 = oprot.WriteMessageEnd(); err == nil && err2 != nil {
		err = err2
	}
	if err2 = oprot.Flush(); err == nil && err2 != nil {
		err = err2
	}
	if err != nil {
		return
	}
	return true, err
}

// HELPER FUNCTIONS AND STRUCTURES

type RenderServicePingArgs struct {
}

func NewRenderServicePingArgs() *RenderServicePingArgs {
	return &RenderServicePingArgs{}
}

func (p *RenderServicePingArgs) Read(iprot thrift.TProtocol) error {
	if _, err := iprot.ReadStructBegin(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
	}

	for {
		_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
		if err != nil {
			return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
		}
		if fieldTypeId == thrift.STOP {
			break
		}
		if err := iprot.Skip(fieldTypeId); err != nil {
			return err
		}
		if err := iprot.ReadFieldEnd(); err != nil {
			return err
		}
	}
	if err := iprot.ReadStructEnd(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
	}
	return nil
}

func (p *RenderServicePingArgs) Write(oprot thrift.TProtocol) error {
	if err := oprot.WriteStructBegin("Ping_args"); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
	}
	if err := oprot.WriteFieldStop(); err != nil {
		return thrift.PrependError("write field stop error: ", err)
	}
	if err := oprot.WriteStructEnd(); err != nil {
		return thrift.PrependError("write struct stop error: ", err)
	}
	return nil
}

func (p *RenderServicePingArgs) String() string {
	if p == nil {
		return "<nil>"
	}
	return fmt.Sprintf("RenderServicePingArgs(%+v)", *p)
}

// Attributes:
//  - Success
type RenderServicePingResult struct {
	Success *string `thrift:"success,0" json:"success,omitempty"`
}

func NewRenderServicePingResult() *RenderServicePingResult {
	return &RenderServicePingResult{}
}

var RenderServicePingResult_Success_DEFAULT string

func (p *RenderServicePingResult) GetSuccess() string {
	if !p.IsSetSuccess() {
		return RenderServicePingResult_Success_DEFAULT
	}
	return *p.Success
}
func (p *RenderServicePingResult) IsSetSuccess() bool {
	return p.Success != nil
}

func (p *RenderServicePingResult) Read(iprot thrift.TProtocol) error {
	if _, err := iprot.ReadStructBegin(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
	}

	for {
		_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
		if err != nil {
			return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
		}
		if fieldTypeId == thrift.STOP {
			break
		}
		switch fieldId {
		case 0:
			if err := p.readField0(iprot); err != nil {
				return err
			}
		default:
			if err := iprot.Skip(fieldTypeId); err != nil {
				return err
			}
		}
		if err := iprot.ReadFieldEnd(); err != nil {
			return err
		}
	}
	if err := iprot.ReadStructEnd(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
	}
	return nil
}

func (p *RenderServicePingResult) readField0(iprot thrift.TProtocol) error {
	if v, err := iprot.ReadString(); err != nil {
		return thrift.PrependError("error reading field 0: ", err)
	} else {
		p.Success = &v
	}
	return nil
}

func (p *RenderServicePingResult) Write(oprot thrift.TProtocol) error {
	if err := oprot.WriteStructBegin("Ping_result"); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
	}
	if err := p.writeField0(oprot); err != nil {
		return err
	}
	if err := oprot.WriteFieldStop(); err != nil {
		return thrift.PrependError("write field stop error: ", err)
	}
	if err := oprot.WriteStructEnd(); err != nil {
		return thrift.PrependError("write struct stop error: ", err)
	}
	return nil
}

func (p *RenderServicePingResult) writeField0(oprot thrift.TProtocol) (err error) {
	if p.IsSetSuccess() {
		if err := oprot.WriteFieldBegin("success", thrift.STRING, 0); err != nil {
			return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err)
		}
		if err := oprot.WriteString(string(*p.Success)); err != nil {
			return thrift.PrependError(fmt.Sprintf("%T.success (0) field write error: ", p), err)
		}
		if err := oprot.WriteFieldEnd(); err != nil {
			return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err)
		}
	}
	return err
}

func (p *RenderServicePingResult) String() string {
	if p == nil {
		return "<nil>"
	}
	return fmt.Sprintf("RenderServicePingResult(%+v)", *p)
}

// Attributes:
//  - Tplname
//  - KeyMap
type RenderServiceRenderTplArgs struct {
	Tplname string            `thrift:"tplname,1" json:"tplname"`
	KeyMap  map[string]string `thrift:"keyMap,2" json:"keyMap"`
}

func NewRenderServiceRenderTplArgs() *RenderServiceRenderTplArgs {
	return &RenderServiceRenderTplArgs{}
}

func (p *RenderServiceRenderTplArgs) GetTplname() string {
	return p.Tplname
}

func (p *RenderServiceRenderTplArgs) GetKeyMap() map[string]string {
	return p.KeyMap
}
func (p *RenderServiceRenderTplArgs) Read(iprot thrift.TProtocol) error {
	if _, err := iprot.ReadStructBegin(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
	}

	for {
		_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
		if err != nil {
			return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
		}
		if fieldTypeId == thrift.STOP {
			break
		}
		switch fieldId {
		case 1:
			if err := p.readField1(iprot); err != nil {
				return err
			}
		case 2:
			if err := p.readField2(iprot); err != nil {
				return err
			}
		default:
			if err := iprot.Skip(fieldTypeId); err != nil {
				return err
			}
		}
		if err := iprot.ReadFieldEnd(); err != nil {
			return err
		}
	}
	if err := iprot.ReadStructEnd(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
	}
	return nil
}

func (p *RenderServiceRenderTplArgs) readField1(iprot thrift.TProtocol) error {
	if v, err := iprot.ReadString(); err != nil {
		return thrift.PrependError("error reading field 1: ", err)
	} else {
		p.Tplname = v
	}
	return nil
}

func (p *RenderServiceRenderTplArgs) readField2(iprot thrift.TProtocol) error {
	_, _, size, err := iprot.ReadMapBegin()
	if err != nil {
		return thrift.PrependError("error reading map begin: ", err)
	}
	tMap := make(map[string]string, size)
	p.KeyMap = tMap
	for i := 0; i < size; i++ {
		var _key6 string
		if v, err := iprot.ReadString(); err != nil {
			return thrift.PrependError("error reading field 0: ", err)
		} else {
			_key6 = v
		}
		var _val7 string
		if v, err := iprot.ReadString(); err != nil {
			return thrift.PrependError("error reading field 0: ", err)
		} else {
			_val7 = v
		}
		p.KeyMap[_key6] = _val7
	}
	if err := iprot.ReadMapEnd(); err != nil {
		return thrift.PrependError("error reading map end: ", err)
	}
	return nil
}

func (p *RenderServiceRenderTplArgs) Write(oprot thrift.TProtocol) error {
	if err := oprot.WriteStructBegin("RenderTpl_args"); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
	}
	if err := p.writeField1(oprot); err != nil {
		return err
	}
	if err := p.writeField2(oprot); err != nil {
		return err
	}
	if err := oprot.WriteFieldStop(); err != nil {
		return thrift.PrependError("write field stop error: ", err)
	}
	if err := oprot.WriteStructEnd(); err != nil {
		return thrift.PrependError("write struct stop error: ", err)
	}
	return nil
}

func (p *RenderServiceRenderTplArgs) writeField1(oprot thrift.TProtocol) (err error) {
	if err := oprot.WriteFieldBegin("tplname", thrift.STRING, 1); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T write field begin error 1:tplname: ", p), err)
	}
	if err := oprot.WriteString(string(p.Tplname)); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T.tplname (1) field write error: ", p), err)
	}
	if err := oprot.WriteFieldEnd(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T write field end error 1:tplname: ", p), err)
	}
	return err
}

func (p *RenderServiceRenderTplArgs) writeField2(oprot thrift.TProtocol) (err error) {
	if err := oprot.WriteFieldBegin("keyMap", thrift.MAP, 2); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T write field begin error 2:keyMap: ", p), err)
	}
	if err := oprot.WriteMapBegin(thrift.STRING, thrift.STRING, len(p.KeyMap)); err != nil {
		return thrift.PrependError("error writing map begin: ", err)
	}
	for k, v := range p.KeyMap {
		if err := oprot.WriteString(string(k)); err != nil {
			return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err)
		}
		if err := oprot.WriteString(string(v)); err != nil {
			return thrift.PrependError(fmt.Sprintf("%T. (0) field write error: ", p), err)
		}
	}
	if err := oprot.WriteMapEnd(); err != nil {
		return thrift.PrependError("error writing map end: ", err)
	}
	if err := oprot.WriteFieldEnd(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T write field end error 2:keyMap: ", p), err)
	}
	return err
}

func (p *RenderServiceRenderTplArgs) String() string {
	if p == nil {
		return "<nil>"
	}
	return fmt.Sprintf("RenderServiceRenderTplArgs(%+v)", *p)
}

// Attributes:
//  - Success
type RenderServiceRenderTplResult struct {
	Success *string `thrift:"success,0" json:"success,omitempty"`
}

func NewRenderServiceRenderTplResult() *RenderServiceRenderTplResult {
	return &RenderServiceRenderTplResult{}
}

var RenderServiceRenderTplResult_Success_DEFAULT string

func (p *RenderServiceRenderTplResult) GetSuccess() string {
	if !p.IsSetSuccess() {
		return RenderServiceRenderTplResult_Success_DEFAULT
	}
	return *p.Success
}
func (p *RenderServiceRenderTplResult) IsSetSuccess() bool {
	return p.Success != nil
}

func (p *RenderServiceRenderTplResult) Read(iprot thrift.TProtocol) error {
	if _, err := iprot.ReadStructBegin(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T read error: ", p), err)
	}

	for {
		_, fieldTypeId, fieldId, err := iprot.ReadFieldBegin()
		if err != nil {
			return thrift.PrependError(fmt.Sprintf("%T field %d read error: ", p, fieldId), err)
		}
		if fieldTypeId == thrift.STOP {
			break
		}
		switch fieldId {
		case 0:
			if err := p.readField0(iprot); err != nil {
				return err
			}
		default:
			if err := iprot.Skip(fieldTypeId); err != nil {
				return err
			}
		}
		if err := iprot.ReadFieldEnd(); err != nil {
			return err
		}
	}
	if err := iprot.ReadStructEnd(); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T read struct end error: ", p), err)
	}
	return nil
}

func (p *RenderServiceRenderTplResult) readField0(iprot thrift.TProtocol) error {
	if v, err := iprot.ReadString(); err != nil {
		return thrift.PrependError("error reading field 0: ", err)
	} else {
		p.Success = &v
	}
	return nil
}

func (p *RenderServiceRenderTplResult) Write(oprot thrift.TProtocol) error {
	if err := oprot.WriteStructBegin("RenderTpl_result"); err != nil {
		return thrift.PrependError(fmt.Sprintf("%T write struct begin error: ", p), err)
	}
	if err := p.writeField0(oprot); err != nil {
		return err
	}
	if err := oprot.WriteFieldStop(); err != nil {
		return thrift.PrependError("write field stop error: ", err)
	}
	if err := oprot.WriteStructEnd(); err != nil {
		return thrift.PrependError("write struct stop error: ", err)
	}
	return nil
}

func (p *RenderServiceRenderTplResult) writeField0(oprot thrift.TProtocol) (err error) {
	if p.IsSetSuccess() {
		if err := oprot.WriteFieldBegin("success", thrift.STRING, 0); err != nil {
			return thrift.PrependError(fmt.Sprintf("%T write field begin error 0:success: ", p), err)
		}
		if err := oprot.WriteString(string(*p.Success)); err != nil {
			return thrift.PrependError(fmt.Sprintf("%T.success (0) field write error: ", p), err)
		}
		if err := oprot.WriteFieldEnd(); err != nil {
			return thrift.PrependError(fmt.Sprintf("%T write field end error 0:success: ", p), err)
		}
	}
	return err
}

func (p *RenderServiceRenderTplResult) String() string {
	if p == nil {
		return "<nil>"
	}
	return fmt.Sprintf("RenderServiceRenderTplResult(%+v)", *p)
}


text:
@implementation MainViewCell

+ (instancetype)cellWithTableView:(UITableView *)tableView {

    static NSString *ID = @"SDEleSignatureCell";

    MainViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {

        cell = [[MainViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];

        cell.selectedBackgroundView = [[UIImageView alloc] initWithImage:[UIImage imageWithBgColor:[UIColor whiteColor]]];

        cell.textLabel.textColor = ZLRGB(39, 39, 39);
        cell.textLabel.font = [UIFont systemFontOfSize:28 * SCALE];
    }
    return cell;

}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{

    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {

    }

    return self;
}

#pragma mark - 设置数据
- (void)setItem:(NSDictionary *)item{

    self.textLabel.text = item[@"title"];

}

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end


text:
IBM MQ is used by businesses to build scalable architectures.It is largely queue-based and capable of transporting any form of data as messages. It enables the delivery of secure messages across a wide range of computing platforms, online services, communication networks, and applications. With IBM MQ, you can monitor and manage the flow of messages and data.

Hence using our plugin, technician can monitor the performance  attributes of IBM MQ Objects like queue manager, channels and queues while also enabling easy alerting, health check would help  reduce risk of downtime within your IBM MQ infrastructure.

## Prerequisites

- Download and install the latest version of the [Site24x7 Linux agent] (https://www.site24x7.com/app/client#/admin/inventory/add-monitor) in the server where you plan to run the plugin.

- Install pymqi module for python
```
  pip install pymqi
```
---

### Plugin Installation

- Create a directory named "ibm_mq_monitoring" under the Site24x7 Linux Agent plugin directory:

		Linux             ->   /opt/site24x7/monagent/plugins/ibm_mq_monitoring

- Download all the files in the "ibm_mq_monitoring" folder and place it under the "ibm_mq_monitoring" directory.

		wget https://raw.githubusercontent.com/site24x7/plugins/master/ibm_mq_monitoring/ibm_mq_monitoring.py
		wget https://raw.githubusercontent.com/site24x7/plugins/master/ibm_mq_monitoring/ibm_mq_monitoring.cfg

- Execute the following command in your server to install pymqi:

		pip install pymqi

- Execute the below command with appropriate arguments to check for the valid json output:
```
 python3 ibm_mq_monitoring.py --queue_manager_name=<name of the queue manager> --channel_name=<channel name> --queue_name=<queue_name> --host=<host name> --port=<port number>  --username=<optional - username> --password=<optional - password>
 ```
Since it's a python plugin, to run in windows server please follow the steps in below link, remaining configuration steps are exactly the same.

  https://support.site24x7.com/portal/en/kb/articles/run-python-plugin-scripts-in-windows-servers

---

### Configurations

- Provide your IBM MQ configurations in ibm_mq_monitoring.cfg file.
```
    [ibm_mq]
    queue_manager_name=<QUEUE MANAGER NAME>
    channel_name=<CHANNEL NAME>
    queue_name = <QUEUE NAME>
    host=<HOST NAME>
    port = <PORT NUMBER>
    username=<IBM MQ USERNAME>
    password = <IBM MQ PASSWORD>
```

The agent will automatically execute the plugin within five minutes and send performance data to the Site24x7 data center.

## Supported Metrics
The following metrics are captured in the IBM MQ monitoring plugin, which has been categorized under the following entities of IBM WebSphere MQ.

- Queue Manager Metrics
- Queue Metrics
- Channel Metrics

### **Queue Manager Metrics**

- #### Connection_count
     The number of connections to the queue manager.

- #### Status
     The status of the queue manager.

### **Queue Metrics**

- #### Queue Name
     The name of the queue.

- #### High Queue Depth
     The maximum number of messages on the queue since the queue statistics were last reset.

- #### Msg Dequeue Count
     The number of messages removed from the queue since the queue statistics were last reset.

- #### Msg Enqueue Count
     The number of messages enqueued, i.e., the number of messages put on the queue since the queue statistics were last reset.

- #### Current Queue Depth
     The current number of messages on the queue.

- #### Handles Open (Input Count)
     The number of handles that are currently open for input for the queue.

- #### Handles Open (Output Count)
     The number of handles that are currently open for output for the queue.

- #### Last Msg get Date
     The date of the last message successfully read from the queue.

- #### Last Msg get Time
     The time of the last message successfully read from the queue.

- #### Last Msg put Date
     The date of the last message successfully put to the queue.

- #### Last Msg put Time
     The time of the last message successfully put to the queue.

- #### Oldest Msg Age
     The age of the oldest message on the queue.

- #### No. of Uncommitted Msgs
     The number of uncommitted messages on the queue.

### **Channel Metrics**

- #### Channel Name
     The name of the channel name.

- #### Channel Connection Name
     The number of connections described in the summary.

- #### Channel Status
     The current status of the client.

- #### No. of MQI calls
     The number of messages sent or received.

- #### Bytes Sent
     The number of bytes sent.

- #### Bytes Received
     The number of bytes received.

- #### Buffers Sent
     The number of buffers sent.

- #### Buffers Received
     The number of buffers received.

- #### Channel Substate
     The current action being performed by the channel.

- #### Channel Start Date
     The date when the channel started.

- #### Channel Start Time
     The time when the channel started.


text:
#region License
// The MIT License (MIT)
//
// Copyright (c) 2016 João Simões
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
namespace SimpleSOAPClient.Models.Headers
{
    using System;
    using Microsoft;
    using Oasis.Security;

    /// <summary>
    /// Class with known <see cref="SoapHeader"/> builder methods.
    /// </summary>
    public static class KnownHeader
    {
        /// <summary>
        /// Class with Microsoft specific <see cref="SoapHeader"/> builder methods.
        /// </summary>
        public static class Microsoft
        {
            /// <summary>
            /// Creates a new Microsoft Action SOAP Header.
            /// </summary>
            /// <param name="action">The action for the header</param>
            /// <param name="mustUnderstand">Does the server must understand the header?</param>
            /// <returns>The new <see cref="ActionSoapHeader"/></returns>
            public static ActionSoapHeader Action(string action, bool mustUnderstand = true)
            {
                return new ActionSoapHeader
                {
                    Action = action,
                    MustUnderstand = mustUnderstand ? 1 : 0
                };
            }

            /// <summary>
            /// Creates a new Microsoft To SOAP Header.
            /// </summary>
            /// <param name="to">The action for the header</param>
            /// <param name="mustUnderstand">Does the server must understand the header?</param>
            /// <returns>The new <see cref="ToSoapHeader"/></returns>
            public static ToSoapHeader To(string to, bool mustUnderstand = true)
            {
                return new ToSoapHeader
                {
                    To = to,
                    MustUnderstand = mustUnderstand ? 1 : 0
                };
            }
        }

        /// <summary>
        /// Class with Oasis specific <see cref="SoapHeader"/> builder methods.
        /// </summary>
        public static class Oasis
        {
            /// <summary>
            /// Class with Oasis Security specific <see cref="SoapHeader"/> builder methods.
            /// </summary>
            public static class Security
            {
                /// <summary>
                /// Creates a new Oasis Security Username Token with password text SOAP header.
                /// </summary>
                /// <param name="username">The username</param>
                /// <param name="password">The password</param>
                /// <param name="mustUnderstand">Does the server must understand the header?</param>
                /// <returns>The new <see cref="UsernameTokenAndPasswordTextSoapHeader"/></returns>
                public static UsernameTokenAndPasswordTextSoapHeader UsernameTokenAndPasswordText(
                    string username, string password, bool mustUnderstand = true)
                {
                    var randomId = Guid.NewGuid().ToString("N");

                    return new UsernameTokenAndPasswordTextSoapHeader
                    {
                        Timestamp = new Timestamp
                        {
                            Id = string.Concat("_TS", randomId),
                            Created = DateTime.UtcNow,
                            Expires = DateTime.UtcNow.AddMinutes(15)
                        },
                        UsernameToken = new UsernameTokenWithPasswordText
                        {
                            Id = string.Concat("_UT", randomId),
                            Username = username,
                            Password = new UsernameTokenPasswordText
                            {
                                Value = password
                            }
                        },
                        MustUnderstand = mustUnderstand ? 1 : 0
                    };
                }
            }
        }
    }
}


text:
<?php

require_once 'Inquisition/admin/components/Option/Edit.php';
require_once 'CME/admin/components/Option/include/CMEOptionHelper.php';

class CMEOptionEdit extends InquisitionOptionEdit
{
	// {{{ protected properties

	/**
	 * @var CMEOptionHelper
	 */
	protected $helper;

	// }}}

	// init phase
	// {{{ protected function initInternal()

	protected function initInternal()
	{
		parent::initInternal();

		$this->helper = $this->getOptionHelper();
		$this->helper->initInternal();
	}

	// }}}
	// {{{ protected function getOptionHelper()

	protected function getOptionHelper()
	{
		$question_helper = new CMEQuestionHelper(
			$this->app,
			$this->inquisition
		);

		return new CMEOptionHelper(
			$this->app,
			$question_helper,
			$this->question
		);
	}

	// }}}

	// build phase
	// {{{ protected function buildNavBar()

	protected function buildNavBar()
	{
		parent::buildNavBar();

		// put add/edit title entry at the end
		$title = $this->navbar->popEntry();

		// Add dummy entry. The CMEOptionHelper will remove this. All other
		// option admin components have a details component in the nav bar.
		if ($this->isNew()) {
			$this->navbar->createEntry('');
		}

		$this->helper->buildNavBar($this->navbar);

		// remove dummy entry.
		if ($this->isNew()) {
			$this->navbar->popEntry();
		}

		$this->navbar->addEntry($title);
	}

	// }}}
}

?>


text:
// -----------------------------------------------------------------------
// <copyright file="CanonicalDeliveryDataFixture.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Linq;

using DynamicAllocation;

using DynamicAllocationActivities;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;

namespace DynamicAllocationActivitiesUnitTests
{
    ///
    /// Test fixture for CanonicalDeliverData class
    ///
    [TestClass]
    public class CanonicalDeliveryDataFixture
    {
        /// Test default construction.
        [TestMethod]
        public void DefaultConstruction()
        {
            var canonicalDeliveryData = new CanonicalDeliveryData();
            Assert.AreEqual(0, canonicalDeliveryData.DeliveryDataForNetwork.Count);
            Assert.AreEqual(DeliveryNetworkDesignation.Unknown, canonicalDeliveryData.Network);
            Assert.AreEqual(CanonicalDeliveryData.MinimumDeliveryDate, canonicalDeliveryData.LatestDeliveryReportDate);
            Assert.AreEqual(CanonicalDeliveryData.MinimumDeliveryDate, canonicalDeliveryData.LatestDeliveryDataDate);
            Assert.AreEqual(CanonicalDeliveryData.MaximumDeliveryDate, canonicalDeliveryData.EarliestDeliveryDataDate);
            Assert.AreEqual(CanonicalDeliveryData.MaximumDeliveryDate, canonicalDeliveryData.EarliestDeliveryReportDate);
        }

        /// Test non-default construction.
        [TestMethod]
        public void NonDefaultConstruction()
        {
            var canonicalDeliveryData = new CanonicalDeliveryData(DeliveryNetworkDesignation.AppNexus);
            Assert.AreEqual(0, canonicalDeliveryData.DeliveryDataForNetwork.Count);
            Assert.AreEqual(DeliveryNetworkDesignation.AppNexus, canonicalDeliveryData.Network);
            Assert.AreEqual(CanonicalDeliveryData.MinimumDeliveryDate, canonicalDeliveryData.LatestDeliveryReportDate);
            Assert.AreEqual(CanonicalDeliveryData.MinimumDeliveryDate, canonicalDeliveryData.LatestDeliveryDataDate);
            Assert.AreEqual(CanonicalDeliveryData.MaximumDeliveryDate, canonicalDeliveryData.EarliestDeliveryDataDate);
            Assert.AreEqual(CanonicalDeliveryData.MaximumDeliveryDate, canonicalDeliveryData.EarliestDeliveryReportDate);
        }

        /// Test we can parse overlapping raw delivery data into unique canonical delivery data.
        [TestMethod]
        public void AddRawDataOverlapping()
        {
            var expectedReportDate = DateTime.UtcNow;
            var canonicalDeliveryData = new CanonicalDeliveryData();
            var result = this.AddRawDataToCanonicalDeliveryData(
                    new[] { "Resources.ApnxDeliveryDataA.csv", "Resources.ApnxDeliveryDataB.csv" },
                    expectedReportDate,
                    ref canonicalDeliveryData);

            // There should be 9 unique records out of 12 overlapping records in the raw csv's
            Assert.IsTrue(result);
            Assert.AreEqual(9, canonicalDeliveryData.DeliveryDataForNetwork.Count);
            Assert.AreEqual("2012-03-16T23:00:00.0000000Z", canonicalDeliveryData.LatestDeliveryDataDate.ToString("o"));
            Assert.AreEqual("2012-03-15T19:00:00.0000000Z", canonicalDeliveryData.EarliestDeliveryDataDate.ToString("o"));
            Assert.AreEqual(expectedReportDate, canonicalDeliveryData.LatestDeliveryReportDate);
        }

        /// Test we return false on parse failure.
        [TestMethod]
        public void AddRawDataFailParse()
        {
            // Setup raw delivery data with a rogue header
            var rawDeliveryDataList = new[]
            {
                "campaign_id,hour,campaign_code,imps,ecpm,spend,clicks\r\nNOTANID,2012-03-16 15:00,00000000000000000000000000000001,1,1,1,1"
            };

            var expectedReportDate = DateTime.UtcNow;
            var canonicalDeliveryData = new CanonicalDeliveryData();
            var result = this.AddRawDataToCanonicalDeliveryDataCsv(
                    rawDeliveryDataList,
                    expectedReportDate,
                    ref canonicalDeliveryData);

            Assert.IsFalse(result);
        }

        /// Test we are tolerant of zero-data raw reports.
        [TestMethod]
        public void AddRawDataEmptyDeliveryData()
        {
            // Setup raw delivery data with a rogue header
            var rawDeliveryDataList = new[]
            {
                "campaign_id,hour,campaign_code,imps,ecpm,spend,clicks\r\n",
                "campaign_id,hour,campaign_code,imps,ecpm,spend,clicks\r\n1234,2012-03-16 15:00,00000000000000000000000000000001,1,1,1,1"
            };

            var expectedReportDate = DateTime.UtcNow;
            var canonicalDeliveryData = new CanonicalDeliveryData();
            var result = this.AddRawDataToCanonicalDeliveryDataCsv(
                    rawDeliveryDataList,
                    expectedReportDate,
                    ref canonicalDeliveryData);

            Assert.IsTrue(result);
            Assert.AreEqual(1, canonicalDeliveryData.DeliveryDataForNetwork.Count);
        }

        /// Add raw delivery data from an array of resources to CanonicalDeliveryData.
        /// <param name="deliveryDataResources">The delivery data resources.</param>
        /// <param name="latestDeliveryReportDate">The latest delivery report date to use.</param>
        /// <param name="canonicalDeliveryData">CanonicalDeliveryData to update.</param>
        /// <returns>Result of AddRawData.</returns>
        private bool AddRawDataToCanonicalDeliveryData(
            string[] deliveryDataResources,
            DateTime latestDeliveryReportDate,
            ref CanonicalDeliveryData canonicalDeliveryData)
        {
            var rawDeliveryDataCsvs = deliveryDataResources.Select(r =>
                    EmbeddedResourceHelper.GetEmbeddedResourceAsString(typeof(GetCampaignDeliveryDataFixture), r))
                    .ToArray();

            return this.AddRawDataToCanonicalDeliveryDataCsv(
                rawDeliveryDataCsvs, latestDeliveryReportDate, ref canonicalDeliveryData);
        }

        /// Add raw csv delivery data from an array of raw data to CanonicalDeliveryData.
        /// <param name="deliveryData">The raw delivery data.</param>
        /// <param name="latestDeliveryReportDate">The latest delivery report date to use.</param>
        /// <param name="canonicalDeliveryData">CanonicalDeliveryData to update.</param>
        /// <returns>Result of AddRawData.</returns>
        private bool AddRawDataToCanonicalDeliveryDataCsv(
            string[] deliveryData,
            DateTime latestDeliveryReportDate,
            ref CanonicalDeliveryData canonicalDeliveryData)
        {
            var result = true;

            foreach (var rawDeliveryData in deliveryData)
            {
                result = result && canonicalDeliveryData.AddRawData(
                    rawDeliveryData, latestDeliveryReportDate, new ApnxReportCsvParser());
            }

            return result;
        }
    }
}


text:
git pull origin master
git pull origin gh-pages
git checkout gh-pages
git merge master
git push origin gh-pages
git checkout master


text:
/**
 *
 */

function Home() {
}
	Home.prototype = {
		urlCambiarPagina: "",
		urlAgregar:"",
		urlEliminar:"",
		idCompra: 0,
		init: function() {
			this.setupEvents();
		},
		parsearArrayArticulos: function(result) {
			 var string = "";
					for (var i=0; i<result.articulos.length;i++)
					{
						string = string + "
" +
						result.articulos[i].nombre +
						"	" + result.articulos[i].precio +
						"	Agregar" +
						"<input type='hidden' name='id' value='" +
						result.articulos[i].id + "'>
";
					}
					return string;
		},
		setupEvents: function() {
		var self = this;

					//EVENTOINICIO
					$("#primeraPagina").on("click",function(e) {
						e.preventDefault();

						//CATALOGO TBODY APPEND
						$.post(self.urlCambiarPagina,{pagina: 1})
						.done(function(result) {
							$("#Catalogo tbody tr").remove();
							$("#Catalogo tbody").append(self.parsearArrayArticulos(result));
						})
						.fail(function(result) {
							alert("Error en el servidor");
							return false;
						});
					});
					//EVENTOFIN
					$("#ultimaPagina").on("click",function(e) {
						e.preventDefault();

						//CATALOGO TBODY APPEND
						$.post(self.urlCambiarPagina,{pagina: $(this).attr("name")})
						.done(function(result) {
							$("#Catalogo tbody tr").remove();
							$("#Catalogo tbody").append(self.parsearArrayArticulos(result));
						})
						.fail(function(result) {
							alert("Error en el servidor");
							return false;
						});
					});

					//EVENTONUMEROS
					$(".pagina").on("click",function(e) {
					e.preventDefault();

					//CATALOGO TBODY APPEND
					$.post(self.urlCambiarPagina,{pagina: $(this).attr("id")})
					.done(function(result) {
						var result = result;
						$("#Catalogo tbody tr").remove();
						$("#Catalogo tbody").append(self.parsearArrayArticulos(result));
					})
					.fail(function(result) {
						alert("Error en el servidor");
						return false;
					});

			});

//	 			.agregar son los links

				// EVENTO PARA AGREGAR
					$("#Catalogo").on("click",".agregar", function(e) {
					e.preventDefault();
					cantidadSolicitada = prompt("Ingrese cantidad");
					$.post(self.urlAgregar,{cantidad: cantidadSolicitada, id:$(this).siblings().val(), idCompra: self.idCompra})
					.done(function(result) {
						precioAgregar = result.cantidad * result.precio;
						$(".total").remove();
						$("#Carrito tbody").append("
" +
						result.nombre +
						"	" +
						result.cantidad +
						"	" +
						precioAgregar +
						"	" +
						" Eliminar
" +
						"
" +
						result.total +
						"
") ;
					})
					.fail(function(result) {
						alert("Error en el servidor");
						return false;
					});
				});
	//EVENTO PARA ELIMINAR
				$("#Carrito").on("click",".eliminar", function(e) {
					e.preventDefault();
					$.post(self.urlEliminar,{ index:$(this).closest("tr").attr("id") })
					.done(function(result) {
					$(".total").remove();
					$("#" + result.index).remove();
					$("#Carrito tbody").append(
							"
" +
							result.total +
							"
") ;
					})
					.fail(function(result) {
						alert("Error en el servidor");
						return false;
					});
			});

	}
}


text:
package org.tiatus.dao;

import javax.persistence.EntityManager;
import javax.transaction.*;

/**
 * Created by johnreynolds on 25/06/2016.
 */
public class EntityUserTransaction implements UserTransaction {
    private EntityManager em;

    public EntityUserTransaction(EntityManager em) {
        this.em = em;
    }

    @Override
    public void begin() throws NotSupportedException, SystemException {
        if (em.getTransaction() == null) {
            throw new SystemException();
        }
        if (em.getTransaction().isActive()) {
            throw new NotSupportedException();
        }
        em.getTransaction().begin();
    }

    @Override
    public void commit() throws HeuristicMixedException, HeuristicRollbackException, IllegalStateException, RollbackException, SecurityException, SystemException {
        if (em.getTransaction() == null) {
            throw new SystemException();
        }
        em.getTransaction().commit();
    }

    @Override
    public int getStatus() throws SystemException {
        if (em.getTransaction() == null) {
            throw new SystemException();
        }
        if (em.getTransaction().isActive()) {
            return Status.STATUS_ACTIVE;
        } else {
            return Status.STATUS_NO_TRANSACTION;
        }
    }

    @Override
    public void rollback() throws IllegalStateException, SecurityException, SystemException {
        if (em.getTransaction() == null) {
            throw new SystemException();
        }
        em.getTransaction().rollback();
    }

    @Override
    public void setRollbackOnly() throws IllegalStateException, SystemException {
        if (em.getTransaction() == null) {
            throw new SystemException();
        }
        em.getTransaction().setRollbackOnly();
    }

    @Override
    public void setTransactionTimeout(int i) throws SystemException {
        throw new UnsupportedOperationException();
    }
}