text:
package format

import (
	"bytes"
	"fmt"
	"regexp"
	"sort"

	"github.com/open-policy-agent/opa/ast"
)

// defaultLocationFile is the file name used in `Ast()` for terms
// without a location, as could happen when pretty-printing the
// results of partial eval.
const defaultLocationFile = "__format_default__"

// Source formats a Rego source file. The bytes provided must describe a complete
// Rego module. If they don't, Source will return an error resulting from the attempt
// to parse the bytes.
func Source(filename string, src []byte) ([]byte, error) {
	module, err := ast.ParseModule(filename, string(src))
	if err != nil {
		return nil, err
	}
	formatted, err := Ast(module)
	if err != nil {
		return nil, fmt.Errorf("%s: %v", filename, err)
	}
	return formatted, nil
}

// MustAst is a helper function to format a Rego AST element. If any errors
// occurs this function will panic. This is mostly used for test
func MustAst(x interface{}) []byte {
	bs, err := Ast(x)
	if err != nil {
		panic(err)
	}
	return bs
}

// Ast formats a Rego AST element. If the passed value is not a valid AST
// element, Ast returns nil and an error. If AST nodes are missing locations
// an arbitrary location will be used.
func Ast(x interface{}) ([]byte, error) {

	// The node has to be deep copied because it may be mutated below. Alternatively,
	// we could avoid the copy by checking if mutation will occur first. For now,
	// since format is not latency sensitive, just deep copy in all cases.
	x = ast.Copy(x)

	wildcards := map[ast.Var]*ast.Term{}

	// NOTE(sr): When the formatter encounters a call to internal.member_2
	// or internal.member_3, it will sugarize them into usage of the `in`
	// operator. It has to ensure that the proper future keyword import is
	// present.
	extraFutureKeywordImports := map[string]bool{}

	// Preprocess the AST. Set any required defaults and calculate
	// values required for printing the formatted output.
	ast.WalkNodes(x, func(x ast.Node) bool {
		switch n := x.(type) {
		case ast.Body:
			if len(n) == 0 {
				return false
			}
		case *ast.Term:
			unmangleWildcardVar(wildcards, n)

		case *ast.Expr:
			switch {
			case n.IsCall() && ast.Member.Ref().Equal(n.Operator()) || ast.MemberWithKey.Ref().Equal(n.Operator()):
				extraFutureKeywordImports["in"] = true
			case n.IsEvery():
				extraFutureKeywordImports["every"] = true
			}
		}
		if x.Loc() == nil {
			x.SetLoc(defaultLocation(x))
		}
		return false
	})

	w := &writer{
		indent: "\t",
	}

	switch x := x.(type) {
	case *ast.Module:
		for kw := range extraFutureKeywordImports {
			x.Imports = ensureFutureKeywordImport(x.Imports, kw)
		}
		w.writeModule(x)
	case *ast.Package:
		w.writePackage(x, nil)
	case *ast.Import:
		w.writeImports([]*ast.Import{x}, nil)
	case *ast.Rule:
		w.writeRule(x, false, nil)
	case *ast.Head:
		w.writeHead(x, false, false, nil)
	case ast.Body:
		w.writeBody(x, nil)
	case *ast.Expr:
		w.writeExpr(x, nil)
	case *ast.With:
		w.writeWith(x, nil, false)
	case *ast.Term:
		w.writeTerm(x, nil)
	case ast.Value:
		w.writeTerm(&ast.Term{Value: x, Location: &ast.Location{}}, nil)
	case *ast.Comment:
		w.writeComments([]*ast.Comment{x})
	default:
		return nil, fmt.Errorf("not an ast element: %v", x)
	}

	return squashTrailingNewlines(w.buf.Bytes()), nil
}

func unmangleWildcardVar(wildcards map[ast.Var]*ast.Term, n *ast.Term) {

	v, ok := n.Value.(ast.Var)
	if !ok || !v.IsWildcard() {
		return
	}

	first, ok := wildcards[v]
	if !ok {
		wildcards[v] = n
		return
	}

	w := v[len(ast.WildcardPrefix):]

	// Prepend an underscore to ensure the variable will parse.
	if len(w) == 0 || w[0] != '_' {
		w = "_" + w
	}

	if first != nil {
		first.Value = w
		wildcards[v] = nil
	}

	n.Value = w
}

func squashTrailingNewlines(bs []byte) []byte {
	if bytes.HasSuffix(bs, []byte("\n")) {
		return append(bytes.TrimRight(bs, "\n"), '\n')
	}
	return bs
}

func defaultLocation(x ast.Node) *ast.Location {
	return ast.NewLocation([]byte(x.String()), defaultLocationFile, 1, 1)
}

type writer struct {
	buf bytes.Buffer

	indent    string
	level     int
	inline    bool
	beforeEnd *ast.Comment
	delay     bool
}

func (w *writer) writeModule(module *ast.Module) {
	var pkg *ast.Package
	var others []interface{}
	var comments []*ast.Comment
	visitor := ast.NewGenericVisitor(func(x interface{}) bool {
		switch x := x.(type) {
		case *ast.Comment:
			comments = append(comments, x)
			return true
		case *ast.Import, *ast.Rule:
			others = append(others, x)
			return true
		case *ast.Package:
			pkg = x
			return true
		default:
			return false
		}
	})
	visitor.Walk(module)

	sort.Slice(comments, func(i, j int) bool {
		return locLess(comments[i], comments[j])
	})

	// XXX: The parser currently duplicates comments for some reason, so we need
	// to remove duplicates here.
	comments = dedupComments(comments)
	sort.Slice(others, func(i, j int) bool {
		return locLess(others[i], others[j])
	})

	comments = w.writePackage(pkg, comments)
	var imports []*ast.Import
	var rules []*ast.Rule
	for len(others) > 0 {
		imports, others = gatherImports(others)
		comments = w.writeImports(imports, comments)
		rules, others = gatherRules(others)
		comments = w.writeRules(rules, comments)
	}

	for i, c := range comments {
		w.writeLine(c.String())
		if i == len(comments)-1 {
			w.write("\n")
		}
	}
}

func (w *writer) writePackage(pkg *ast.Package, comments []*ast.Comment) []*ast.Comment {
	comments = w.insertComments(comments, pkg.Location)

	w.startLine()
	w.write(pkg.String())
	w.blankLine()

	return comments
}

func (w *writer) writeComments(comments []*ast.Comment) {
	for i := 0; i < len(comments); i++ {
		if i > 0 && locCmp(comments[i], comments[i-1]) > 1 {
			w.blankLine()
		}
		w.writeLine(comments[i].String())
	}
}

func (w *writer) writeRules(rules []*ast.Rule, comments []*ast.Comment) []*ast.Comment {
	for _, rule := range rules {
		comments = w.insertComments(comments, rule.Location)
		comments = w.writeRule(rule, false, comments)
		w.blankLine()
	}
	return comments
}

func (w *writer) writeRule(rule *ast.Rule, isElse bool, comments []*ast.Comment) []*ast.Comment {
	if rule == nil {
		return comments
	}

	if !isElse {
		w.startLine()
	}

	if rule.Default {
		w.write("default ")
	}

	// OPA transforms lone bodies like `foo = {"a": "b"}` into rules of the form
	// `foo = {"a": "b"} { true }` in the AST. We want to preserve that notation
	// in the formatted code instead of expanding the bodies into rules, so we
	// pretend that the rule has no body in this case.
	isExpandedConst := rule.Body.Equal(ast.NewBody(ast.NewExpr(ast.BooleanTerm(true)))) && rule.Else == nil

	comments = w.writeHead(rule.Head, rule.Default, isExpandedConst, comments)

	if (len(rule.Body) == 0 || isExpandedConst) && !isElse {
		w.endLine()
		return comments
	}

	w.write(" {")
	w.endLine()
	w.up()

	comments = w.writeBody(rule.Body, comments)

	var closeLoc *ast.Location

	if len(rule.Head.Args) > 0 {
		closeLoc = closingLoc('(', ')', '{', '}', rule.Location)
	} else {
		closeLoc = closingLoc('[', ']', '{', '}', rule.Location)
	}

	comments = w.insertComments(comments, closeLoc)

	w.down()
	w.startLine()
	w.write("}")
	if rule.Else != nil {
		comments = w.writeElse(rule, comments)
	}
	return comments
}

func (w *writer) writeElse(rule *ast.Rule, comments []*ast.Comment) []*ast.Comment {
	// If there was nothing else on the line before the "else" starts
	// then preserve this style of else block, otherwise it will be
	// started as an "inline" else eg:
	//
	//     p {
	//     	...
	//     }
	//
	//     else {
	//     	...
	//     }
	//
	// versus
	//
	//     p {
	// 	    ...
	//     } else {
	//     	...
	//     }
	//
	// Note: This doesn't use the `close` as it currently isn't accurate for all
	// types of values. Checking the actual line text is the most consistent approach.
	wasInline := false
	ruleLines := bytes.Split(rule.Location.Text, []byte("\n"))
	relativeElseRow := rule.Else.Location.Row - rule.Location.Row
	if relativeElseRow > 0 && relativeElseRow < len(ruleLines) {
		elseLine := ruleLines[relativeElseRow]
		if !bytes.HasPrefix(bytes.TrimSpace(elseLine), []byte("else")) {
			wasInline = true
		}
	}

	// If there are any comments between the closing brace of the previous rule and the start
	// of the else block we will always insert a new blank line between them.
	hasCommentAbove := len(comments) > 0 && comments[0].Location.Row-rule.Else.Head.Location.Row < 0 || w.beforeEnd != nil

	if !hasCommentAbove && wasInline {
		w.write(" ")
	} else {
		w.blankLine()
		w.startLine()
	}

	rule.Else.Head.Name = "else"
	rule.Else.Head.Args = nil
	comments = w.insertComments(comments, rule.Else.Head.Location)

	if hasCommentAbove && !wasInline {
		// The comments would have ended the line, be sure to start one again
		// before writing the rest of the "else" rule.
		w.startLine()
	}

	// For backwards compatibility adjust the rule head value location
	// TODO: Refactor the logic for inserting comments, or special
	// case comments in a rule head value so this can be removed
	if rule.Else.Head.Value != nil {
		rule.Else.Head.Value.Location = rule.Else.Head.Location
	}

	return w.writeRule(rule.Else, true, comments)
}

func (w *writer) writeHead(head *ast.Head, isDefault bool, isExpandedConst bool, comments []*ast.Comment) []*ast.Comment {
	w.write(head.Name.String())
	if len(head.Args) > 0 {
		w.write("(")
		var args []interface{}
		for _, arg := range head.Args {
			args = append(args, arg)
		}
		comments = w.writeIterable(args, head.Location, closingLoc(0, 0, '(', ')', head.Location), comments, w.listWriter())
		w.write(")")
	}
	if head.Key != nil {
		w.write("[")
		comments = w.writeTerm(head.Key, comments)
		w.write("]")
	}
	if head.Value != nil && (head.Key != nil || ast.Compare(head.Value, ast.BooleanTerm(true)) != 0 || isExpandedConst || isDefault) {
		if head.Assign {
			w.write(" := ")
		} else {
			w.write(" = ")
		}
		comments = w.writeTerm(head.Value, comments)
	}
	return comments
}

func (w *writer) insertComments(comments []*ast.Comment, loc *ast.Location) []*ast.Comment {
	before, at, comments := partitionComments(comments, loc)
	w.writeComments(before)
	if len(before) > 0 && loc.Row-before[len(before)-1].Location.Row > 1 {
		w.blankLine()
	}

	w.beforeLineEnd(at)
	return comments
}

func (w *writer) writeBody(body ast.Body, comments []*ast.Comment) []*ast.Comment {
	comments = w.insertComments(comments, body.Loc())
	offset := 0
	for i, expr := range body {
		if i > 0 && expr.Location.Row-body[i-1].Location.Row-offset > 1 {
			w.blankLine()
		}
		w.startLine()

		comments = w.writeExpr(expr, comments)
		w.endLine()
	}
	return comments
}

func (w *writer) writeExpr(expr *ast.Expr, comments []*ast.Comment) []*ast.Comment {
	comments = w.insertComments(comments, expr.Location)
	if !w.inline {
		w.startLine()
	}

	if expr.Negated {
		w.write("not ")
	}

	switch t := expr.Terms.(type) {
	case *ast.SomeDecl:
		comments = w.writeSomeDecl(t, comments)
	case *ast.Every:
		comments = w.writeEvery(t, comments)
	case []*ast.Term:
		comments = w.writeFunctionCall(expr, comments)
	case *ast.Term:
		comments = w.writeTerm(t, comments)
	}

	var indented bool
	for i, with := range expr.With {
		if i > 0 && with.Location.Row-expr.With[i-1].Location.Row > 0 {
			if !indented {
				indented = true

				w.up()
				defer w.down()
			}
			w.endLine()
			w.startLine()
		}
		comments = w.writeWith(with, comments, indented)
	}

	return comments
}

func (w *writer) writeSomeDecl(decl *ast.SomeDecl, comments []*ast.Comment) []*ast.Comment {
	comments = w.insertComments(comments, decl.Location)
	w.write("some ")

	row := decl.Location.Row

	for i, term := range decl.Symbols {
		switch val := term.Value.(type) {
		case ast.Var:
			if term.Location.Row > row {
				w.endLine()
				w.startLine()
				w.write(w.indent)
				row = term.Location.Row
			} else if i > 0 {
				w.write(" ")
			}

			comments = w.writeTerm(term, comments)

			if i < len(decl.Symbols)-1 {
				w.write(",")
			}
		case ast.Call:
			comments = w.writeInOperator(false, val[1:], comments)
		}
	}

	return comments
}

func (w *writer) writeEvery(every *ast.Every, comments []*ast.Comment) []*ast.Comment {
	comments = w.insertComments(comments, every.Location)
	w.write("every ")
	if every.Key != nil {
		comments = w.writeTerm(every.Key, comments)
		w.write(", ")
	}
	comments = w.writeTerm(every.Value, comments)
	w.write(" in ")
	comments = w.writeTerm(every.Domain, comments)
	w.write(" {")
	comments = w.writeComprehensionBody('{', '}', every.Body, every.Loc(), every.Loc(), comments)

	if len(every.Body) == 1 &&
		every.Body[0].Location.Row == every.Location.Row {
		w.write(" ")
	}
	w.write("}")
	return comments
}

func (w *writer) writeFunctionCall(expr *ast.Expr, comments []*ast.Comment) []*ast.Comment {

	terms := expr.Terms.([]*ast.Term)
	operator := terms[0].Value.String()

	switch operator {
	case ast.Member.Name, ast.MemberWithKey.Name:
		return w.writeInOperator(false, terms[1:], comments)
	}

	bi, ok := ast.BuiltinMap[operator]
	if !ok || bi.Infix == "" {
		return w.writeFunctionCallPlain(terms, comments)
	}

	numDeclArgs := len(bi.Decl.Args())
	numCallArgs := len(terms) - 1

	switch numCallArgs {
	case numDeclArgs: // Print infix where result is unassigned (e.g., x != y)
		comments = w.writeTerm(terms[1], comments)
		w.write(" " + bi.Infix + " ")
		return w.writeTerm(terms[2], comments)

	case numDeclArgs + 1: // Print infix where result is assigned (e.g., z = x + y)
		comments = w.writeTerm(terms[3], comments)
		w.write(" " + ast.Equality.Infix + " ")
		comments = w.writeTerm(terms[1], comments)
		w.write(" " + bi.Infix + " ")
		comments = w.writeTerm(terms[2], comments)
		return comments
	}
	return w.writeFunctionCallPlain(terms, comments)
}

func (w *writer) writeFunctionCallPlain(terms []*ast.Term, comments []*ast.Comment) []*ast.Comment {
	w.write(terms[0].String() + "(")
	defer w.write(")")
	args := make([]interface{}, len(terms)-1)
	for i, t := range terms[1:] {
		args[i] = t
	}
	loc := terms[0].Location
	return w.writeIterable(args, loc, closingLoc(0, 0, '(', ')', loc), comments, w.listWriter())
}

func (w *writer) writeWith(with *ast.With, comments []*ast.Comment, indented bool) []*ast.Comment {
	comments = w.insertComments(comments, with.Location)
	if !indented {
		w.write(" ")
	}
	w.write("with ")
	comments = w.writeTerm(with.Target, comments)
	w.write(" as ")
	return w.writeTerm(with.Value, comments)
}

func (w *writer) writeTerm(term *ast.Term, comments []*ast.Comment) []*ast.Comment {
	return w.writeTermParens(false, term, comments)
}

func (w *writer) writeTermParens(parens bool, term *ast.Term, comments []*ast.Comment) []*ast.Comment {
	comments = w.insertComments(comments, term.Location)
	if !w.inline {
		w.startLine()
	}

	switch x := term.Value.(type) {
	case ast.Ref:
		w.writeRef(x)
	case ast.Object:
		comments = w.writeObject(x, term.Location, comments)
	case *ast.Array:
		comments = w.writeArray(x, term.Location, comments)
	case ast.Set:
		comments = w.writeSet(x, term.Location, comments)
	case *ast.ArrayComprehension:
		comments = w.writeArrayComprehension(x, term.Location, comments)
	case *ast.ObjectComprehension:
		comments = w.writeObjectComprehension(x, term.Location, comments)
	case *ast.SetComprehension:
		comments = w.writeSetComprehension(x, term.Location, comments)
	case ast.String:
		if term.Location.Text[0] == '`' {
			// To preserve raw strings, we need to output the original text,
			// not what x.String() would give us.
			w.write(string(term.Location.Text))
		} else {
			w.write(x.String())
		}
	case ast.Var:
		w.write(w.formatVar(x))
	case ast.Call:
		comments = w.writeCall(parens, x, comments)
	case fmt.Stringer:
		w.write(x.String())
	}

	if !w.inline {
		w.startLine()
	}
	return comments
}

func (w *writer) writeRef(x ast.Ref) {
	if len(x) > 0 {
		w.writeTerm(x[0], nil)
		path := x[1:]
		for _, t := range path {
			switch p := t.Value.(type) {
			case ast.String:
				w.writeRefStringPath(p)
			case ast.Var:
				w.writeBracketed(w.formatVar(p))
			default:
				w.write("[")
				w.writeTerm(t, nil)
				w.write("]")
			}
		}
	}
}

func (w *writer) writeBracketed(str string) {
	w.write("[" + str + "]")
}

var varRegexp = regexp.MustCompile("^[[:alpha:]_][[:alpha:][:digit:]_]*$")

func (w *writer) writeRefStringPath(s ast.String) {
	str := string(s)
	if varRegexp.MatchString(str) && !ast.IsKeyword(str) {
		w.write("." + str)
	} else {
		w.writeBracketed(s.String())
	}
}

func (w *writer) formatVar(v ast.Var) string {
	if v.IsWildcard() {
		return ast.Wildcard.String()
	}
	return v.String()
}

func (w *writer) writeCall(parens bool, x ast.Call, comments []*ast.Comment) []*ast.Comment {
	bi, ok := ast.BuiltinMap[x[0].String()]
	if !ok || bi.Infix == "" {
		return w.writeFunctionCallPlain(x, comments)
	}

	if bi.Infix == "in" {
		// NOTE(sr): `in` requires special handling, mirroring what happens in the parser,
		// since there can be one or two lhs arguments.
		return w.writeInOperator(true, x[1:], comments)
	}

	// TODO(tsandall): improve to consider precedence?
	if parens {
		w.write("(")
	}
	comments = w.writeTermParens(true, x[1], comments)
	w.write(" " + bi.Infix + " ")
	comments = w.writeTermParens(true, x[2], comments)
	if parens {
		w.write(")")
	}

	return comments
}

func (w *writer) writeInOperator(parens bool, operands []*ast.Term, comments []*ast.Comment) []*ast.Comment {
	kw := "in"
	switch len(operands) {
	case 2:
		comments = w.writeTermParens(true, operands[0], comments)
		w.write(" ")
		w.write(kw)
		w.write(" ")
		comments = w.writeTermParens(true, operands[1], comments)
	case 3:
		if parens {
			w.write("(")
			defer w.write(")")
		}
		comments = w.writeTermParens(true, operands[0], comments)
		w.write(", ")
		comments = w.writeTermParens(true, operands[1], comments)
		w.write(" ")
		w.write(kw)
		w.write(" ")
		comments = w.writeTermParens(true, operands[2], comments)
	}
	return comments
}

func (w *writer) writeObject(obj ast.Object, loc *ast.Location, comments []*ast.Comment) []*ast.Comment {
	w.write("{")
	defer w.write("}")

	var s []interface{}
	obj.Foreach(func(k, v *ast.Term) {
		s = append(s, ast.Item(k, v))
	})
	return w.writeIterable(s, loc, closingLoc(0, 0, '{', '}', loc), comments, w.objectWriter())
}

func (w *writer) writeArray(arr *ast.Array, loc *ast.Location, comments []*ast.Comment) []*ast.Comment {
	w.write("[")
	defer w.write("]")

	var s []interface{}
	arr.Foreach(func(t *ast.Term) {
		s = append(s, t)
	})
	return w.writeIterable(s, loc, closingLoc(0, 0, '[', ']', loc), comments, w.listWriter())
}

func (w *writer) writeSet(set ast.Set, loc *ast.Location, comments []*ast.Comment) []*ast.Comment {

	if set.Len() == 0 {
		w.write("set()")
		return w.insertComments(comments, closingLoc(0, 0, '(', ')', loc))
	}

	w.write("{")
	defer w.write("}")

	var s []interface{}
	set.Foreach(func(t *ast.Term) {
		s = append(s, t)
	})
	return w.writeIterable(s, loc, closingLoc(0, 0, '{', '}', loc), comments, w.listWriter())
}

func (w *writer) writeArrayComprehension(arr *ast.ArrayComprehension, loc *ast.Location, comments []*ast.Comment) []*ast.Comment {
	w.write("[")
	defer w.write("]")

	return w.writeComprehension('[', ']', arr.Term, arr.Body, loc, comments)
}

func (w *writer) writeSetComprehension(set *ast.SetComprehension, loc *ast.Location, comments []*ast.Comment) []*ast.Comment {
	w.write("{")
	defer w.write("}")

	return w.writeComprehension('{', '}', set.Term, set.Body, loc, comments)
}

func (w *writer) writeObjectComprehension(object *ast.ObjectComprehension, loc *ast.Location, comments []*ast.Comment) []*ast.Comment {
	w.write("{")
	defer w.write("}")

	object.Value.Location = object.Key.Location // Ensure the value is not written on the next line.
	if object.Key.Location.Row-loc.Row > 1 {
		w.endLine()
		w.startLine()
	}

	comments = w.writeTerm(object.Key, comments)
	w.write(": ")
	return w.writeComprehension('{', '}', object.Value, object.Body, loc, comments)
}

func (w *writer) writeComprehension(open, close byte, term *ast.Term, body ast.Body, loc *ast.Location, comments []*ast.Comment) []*ast.Comment {
	if term.Location.Row-loc.Row > 1 {
		w.endLine()
		w.startLine()
	}

	comments = w.writeTerm(term, comments)
	w.write(" |")

	return w.writeComprehensionBody(open, close, body, term.Location, loc, comments)
}

func (w *writer) writeComprehensionBody(open, close byte, body ast.Body, term, compr *ast.Location, comments []*ast.Comment) []*ast.Comment {
	var exprs []interface{}
	for _, expr := range body {
		exprs = append(exprs, expr)
	}
	lines := groupIterable(exprs, term)

	if body.Loc().Row-term.Row > 0 || len(lines) > 1 {
		w.endLine()
		w.up()
		defer w.startLine()
		defer w.down()

		comments = w.writeBody(body, comments)
	} else {
		w.write(" ")
		i := 0
		for ; i < len(body)-1; i++ {
			comments = w.writeExpr(body[i], comments)
			w.write("; ")
		}
		comments = w.writeExpr(body[i], comments)
	}

	return w.insertComments(comments, closingLoc(0, 0, open, close, compr))
}

func (w *writer) writeImports(imports []*ast.Import, comments []*ast.Comment) []*ast.Comment {
	m, comments := mapImportsToComments(imports, comments)

	groups := groupImports(imports)
	for _, group := range groups {
		comments = w.insertComments(comments, group[0].Loc())

		// Sort imports within a newline grouping.
		sort.Slice(group, func(i, j int) bool {
			a := group[i]
			b := group[j]
			return a.Compare(b) < 0
		})
		for _, i := range group {
			w.startLine()
			w.write(i.String())
			if c, ok := m[i]; ok {
				w.write(" " + c.String())
			}
			w.endLine()
		}
		w.blankLine()
	}

	return comments
}

type entryWriter func(interface{}, []*ast.Comment) []*ast.Comment

func (w *writer) writeIterable(elements []interface{}, last *ast.Location, close *ast.Location, comments []*ast.Comment, fn entryWriter) []*ast.Comment {
	lines := groupIterable(elements, last)
	if len(lines) > 1 {
		w.delayBeforeEnd()
		w.startMultilineSeq()
	}

	i := 0
	for ; i < len(lines)-1; i++ {
		comments = w.writeIterableLine(lines[i], comments, fn)
		w.write(",")

		w.endLine()
		w.startLine()
	}

	comments = w.writeIterableLine(lines[i], comments, fn)

	if len(lines) > 1 {
		w.write(",")
		w.endLine()
		comments = w.insertComments(comments, close)
		w.down()
		w.startLine()
	}

	return comments
}

func (w *writer) writeIterableLine(elements []interface{}, comments []*ast.Comment, fn entryWriter) []*ast.Comment {
	if len(elements) == 0 {
		return comments
	}

	i := 0
	for ; i < len(elements)-1; i++ {
		comments = fn(elements[i], comments)
		w.write(", ")
	}

	return fn(elements[i], comments)
}

func (w *writer) objectWriter() entryWriter {
	return func(x interface{}, comments []*ast.Comment) []*ast.Comment {
		entry := x.([2]*ast.Term)
		comments = w.writeTerm(entry[0], comments)
		w.write(": ")
		return w.writeTerm(entry[1], comments)
	}
}

func (w *writer) listWriter() entryWriter {
	return func(x interface{}, comments []*ast.Comment) []*ast.Comment {
		return w.writeTerm(x.(*ast.Term), comments)
	}
}

// groupIterable will group the `elements` slice into slices according to their
// location: anything on the same line will be put into a slice.
func groupIterable(elements []interface{}, last *ast.Location) [][]interface{} {
	// Generated vars occur in the AST when we're rendering the result of
	// partial evaluation in a bundle build with optimization.
	// Those variables, and wildcard variables have the "default location",
	// set in `Ast()`). That is no proper file location, and the grouping
	// based on source location will yield a bad result.
	// Another case is generated variables: they do have proper file locations,
	// but their row/col information may no longer match their AST location.
	// So, for generated variables, we also don't trust the location, but
	// keep them ungrouped.
	def := false // default location found?
	for _, elem := range elements {
		ast.WalkTerms(elem, func(t *ast.Term) bool {
			if t.Location.File == defaultLocationFile {
				def = true
				return true
			}
			return false
		})
		ast.WalkVars(elem, func(v ast.Var) bool {
			if v.IsGenerated() {
				def = true
				return true
			}
			return false
		})
		if def { // return as-is
			return [][]interface{}{elements}
		}
	}
	sort.Slice(elements, func(i, j int) bool {
		return locLess(elements[i], elements[j])
	})

	var lines [][]interface{}
	var cur []interface{}
	for i, t := range elements {
		elem := t
		loc := getLoc(elem)
		lineDiff := loc.Row - last.Row
		if lineDiff > 0 && i > 0 {
			lines = append(lines, cur)
			cur = nil
		}

		last = loc
		cur = append(cur, elem)
	}
	return append(lines, cur)
}

func mapImportsToComments(imports []*ast.Import, comments []*ast.Comment) (map[*ast.Import]*ast.Comment, []*ast.Comment) {
	var leftovers []*ast.Comment
	m := map[*ast.Import]*ast.Comment{}

	for _, c := range comments {
		matched := false
		for _, i := range imports {
			if c.Loc().Row == i.Loc().Row {
				m[i] = c
				matched = true
				break
			}
		}
		if !matched {
			leftovers = append(leftovers, c)
		}
	}

	return m, leftovers
}

func groupImports(imports []*ast.Import) [][]*ast.Import {
	switch len(imports) { // shortcuts
	case 0:
		return nil
	case 1:
		return [][]*ast.Import{imports}
	}
	// there are >=2 imports to group

	var groups [][]*ast.Import
	group := []*ast.Import{imports[0]}

	for _, i := range imports[1:] {
		last := group[len(group)-1]

		// nil-location imports have been sorted up to come first
		if i.Loc() != nil && last.Loc() != nil && // first import with a location, or
			i.Loc().Row-last.Loc().Row > 1 { // more than one row apart from previous import

			// start a new group
			groups = append(groups, group)
			group = []*ast.Import{}
		}
		group = append(group, i)
	}
	if len(group) > 0 {
		groups = append(groups, group)
	}

	return groups
}

func partitionComments(comments []*ast.Comment, l *ast.Location) (before []*ast.Comment, at *ast.Comment, after []*ast.Comment) {
	for _, c := range comments {
		switch cmp := c.Location.Row - l.Row; {
		case cmp < 0:
			before = append(before, c)
		case cmp > 0:
			after = append(after, c)
		case cmp == 0:
			at = c
		}
	}

	return before, at, after
}

func gatherImports(others []interface{}) (imports []*ast.Import, rest []interface{}) {
	i := 0
loop:
	for ; i < len(others); i++ {
		switch x := others[i].(type) {
		case *ast.Import:
			imports = append(imports, x)
		case *ast.Rule:
			break loop
		}
	}
	return imports, others[i:]
}

func gatherRules(others []interface{}) (rules []*ast.Rule, rest []interface{}) {
	i := 0
loop:
	for ; i < len(others); i++ {
		switch x := others[i].(type) {
		case *ast.Rule:
			rules = append(rules, x)
		case *ast.Import:
			break loop
		}
	}
	return rules, others[i:]
}

func locLess(a, b interface{}) bool {
	return locCmp(a, b) < 0
}

func locCmp(a, b interface{}) int {
	al := getLoc(a)
	bl := getLoc(b)
	switch {
	case al == nil && bl == nil:
		return 0
	case al == nil:
		return -1
	case bl == nil:
		return 1
	}

	if cmp := al.Row - bl.Row; cmp != 0 {
		return cmp

	}
	return al.Col - bl.Col
}

func getLoc(x interface{}) *ast.Location {
	switch x := x.(type) {
	case ast.Node: // *ast.Head, *ast.Expr, *ast.With, *ast.Term
		return x.Loc()
	case *ast.Location:
		return x
	case [2]*ast.Term: // Special case to allow for easy printing of objects.
		return x[0].Location
	default:
		panic("Not reached")
	}
}

func closingLoc(skipOpen, skipClose, open, close byte, loc *ast.Location) *ast.Location {
	i, offset := 0, 0

	// Skip past parens/brackets/braces in rule heads.
	if skipOpen > 0 {
		i, offset = skipPast(skipOpen, skipClose, loc)
	}

	for ; i < len(loc.Text) && loc.Text[i] != open; i++ {
	}

	if i >= len(loc.Text) {
		return &ast.Location{Row: -1}
	}

	state := 1
	for state > 0 {
		i++
		if i >= len(loc.Text) {
			return &ast.Location{Row: -1}
		}

		switch loc.Text[i] {
		case open:
			state++
		case close:
			state--
		case '\n':
			offset++
		}
	}

	return &ast.Location{Row: loc.Row + offset}
}

func skipPast(open, close byte, loc *ast.Location) (int, int) {
	i := 0
	for ; i < len(loc.Text) && loc.Text[i] != open; i++ {
	}

	state := 1
	offset := 0
	for state > 0 {
		i++
		if i >= len(loc.Text) {
			return i, offset
		}

		switch loc.Text[i] {
		case open:
			state++
		case close:
			state--
		case '\n':
			offset++
		}
	}

	return i, offset
}

func dedupComments(comments []*ast.Comment) []*ast.Comment {
	if len(comments) == 0 {
		return nil
	}

	filtered := []*ast.Comment{comments[0]}
	for i := 1; i < len(comments); i++ {
		if comments[i].Location.Equal(comments[i-1].Location) {
			continue
		}
		filtered = append(filtered, comments[i])
	}
	return filtered
}

// startLine begins a line with the current indentation level.
func (w *writer) startLine() {
	w.inline = true
	for i := 0; i < w.level; i++ {
		w.write(w.indent)
	}
}

// endLine ends a line with a newline.
func (w *writer) endLine() {
	w.inline = false
	if w.beforeEnd != nil && !w.delay {
		w.write(" " + w.beforeEnd.String())
		w.beforeEnd = nil
	}
	w.delay = false
	w.write("\n")
}

// beforeLineEnd registers a comment to be printed at the end of the current line.
func (w *writer) beforeLineEnd(c *ast.Comment) {
	if w.beforeEnd != nil {
		if c == nil {
			return
		}
		panic("overwriting non-nil beforeEnd")
	}
	w.beforeEnd = c
}

func (w *writer) delayBeforeEnd() {
	w.delay = true
}

// line prints a blank line. If the writer is currently in the middle of a line,
// line ends it and then prints a blank one.
func (w *writer) blankLine() {
	if w.inline {
		w.endLine()
	}
	w.write("\n")
}

// write the input string and writes it to the buffer.
func (w *writer) write(s string) {
	w.buf.WriteString(s)
}

// writeLine writes the string on a newly started line, then terminate the line.
func (w *writer) writeLine(s string) {
	if !w.inline {
		w.startLine()
	}
	w.write(s)
	w.endLine()
}

func (w *writer) startMultilineSeq() {
	w.endLine()
	w.up()
	w.startLine()
}

// up increases the indentation level
func (w *writer) up() {
	w.level++
}

// down decreases the indentation level
func (w *writer) down() {
	if w.level == 0 {
		panic("negative indentation level")
	}
	w.level--
}

func ensureFutureKeywordImport(imps []*ast.Import, kw string) []*ast.Import {
	allKeywords := ast.MustParseTerm("future.keywords")
	kwPath := ast.MustParseTerm("future.keywords." + kw)
	for _, imp := range imps {
		if allKeywords.Equal(imp.Path) || imp.Path.Equal(kwPath) {
			return imps
		}
	}
	return append(imps, &ast.Import{Path: kwPath})
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**username** | **string** | Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. |
**email** | **string** |  | [optional]
**groups** | **string[]** | The groups this user belongs to. A user will get all permissions granted to each of their groups. | [optional]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)

redpajama_set_name: RedPajamaGithub


text:
package Systems;

import NetworkComm.InputOutputComm;
import edu.wpi.first.wpilibj.CANTalon;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Utility;
import edu.wpi.first.wpilibj.networktables.NetworkTable;

//Chill Out 1778 class for controlling the drivetrain

public class CANDriveAssembly {

	private static boolean initialized = false;

	// Speed controller IDs
	private static final int LEFT_FRONT_TALON_ID = 3;
	private static final int LEFT_REAR_TALON_ID = 4;
	private static final int RIGHT_FRONT_TALON_ID = 8;
	private static final int RIGHT_REAR_TALON_ID = 7;

	// joystick axis ids
	private static final int JOY_X_AXIS = 0;
	private static final int JOY_Y_AXIS = 1;
	private static final int JOY_Z_AXIS = 2;
	private static final int JOY_SLIDER_AXIS = 3;

	// joystick device ids
	private static final int LEFT_JOYSTICK_ID = 0;
	private static final int RIGHT_JOYSTICK_ID = 1;

	//threshold constants
	private static final double LATERAL_DEADZONE = 0.3;
	private static final double DRIVE_DEADZONE = 0.2;
	private static final double EQUALIZATION_THRESHOLD = 0.1;

	private static final long AUTO_DRIVE_TIME_SEC = 4;
	private static final double AUTO_DRIVE_SPEED = -0.5;
	private static final double AUTO_DRIVE_CORRECT_COEFF = 0.02;

	//other constants
	private static final boolean USE_SQUARED_INPUTS = true;
	private static final double GYRO_CORRECT_COEFF = 0.03;

	// speed controllers and drive class
	private static CANTalon mFrontLeft, mBackLeft, mFrontRight, mBackRight;
    private static RobotDrive drive;

    // drive control
    private static Joystick leftStick, rightStick;

	// static initializer
	public static void initialize()
	{
		if (!initialized) {
	        mFrontLeft = new CANTalon(LEFT_FRONT_TALON_ID);
	        mBackLeft = new CANTalon(LEFT_REAR_TALON_ID);
	        mFrontRight = new CANTalon(RIGHT_FRONT_TALON_ID);
	        mBackRight = new CANTalon(RIGHT_REAR_TALON_ID);

	        drive = new RobotDrive(mFrontLeft, mBackLeft, mFrontRight, mBackRight);

	        drive.setInvertedMotor(RobotDrive.MotorType.kFrontLeft, false);
	        drive.setInvertedMotor(RobotDrive.MotorType.kFrontRight, false);
	        drive.setInvertedMotor(RobotDrive.MotorType.kRearLeft, false);
	        drive.setInvertedMotor(RobotDrive.MotorType.kRearRight, false);

	        leftStick = new Joystick(LEFT_JOYSTICK_ID);
	        rightStick = new Joystick(RIGHT_JOYSTICK_ID);

	        initialized = true;
		}
	}

	public static void autoInit() {
   	}

	public static void autoPeriodicStraight(double speed) {
		// autonomous operation of drive straight

		//double gyroAngle = 0.0;
		double gyroAngle = GyroSensor.getAngle();

		//System.out.println("autoPeriodicStraight:  Gyro angle = " + gyroAngle);

		// calculate speed adjustment for left and right sides
		double driveAngle = -gyroAngle * AUTO_DRIVE_CORRECT_COEFF;

		// send output data for test & debug
		String gyroAngleStr = String.format("%.2f", gyroAngle);
		String driveAngleStr = String.format("%.2f", driveAngle);
		String myString = new String("gyroAngle = " + gyroAngleStr + " driveAngle = " + driveAngleStr + " speed = " + speed);
		System.out.println(myString);
		InputOutputComm.putString(InputOutputComm.LogTable.kMainLog,"Auto/autoPeriodicStraight_gyro", myString);

		/*
		if (driveAngle > 0.5) driveAngle = 0.5;
		if (driveAngle < -0.5) driveAngle = -0.5;
		*/

		double leftSpeed = speed+driveAngle;
		double rightSpeed = speed-driveAngle;

		String leftSpeedStr = String.format("%.2f", leftSpeed);
		String rightSpeedStr = String.format("%.2f", rightSpeed);
		String myString2 = new String("leftSpeed = " + leftSpeedStr + " rightSpeed = " + rightSpeedStr);
		System.out.println(myString2);
		InputOutputComm.putString(InputOutputComm.LogTable.kMainLog,"Auto/autoPeriodicStraight_tankDrive", myString2);

		// adjust speed of left and right sides
		//drive.tankDrive(driveAngle+speed, -driveAngle+speed);
		drive.tankDrive(leftSpeed, rightSpeed);

		//drive.drive(-speed, driveAngle);
	}

	public static void autoStop() {
		drive.drive(0.0, 0.0);
	}

	public static void teleopInit() {
		GyroSensor.reset();
	}

	public static void teleopPeriodic() {

		// Left Stick Throttle Control
		double throttleVal = 1.0 - ((leftStick.getRawAxis(JOY_Z_AXIS))+1.0)/2.0;

		// invert sign to compensate for joystick polarity (forward is neg Y, backward is pos Y)
		double leftValue = -throttleVal*leftStick.getY();
		double rightValue = -throttleVal*rightStick.getY();

		// Deadzones
		if(Math.abs(leftValue) <= DRIVE_DEADZONE) {
			leftValue = 0;
		}
		if(Math.abs(rightValue) <= DRIVE_DEADZONE) {
			rightValue = 0;
		}

		// Throttle Equalization Compensation
		if(Math.abs(leftValue-rightValue) <= EQUALIZATION_THRESHOLD) {
			double avgValue = (leftValue+rightValue)/2;
			//System.out.println("EQUALIZING: "+avgValue);
			leftValue = avgValue;
			rightValue = avgValue;
		}

		// Slowmode
		if(leftStick.getRawButton(1)) {
			leftValue /= 1.5;
			rightValue /= 1.5;
		}

		//Set the drive train
		drive(leftValue, rightValue, 0);

	}

	public static void drive(double left, double right, double strafe) {
		drive.tankDrive(left, right, USE_SQUARED_INPUTS);
	}

	public static void driveDirection(double angle, double speed) {
		double gyroAngle = getAngle();
		double driveAngle = (angle-gyroAngle)*GYRO_CORRECT_COEFF;
		drive(driveAngle+speed, -driveAngle+speed, 0);
	}

	public static void turnToDirection(double angle, double power) {
		double gyroAngle = getAngle();
		double driveAngle = (angle-gyroAngle)*(1/360)*power;
		drive(driveAngle, -driveAngle, 0);
	}

	public static void driveForward(double forwardVel) {
		drive(forwardVel, forwardVel, 0);
	}

	public static void rotate(double angularVel) {
		drive(angularVel, -angularVel, 0);
	}

	public static void driveVelocity(double forwardVel, double angularVel) {
		drive((forwardVel+angularVel)/2.0,(forwardVel-angularVel)/2.0,0);
	}

	private static double getAngle() {
		double angle = GyroSensor.getAngle();
		return angle;
	}

	//Redundant Methods
	//===================================================
	public static void rotateLeft(double speed) {
		drive(-speed, speed, 0);
	}

	public static void rotateRight(double speed) {
		drive(speed, -speed, 0);
	}
}


text:
/**
 * Shortcodes are a useful way of making content that lives in a CMS or in markdown files dynamic.
 *
 * By default, Elder.js ships with a {{svelteComponent name="" props="" options="" /}} shortcode.
 * Try adding a clock to one of your markdown files with:
 * `{{svelteComponent name="Clock" options='{"preload":true}' props='{"foo": true}' /}}`
 *
 */

module.exports = [
  {
    /**
     * This is a simple shortcode that will wrap content with a magical box.
     * Try adding `{{box class="yellow"}}Your content here{{/box}}` in one of your markdown files.
     * */
    shortcode: 'box',
    run: async ({ content, props }) => {
      return {
        // this is what the shortcode is replaced with. You CAN return an empty string.
        html: `<div class="box ${props.class}">${content}</div>`,

        // This is added to the page's css through the cssStack. You probably want an external css file for most usecases.
        css: '.box{border:1px solid red; padding: 1rem; margin: 1rem 0;} .box.yellow {background: lightyellow;}',

        // Javascript that is added to the footer via the customJsStack.
        js: '<script>var test = true;</script>',

        // Arbitrary HTML that is added to the head via the headStack
        head: '<meta test="true"/>',
      };
    },
  },

  /**
   *
   * A common issue with static content is that someone will need to go back and update that content.
   * * Imagine you have your content in a CMS such as WordPress, Contentful, Prismic, or even a markdown file.
   * * Within this content some "decision maker" has decided that you need to display the number of pages on your site... and it always has to be accurate.
   *
   * Usually pulling this off would require you to put a placeholder like {{numberOfPages /}} and then preprocessing the content, counting the number of pages, and then rendering it.
   *
   * With Elder.js shortcodes, all the preprocessing is done for you, you just need to decide what you want to replace it with.
   *
   * Below is code for the usecase above.
   *
   * It is important to note, even if you wanted {{latestInstagramPhoto /}} to be shown, the same approach would apply. Just use something like
   * `node-fetch` to hit Instagram's API and specify what html, css, js you'd like to add to the page.
   *
   * */

  {
    shortcode: 'numberOfPages',
    run: async ({ allRequests }) => {
      // allRequests represents 'request' objects for all of the pages of our site, if we know the length of that we know the length of our site.
      return {
        html: allRequests.length,
        // other values can be omitted.
      };
    },
  },
];


text:
"""Add Full Text Search

Revision ID: 488e3dae5a17
Revises: 34fa673d7905
Create Date: 2015-12-07 10:49:44.124657

"""

# revision identifiers, used by Alembic.
revision = '488e3dae5a17'
down_revision = '34fa673d7905'

from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
from sqlalchemy_searchable import sync_trigger

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    conn = op.get_bind()
    op.drop_table('sections')
    op.add_column('notes', sa.Column('search_vector', sqlalchemy_utils.types.ts_vector.TSVectorType(), nullable=True))
    op.create_index('ix_notes_search_vector', 'notes', ['search_vector'], unique=False, postgresql_using='gin')
    ### end Alembic commands ###
    sync_trigger(conn, 'notes', 'search_vector', ['title', 'body'])

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_index('ix_notes_search_vector', table_name='notes')
    op.drop_column('notes', 'search_vector')
    op.create_table('sections',
    sa.Column('id', sa.INTEGER(), nullable=False),
    sa.Column('title', sa.VARCHAR(length=200), autoincrement=False, nullable=True),
    sa.Column('notebook_id', sa.INTEGER(), autoincrement=False, nullable=True),
    sa.ForeignKeyConstraint(['notebook_id'], [u'notebooks.id'], name=u'sections_notebook_id_fkey'),
    sa.PrimaryKeyConstraint('id', name=u'sections_pkey')
    )
    ### end Alembic commands ###


text:
Detecting water on my roof using a hi3510/rtt-3300 camera.

For now this is just some random code, but over time it will hopefully become something coherent :)

The goal is to have a cronjob that periodically takes snapshots using the camera pointed at my flat roof.
Roofcam will then detect whether the latest snapshot contains any water and then serve that snapshot and its
classification (water/no water) in a simple html page that can be included in a
[homeassistant](http://homeassistant.io/) dashboard.

Might also build a simple web UI to easily classify snapshots manually. The result of that manual classification
can then be compared to roofcam's classifier as to get an idea of roofcam's classifier accuracy. This will help to
experiment with different classifiers and compare their accuracy.

## Getting started

Roofcam requires [Pillow](http://pillow.readthedocs.io/en/4.0.x/index.html). Since Pillow has binary dependencies, it's
easiest to install it as a system package:

```bash
# Build container image
docker build -t roofcam .

# Run container
docker run -v $(pwd):/roofcam -p 1234:1234 -it roofcam bash

# setup.py develop needed to use Flask debug mode:
python setup.py develop

# Classify a single snapshot
roofcam-ml classify --debug -p `ls samples/snapshot* | sort | tail -1`

# Classify a directory of snapshots
roofcam-ml classify --debug -p samples

# host a webserver with the latest snapshot
roofcam --debug --dir samples --port 1234 --host 0.0.0.0
```

### Convenience commands

```bash
# Remove docker image
docker rmi -f roofcam
```


text:
package mx.fiscoflex.contabilidad.exception;

public class ApiException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private MensajeError mensajeError;

	public ApiException() {

	}

	public ApiException(MensajeError mensajeError) {
		this.mensajeError = mensajeError;
	}

	public String getMessage() {

		String message =  "\n\tError: " + mensajeError.getCodigo() +
			" \n\tMensaje: " + mensajeError.getMensaje() +
			" \n\tReferencia: " + mensajeError.getReferencia() + "\n";

		return message;

	}

	public MensajeError getMensajeError() {
		return mensajeError;
	}

	public void setMensajeError(MensajeError mensajeError) {
		this.mensajeError = mensajeError;
	}

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 32: 567 (1940)

#### Original name
Patella contradicta Seaver

### Remarks
null


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>Evo moram pohvalit ljude iz kvarta. Fino rade svoj posao. Pizza je ukusna, dostava brza i ljubazna. Samo molim Vas jedno-nemojte se pokvarit kao svi ostali jer počeli ste pokazivat prve znakove. Sretno u budućnosti i nadam se još dugoj suradnji. Lijep pozdrav ekipi.</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/pizza-slavonija</Source>
</CrawlItem>


text:
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc.  All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
//     * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
//     * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

package com.google.protobuf;

import any_test.AnyTestProto.TestAny;
import protobuf_unittest.UnittestProto.TestAllTypes;

import junit.framework.TestCase;

/**
 * Unit tests for Any message.
 */
public class AnyTest extends TestCase {
  public void testAnyGeneratedApi() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    TestAllTypes message = builder.build();

    TestAny container = TestAny.newBuilder()
        .setValue(Any.pack(message)).build();

    assertTrue(container.getValue().is(TestAllTypes.class));
    assertFalse(container.getValue().is(TestAny.class));

    TestAllTypes result = container.getValue().unpack(TestAllTypes.class);
    TestUtil.assertAllFieldsSet(result);

    // Unpacking to a wrong type will throw an exception.
    try {
      TestAny wrongMessage = container.getValue().unpack(TestAny.class);
      fail("Exception is expected.");
    } catch (InvalidProtocolBufferException e) {
      // expected.
    }

    // Test that unpacking throws an exception if parsing fails.
    TestAny.Builder containerBuilder = container.toBuilder();
    containerBuilder.getValueBuilder().setValue(
        ByteString.copyFrom(new byte[]{0x11}));
    container = containerBuilder.build();
    try {
      TestAllTypes parsingFailed = container.getValue().unpack(TestAllTypes.class);
      fail("Exception is expected.");
    } catch (InvalidProtocolBufferException e) {
      // expected.
    }
  }

  public void testCachedUnpackResult() throws Exception {
    TestAllTypes.Builder builder = TestAllTypes.newBuilder();
    TestUtil.setAllFields(builder);
    TestAllTypes message = builder.build();

    TestAny container = TestAny.newBuilder()
        .setValue(Any.pack(message)).build();

    assertTrue(container.getValue().is(TestAllTypes.class));

    TestAllTypes result1 = container.getValue().unpack(TestAllTypes.class);
    TestAllTypes result2 = container.getValue().unpack(TestAllTypes.class);
    assertTrue(result1 == result2);
  }
}


text:
package com.encoway.edu;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

/**
 * MyFaces Test Suite.
 */
@RunWith(Suite.class)
@SuiteClasses({ DemoIT.class })
public class ITSuite {

}


text:
/* eslint no-var: 0 */
var command = require("./command");
var packageJson = require("./../package.json");
var utils = require("./utils");

/*------ Update package.json ------*/

var scripts = utils.removePropertiesFromObj(packageJson.scripts,["postinstall"]);

var dependencies = utils.extractPropertiesFromObj(packageJson.dependencies,["react", "react-dom","prop-types"]);

var newJson = {
    "devDependencies": packageJson.dependencies,
    "dependencies": dependencies,
    "scripts":scripts,
    "files": [
        "lib"
    ]
};

command.createDir( "../../src",function(){
    command.createDir( "../../test",function(){
        command.copyDir( "./scripts", "../../scripts",function(){
            command.copyDir( "./src", "../../src",function(){
                command.copyFile( "./webpack.config.js", "../../webpack.config.js",function(){
                    command.copyFile( "./.babelrc", "../../.babelrc",function(){
                        command.copyFile( "./.eslintrc.json", "../../.eslintrc.json",function(){
                            command.updateJson( "../../package.json", newJson,function(){
                                command.remove("../../scripts/postinstall.js",function(){
                                    command.remove("../../scripts/utils.js",function(){
                                        command.remove("../../node_modules/boilerplate")
                                    })
                                })
                            });
                        })
                    });
                });
            });
        });
    });
});


text:
"""
Display bill for Amazon Web Services.

**WARNING: This module generate some costs on the AWS bill.
Take care about the cache_timeout to limit these fees!**

Configuration parameters:
    aws_access_key_id: Your AWS access key (default '')
    aws_account_id: The root ID of the AWS account
        Can be found here` https://console.aws.amazon.com/billing/home#/account
        (default '')
    aws_secret_access_key: Your AWS secret key (default '')
    billing_file: Csv file location (default '/tmp/.aws_billing.csv')
    cache_timeout: How often we refresh this module in seconds (default 3600)
    format: string that formats the output. See placeholders below.
        (default '{bill_amount}$')
    s3_bucket_name: The bucket where billing files are sent by AWS.
        Follow this article to activate this feature:
        https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-reports.html
        (default '')

Format placeholders:
    {bill_amount} AWS bill amount

Color options:
    color_good: Balance available
    color_bad: An error has occured

Requires:
    boto:

@author nawadanp

SAMPLE OUTPUT
{'full_text': u'108.78$'}
"""

import boto
import csv
import datetime

from boto.s3.connection import Key

class Py3status:
    """
    """
    # available configuration parameters
    aws_access_key_id = ''
    aws_account_id = ''
    aws_secret_access_key = ''
    billing_file = '/tmp/.aws_billing.csv'
    cache_timeout = 3600
    format = '{bill_amount}$'
    s3_bucket_name = ''

    def _get_bill_amount(self):
        # Billing file name, generated by Amazon itself
        # Format : 123456789012-aws-billing-csv-yyyy-mm.csv
        s3_file_key = '{}-aws-billing-csv-{}-{}.csv'.format(
            self.aws_account_id, datetime.datetime.now().strftime('%Y'),
            datetime.datetime.now().strftime('%m'))
        i = 0

        # Connection to s3 service
        try:
            conn = boto.connect_s3(self.aws_access_key_id,
                                   self.aws_secret_access_key)
        except:  # noqa e722
            return 'conn_error'

        # Connection to the bucket
        try:
            bucket = conn.get_bucket(self.s3_bucket_name)
        except:  # noqa e722
            return 'bucket_error'

        # Fetch the objects keys and get the billing file
        try:
            k = Key(bucket)
            k.key = s3_file_key
            k.get_contents_to_filename(self.billing_file)
            k.close
        except:  # noqa e722
            return 'key_error'

        # Parse the file and get the InvoiceTotal amount
        try:
            with open(self.billing_file, 'rb') as f:
                reader = csv.reader(f)
                for row in reader:
                    if ''.join(row).find('InvoiceTotal') == -1:
                        continue
                    i = i + 1
                    return row[-1]
        except:  # noqa e722
            return 'csv_error'

        return False

    def aws_bill(self):
        response = {
            'cached_until': self.py3.time_in(self.cache_timeout),
            'color': self.py3.COLOR_BAD,
            'full_text': ''
        }

        bill_amount = self._get_bill_amount()

        if bill_amount == 'csv_error':
            response['full_text'] = 'Bad CSV file'
        elif bill_amount == 'key_error':
            response['full_text'] = 'Key not found in the bucket'
        elif bill_amount == 'bucket_error':
            response['full_text'] = 'Check the bucket name or your AWS keys'
        elif bill_amount == 'conn_error':
            response['full_text'] = 'Check your internet access'
        elif bill_amount is not False:
            response['full_text'] = self.py3.safe_format(
                self.format, {'bill_amount': bill_amount}
            )
            response['color'] = self.py3.COLOR_GOOD
        else:
            response['full_text'] = 'Global error - WTF exception'

        return response

if __name__ == "__main__":
    """
    Run module in test mode.
    """
    from py3status.module_test import module_test
    module_test(Py3status)


text:
def largest_product():
    pass


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Cutlass: cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ > Struct Template Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Cutlass

CUDA Templates for Linear Algebra Subroutines and Solvers

cutlass

gemm

GemmSharedStoreTileDTraits

Classes |
Public Types |
Static Public Attributes |
List of all members

cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ > Struct Template Reference

#include <gemm_shared_tile.h>

Classes

struct  	ThreadOffset

 	Computes the thread offset in (H, W) based on thread ID.  More...

Public Types

typedef platform::remove_const< Scalar_ >::type 	Scalar

 	The scalar.  More...

typedef Scalar_ * 	Pointer

 	The pointer.  More...

typedef OutputTile_ 	OutputTile

 	The dimension of the output tile.  More...

typedef Warps_ 	Warps

 	The warps in the tile.  More...

typedef ThreadsPerWarp_ 	ThreadsPerWarp

 	The threads in the warps.  More...

typedef Shape< 1, 2, kScalarsPerRow/kAccessSize, kAccessSize > 	Tile

 	The tile.  More...

typedef Shape< 1, 1, kScalarsPerThread/kAccessSize > 	Iterations

 	The number of iterations needed to store the tile.  More...

typedef Shape< 0, 0, Warps::kW *ThreadsPerWarp::kW *kAccessSize > 	Delta

 	The strides in each dimension between different loads/stores.  More...

typedef Shape< 0, 0, Warps::kW *ThreadsPerWarp::kW *kAccessSize > 	ImmediateOffsetStrides

 	The strides in each dimension between different loads/stores.  More...

Static Public Attributes

static int const 	kAccessSize = kScalarsPerSts_

 	The number of scalars per LDG/STG.  More...

static int const 	kSkew = kSkew_

 	The skew.  More...

static MemorySpace::Kind const 	kMemorySpace = MemorySpace::kShared

 	The memory space.  More...

static int const 	kScalarsPerThread = OutputTile_::kW / Warps::kW / ThreadsPerWarp::kW

 	The number of scalars per thread.  More...

static int const 	kThreads = ShapeCount<Warps>::kCount * kWarpSize

 	The number of threads.  More...

static int const 	kScalarsPerRow = kThreads / 2 * kScalarsPerThread + kSkew

 	The number of scalars per row. We build a tile with 2 rows (to avoid bank conflicts).  More...

Member Typedef Documentation

◆ Delta

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef Shape<0, 0, Warps::kW * ThreadsPerWarp::kW * kAccessSize> cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::Delta

◆ ImmediateOffsetStrides

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef Shape<0, 0, Warps::kW * ThreadsPerWarp::kW * kAccessSize> cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::ImmediateOffsetStrides

◆ Iterations

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef Shape<1, 1, kScalarsPerThread / kAccessSize> cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::Iterations

◆ OutputTile

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef OutputTile_ cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::OutputTile

◆ Pointer

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef Scalar_* cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::Pointer

◆ Scalar

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef platform::remove_const<Scalar_>::type cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::Scalar

◆ ThreadsPerWarp

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef ThreadsPerWarp_ cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::ThreadsPerWarp

◆ Tile

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef Shape<1, 2, kScalarsPerRow / kAccessSize, kAccessSize> cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::Tile

◆ Warps

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          typedef Warps_ cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::Warps

Member Data Documentation

◆ kAccessSize

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          int const cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::kAccessSize = kScalarsPerSts_

static

◆ kMemorySpace

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          MemorySpace::Kind const cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::kMemorySpace = MemorySpace::kShared

static

◆ kScalarsPerRow

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          int const cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::kScalarsPerRow = kThreads / 2 * kScalarsPerThread + kSkew

static

◆ kScalarsPerThread

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          int const cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::kScalarsPerThread = OutputTile_::kW / Warps::kW / ThreadsPerWarp::kW

static

◆ kSkew

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          int const cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::kSkew = kSkew_

static

◆ kThreads

template<typename Scalar_ , typename OutputTile_ , typename Warps_ , typename ThreadsPerWarp_ , int kScalarsPerSts_, int kSkew_ = 0>

          int const cutlass::gemm::GemmSharedStoreTileDTraits< Scalar_, OutputTile_, Warps_, ThreadsPerWarp_, kScalarsPerSts_, kSkew_ >::kThreads = ShapeCount<Warps>::kCount * kWarpSize

static

The documentation for this struct was generated from the following file:

gemm_shared_tile.h

<address class="footer">
Generated on Fri Oct 26 2018 14:53:39 for Cutlass by

 1.8.14
</address>


text:
<?xml version="1.0" encoding="UTF-8"?>
<atom:feed xmlns:atom="http://www.w3.org/2005/Atom" xmlns:batch="http://schemas.google.com/gdata/batch" xmlns:gs="http://schemas.google.com/spreadsheets/2006" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/">
   <atom:id>https://spreadsheets.google.com/feeds/cells/15LBU0RDjnN-VvhG2tYOoVLfCH40D6JoW5NfFiqSTc5U/ov45g5m/private/full/batch/1459043728174</atom:id>
   <atom:updated>2016-03-27T01:55:28.200Z</atom:updated>
   <atom:category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#cell" />
   <atom:title type="text">Batch Feed</atom:title>
   <atom:entry>
      <atom:id>https://spreadsheets.google.com/feeds/cells/15LBU0RDjnN-VvhG2tYOoVLfCH40D6JoW5NfFiqSTc5U/ov45g5m/private/full/R2C1</atom:id>
      <atom:updated>2016-03-23T22:28:14.711Z</atom:updated>
      <atom:category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#cell" />
      <atom:title type="text">A2</atom:title>
      <atom:content type="text">111</atom:content>
      <atom:link rel="self" type="application/atom+xml" href="https://spreadsheets.google.com/feeds/cells/15LBU0RDjnN-VvhG2tYOoVLfCH40D6JoW5NfFiqSTc5U/ov45g5m/private/full/R2C1" />
      <atom:link rel="edit" type="application/atom+xml" href="https://spreadsheets.google.com/feeds/cells/15LBU0RDjnN-VvhG2tYOoVLfCH40D6JoW5NfFiqSTc5U/ov45g5m/private/full/R2C1/2g41" />
      <gs:cell row="2" col="1" inputValue="111" numericValue="111.0">111</gs:cell>
      <batch:id>A1</batch:id>
      <batch:status code="400" reason="Success" />
      <batch:operation type="update" />
   </atom:entry>
   <atom:entry>
      <atom:id>https://spreadsheets.google.com/feeds/cells/15LBU0RDjnN-VvhG2tYOoVLfCH40D6JoW5NfFiqSTc5U/ov45g5m/private/full/R2C2</atom:id>
      <atom:updated>2016-03-23T22:28:14.711Z</atom:updated>
      <atom:category scheme="http://schemas.google.com/spreadsheets/2006" term="http://schemas.google.com/spreadsheets/2006#cell" />
      <atom:title type="text">B2</atom:title>
      <atom:content type="text">222</atom:content>
      <atom:link rel="self" type="application/atom+xml" href="https://spreadsheets.google.com/feeds/cells/15LBU0RDjnN-VvhG2tYOoVLfCH40D6JoW5NfFiqSTc5U/ov45g5m/private/full/R2C2" />
      <atom:link rel="edit" type="application/atom+xml" href="https://spreadsheets.google.com/feeds/cells/15LBU0RDjnN-VvhG2tYOoVLfCH40D6JoW5NfFiqSTc5U/ov45g5m/private/full/R2C2/a229e" />
      <gs:cell row="2" col="2" inputValue="222" numericValue="222.0">222</gs:cell>
      <batch:id>A2</batch:id>
      <batch:status code="200" reason="Success" />
      <batch:operation type="update" />
   </atom:entry>
</atom:feed>


text:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFireDatabase, AngularFireList } from '@angular/fire/database';
import { Title, Meta } from '@angular/platform-browser';
import { GlobalService } from '../../services/global.service';
import { LocalCartService } from '../../services/localcart.service';

@Component({
  selector: 'checkout-review',
  templateUrl: './checkout-review.component.html',
  styleUrls: ['./checkout-review.component.scss']
})
export class CheckoutReviewComponent implements OnInit {
  order: any;
  user: any;
  now: number;
  sources: AngularFireList<any[]>;
  charges: any;
  newCharge: any;

  constructor(
    public db: AngularFireDatabase,
    public router: Router,
    public globalService: GlobalService,
    public localCart: LocalCartService,
    private title: Title,
    private meta: Meta
  ) {
    this.charges = {};
    this.newCharge = {};
    this.order = globalService.order.getValue();
    this.user = globalService.user.getValue();
    const now = new Date().getTime();

    if (this.user) {
      this.sources = db.list('/stripe_customers/' + this.user.uid + '/sources');
    } else {
      router.navigateByUrl('cart');
    }

    if (this.sources) {
      this.sources.valueChanges().subscribe((s) => {
        this.newCharge.source = s[(s.length - 1)];
      });
    } else {
      router.navigateByUrl('cart');
    }

    if (this.order) {
      if (this.user) {
        this.order.uid = this.user.uid;
      }
      this.order.date = now;
      this.order.rdate = (now * -1);
      this.order.status = 'PAID';
    }

    if (!this.order || !this.order.billing) {
      router.navigateByUrl('cart');
    }
  }

  ngOnInit() {
    this.title.setTitle('Review');
    this.meta.updateTag({ content: 'Review items and information for the order' }, "name='description'");
  }

  confirm() {
    this.submitNewCharge();
    let newKey = Math.abs(this.globalService.hashCode(this.order.date) + this.globalService.hashCode(this.order.shipping.email));
    this.db.list('/orders').push(this.order).then((item) => {
      this.globalService.cart.next(null);
      this.globalService.order.next(null);
      this.localCart.clearAll();
      if (this.user) {
        this.db.object('/users/' + this.user.uid + '/cart').remove();
        this.db.object('/users/' + this.user.uid + '/orders/' + item.key).set(Date.now().toString());
      }
      this.router.navigateByUrl('checkout/confirmation');
    });
  }

  submitNewCharge() {
    this.db.list('/stripe_customers/' + this.user.uid + '/charges').push({
      source: this.newCharge.source.id,
      amount: Math.floor(this.order.total * 100)
    });
  }
}


text:
class ItemsController < ApplicationController

  def new
    @restaurant = Restaurant.find(params[:restaurant_id])
    @item = Item.new
  end

  def create
    @item = Item.new(item_params)
    @restaurant = Restaurant.find(@item.restaurant_id)
    if @item.save
      redirect_to restaurant_path(@restaurant),
        notice: "#{@item.name} added"
    else
      flash[:alert] = "#{@item[:name]} couldn't be added"
      render :new
    end
  end

  def item_params
    params.require(:item).permit(:name, :price, :description, :restaurant_id, :ingredients)
  end

end


text:
package com.syntrust.www.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsFileUploadSupport;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import com.syntrust.www.service.FileService;

/**
 * 文件操作分发类
 *
 * @author reece
 *
 */
@Controller
@RequestMapping("/file")
public class FileController extends CommonsMultipartResolver{

	@Autowired
	private FileService fileService;

	@RequestMapping("/upload.do")
	@ResponseBody
	public String upload(HttpServletRequest request,HttpServletResponse response) throws IOException{

		DefaultMultipartHttpServletRequest mRequest = (DefaultMultipartHttpServletRequest)resolveMultipart(request);

		String test = mRequest.getMultipartContentType("file");

		System.out.println(test);

		Map<String,MultipartFile> files= mRequest.getFileMap();

		System.out.println(files);

		Iterator<String> it= mRequest.getFileNames();
		String name = null;
		while(it.hasNext()) {
			name = it.next();
		}
		MultipartFile file = mRequest.getFile(name);
		InputStream in = file.getInputStream();
		File target = new File("temp.txt");
		if(!target.exists())
			target.createNewFile();
		OutputStream out = new FileOutputStream(target);
		byte[] buf = new byte[1024*8];
		int i=0;
		while((i=in.read(buf)) != -1){
			out.write(buf, 0, i);
		}
		out.flush();

		return "success";
	}

	/*
	protected static class MultipartParsingResult {
		private final MultiValueMap<String, MultipartFile> multipartFiles;
		private final Map<String, String[]> multipartParameters;
		private final Map<String, String> multipartParameterContentTypes;

		public MultipartParsingResult(MultiValueMap<String, MultipartFile> mpFiles, Map<String, String[]> mpParams,
				Map<String, String> mpParamContentTypes) {
			this.multipartFiles = mpFiles;
			this.multipartParameters = mpParams;
			this.multipartParameterContentTypes = mpParamContentTypes;
		}

		public MultiValueMap<String, MultipartFile> getMultipartFiles() {
			return this.multipartFiles;
		}

		public Map<String, String[]> getMultipartParameters() {
			return this.multipartParameters;
		}

		public Map<String, String> getMultipartParameterContentTypes() {
			return this.multipartParameterContentTypes;
		}
	}
	*/

}


text:
package com.hisporter.collection.database.lang;

import java.util.LinkedList;
import java.util.List;

/**
 * 关联字段
 *
 * @author zhangjp
 * @version 1.0
 */

public class JoinField {
    //关联左侧的字段名称
    private final List<String> leftFieldNames = new LinkedList<>();
    //关联右侧的字段名称
    private final List<String> rightFieldNames = new LinkedList<>();

    public List<String> getLeftFieldNames() {
        return leftFieldNames;
    }

    public List<String> getRightFieldNames() {
        return rightFieldNames;
    }

    public void addJoinField(String leftFieldName , String rightFieldName){
        this.leftFieldNames.add(leftFieldName);
        this.rightFieldNames.add(rightFieldName);
    }
}


text:
#ifndef __Application__
#define __Application__

#include <chrono>
#include <iostream>
#include <thread>
#include <string>

#include <SFML/System/Time.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics/Text.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Network.hpp>

#include "Environment.h"
#include "Flag_Handler.h"
#include "Player.h"
#include "Resources.h"
#include "StateStack.h"
#include "Troop_Factory.h"

class Application{

	public:
		Application();
		~Application();
		void run();
		sf::Socket::Status connect();
		void loadResources();
		void render();
		void preTurn();
		void postTurn();
		void handleEvents();
		bool handleIncomingPackets( sf::Packet &pkt );
		void disconnect();
		void listenForUpdates();
		void loadPlayerTroops();

	private:

		/*
		 *  The renderWindow is the hub of SFML
		 *  it handles events, manipulates the view,
		 *  and renders the game
		 */

		sf::RenderWindow window;

		/*
		 * The state stack used to handle all of the mechanisms
		 * such as creating new states (playable/menu), drawing,
		 * and updateing the view/model
		 */

		StateStack stateStack;

		/*
		 *  Socket used to communicate
		 *  with the server
		 */

		sf::TcpSocket server;

		/*
		 *  This is the player for the local application only
		 *  and the object contains player meta data
		 */

		Player player;

		/*
		 * This represents the current turn
		 * within the entire game
		 */

		int turnCount;

		TrName stringToTroopEnum(std::string troop);

		bool should_break;
		void addTroopToFactory(sf::Packet &pkt);
};

#endif


text:
package com.googlecode.aluminumproject.context;

import com.googlecode.aluminumproject.AluminumException;

import java.util.Set;

/**
 * A context that is used throughout the processing of one template.
 *

 * A context can contain variables. Each variable is stored in a certain scope. At the very minimum, implementations are
 * required to support the template scope, though it's possible to add scopes. Scopes that are added can be
 * removed as well.
 *

 * A context can have a number of implicit objects, which are not scoped. Implicit objects can be {@link
 * #addImplicitObject(String, Object) added} and {@link #removeImplicitObject(String) removed} freely, although their
 * names should not start with {@value #RESERVED_IMPLICIT_OBJECT_NAME_PREFIX}. Subclasses can further restrict the names
 * that may be used for implicit names.
 *

 * When a context supports it, it's possible to create one or more child contexts. The parent of such a child context
 * can be {@link #getParent() obtained} and will be used when {@link #findVariable(String) finding variables}.
 */
public interface Context {
	/**
	 * Returns all scope names, ordered by priority (from highest to lowest).
	 *
	 * @return a set that contains the names of all scopes in this context
	 */
	Set<String> getScopeNames();

	/**
	 * Adds a scope.
	 *
	 * @param name the name of the scope to add
	 * @param requireUniqueName whether the name is expected to be unique; if it isn't, this context is allowed to
	 *                          change the name to ensure its uniqueness
	 * @return the actual name of the new scope: this will be the same name as was requested if it should be unique, it
	 *         could be different if a scope with the requested name already exists and the name is not required to be
	 *         unique
	 * @throws AluminumException when the name has to be unique and there already is a scope with the given name
	 */
	String addScope(String name, boolean requireUniqueName) throws AluminumException;

	/**
	 * Removes a scope.
	 *
	 * @param name the name of the scope to remove
	 * @throws AluminumException when there's no scope with the given name or when the scope can't be removed
	 */
	void removeScope(String name) throws AluminumException;

	/**
	 * Returns all variable names within a certain scope.
	 *
	 * @param scope the name of the scope to retrieve the variable names of
	 * @return a set that contains the names of all variables in the given scope (may be empty but not {@code null})
	 * @throws AluminumException when there's no scope with the given name
	 */
	Set<String> getVariableNames(String scope) throws AluminumException;

	/**
	 * Retrieves a variable by name.
	 *
	 * @param scope the name of the scope to get the variable from
	 * @param name the name of the variable to retrieve
	 * @return the value of the variable with the given name in the specified scope
	 * @throws AluminumException when there's no scope with the given name or when there's no variable with the given
	 *                           name within the scope
	 */
	Object getVariable(String scope, String name) throws AluminumException;

	/**
	 * Sets a variable in the innermost scope (i.e. the scope that was added last).
	 *
	 * @param name the name of the variable to set
	 * @param value the value to set
	 * @return the previous value of the variable (or {@code null} if the variable did not exist)
	 */
	Object setVariable(String name, Object value);

	/**
	 * Sets a variable.
	 *
	 * @param scope the name of the scope to set the variable in
	 * @param name the name of the variable to set
	 * @param value the value to set
	 * @return the previous value of the variable (or {@code null} if the variable did not exist)
	 * @throws AluminumException when there's no scope with the given name
	 */
	Object setVariable(String scope, String name, Object value) throws AluminumException;

	/**
	 * Removes a variable from the innermost scope (i.e. the scope that was added last).
	 *
	 * @param name the name of the variable to remove
	 * @return the previous value of the variable
	 * @throws AluminumException when there's no variable with the given name within the innermost scope
	 */
	Object removeVariable(String name) throws AluminumException;

	/**
	 * Removes a variable.
	 *
	 * @param scope the name of the scope to remove the variable from
	 * @param name the name of the variable to remove
	 * @return the previous value of the variable
	 * @throws AluminumException when there's no scope with the given name or when there's no variable with the given
	 *                           name within the scope
	 */
	Object removeVariable(String scope, String name) throws AluminumException;

	/**
	 * Finds a variable across all scopes. When multiple scopes have a variable with the given name, it's up to the
	 * context implementation which variable will be returned. When none of the scopes in this context contain a
	 * variable with the specified name and a parent context is available, the variable will be tried to be found in
	 * that context.
	 *
	 * @param name the name of the variable to find
	 * @return the value of the variable with the given name
	 * @throws AluminumException when not a scope in either this context or one of its ancestor contexts contains a
	 *                           variable with the given name
	 */
	Object findVariable(String name) throws AluminumException;

	/**
	 * Returns all implicit object names.
	 *
	 * @return a set that contains the names of all implicit objects
	 */
	Set<String> getImplicitObjectNames();

	/**
	 * Retrieves a implicit object by name.
	 *
	 * @param name the name of the implicit object to return
	 * @return the implicit object with the given name
	 * @throws AluminumException when no implicit object with the given name exists in this context
	 */
	Object getImplicitObject(String name) throws AluminumException;

 	/**
	 * Adds an implicit object.
	 *
	 * @param name the name of the implicit object
	 * @param implicitObject the implicit object to add
	 * @throws AluminumException when there already is an implicit object with the given name or when the name is
	 *                           reserved
	 */
	void addImplicitObject(String name, Object implicitObject) throws AluminumException;

	/**
	 * Removes an implicit object with a certain name.
	 *
	 * @param name the name of the implicit object to remove
	 * @return the removed implicit object
	 * @throws AluminumException when there's no implicit object with the given name
	 */
	Object removeImplicitObject(String name) throws AluminumException;

	/**
	 * Returns the parent of this context.
	 *
	 * @return this context's parent, {@code null} if this context does not have a parent
	 */
	Context getParent();

	/**
	 * Creates a child context of this context.
	 *
	 * @return the new subcontext
	 * @throws AluminumException when this context does not support subcontexts
	 */
	Context createSubcontext() throws AluminumException;

	/** The name of the default scope. */
	String TEMPLATE_SCOPE = "template";

	/** The prefix of names of implicit objects that are reserved for internal use: {@value}. */
	String RESERVED_IMPLICIT_OBJECT_NAME_PREFIX = "aluminum";
}


text:
package dms_enterprise

//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

// SearchDatabase is a nested struct in dms_enterprise response
type SearchDatabase struct {
	DatabaseId    string                        `json:"DatabaseId" xml:"DatabaseId"`
	Logic         bool                          `json:"Logic" xml:"Logic"`
	EnvType       string                        `json:"EnvType" xml:"EnvType"`
	SchemaName    string                        `json:"SchemaName" xml:"SchemaName"`
	SearchName    string                        `json:"SearchName" xml:"SearchName"`
	DbType        string                        `json:"DbType" xml:"DbType"`
	Host          string                        `json:"Host" xml:"Host"`
	Port          int                           `json:"Port" xml:"Port"`
	Sid           string                        `json:"Sid" xml:"Sid"`
	DbaId         string                        `json:"DbaId" xml:"DbaId"`
	Encoding      string                        `json:"Encoding" xml:"Encoding"`
	Alias         string                        `json:"Alias" xml:"Alias"`
	DatalinkName  string                        `json:"DatalinkName" xml:"DatalinkName"`
	OwnerIdList   OwnerIdListInSearchDatabase   `json:"OwnerIdList" xml:"OwnerIdList"`
	OwnerNameList OwnerNameListInSearchDatabase `json:"OwnerNameList" xml:"OwnerNameList"`
}


text:
var address = {};
module['exports'] = address;
address.country = require("./country");
address.building_number = require("./building_number");
address.street_prefix = require("./street_prefix");
address.secondary_address = require("./secondary_address");
address.postcode = require("./postcode");
address.state = require("./state");
address.state_abbr = require("./state_abbr");
address.city_name = require("./city_name");
address.city = require("./city");
address.street_name = require("./street_name");
address.street_address = require("./street_address");
address.default_country = require("./default_country");


text:
package com.vladium.utils;

// ----------------------------------------------------------------------------
/**
 * An {@link ILink} implementation for tree links created by array fields.
 *
 * @author (C) Vlad Roubtsov, 2003
 */
final class ArrayIndexLink implements ILink
{
    // public: ................................................................

    // ILink:

    public String name ()
    {
        final StringBuffer s = new StringBuffer ();

        ILink l = this;
        while (l instanceof ArrayIndexLink)
        {
            final ArrayIndexLink asl = (ArrayIndexLink) l;

            s.insert (0, ']');
            s.insert (0, asl.m_index);
            s.insert (0, '[');

            l = asl.m_container;
        }

        s.insert (0, l != null ? l.name () : ObjectProfiler.INPUT_OBJECT_NAME);

        return s.toString ();
    }

    // protected: .............................................................

    // package: ...............................................................

    ArrayIndexLink (final ILink container, final int index)
    {
        m_container = container;
        m_index = index;
    }

    // private: ...............................................................

    private final ILink m_container;
    private final int m_index;

} // end of class
// ----------------------------------------------------------------------------


text:
function fread(handle,length){
	var data = handle.data.slice(handle.pos,handle.pos+length);
	handle.pos = handle.pos+length;
	return data;
}
function fwrite(handle,buffer,length){
	handle.data = handle.data + buffer.slice(0, length);
	handle.pos = handle.pos+length;
	return handle.pos;
}

function getInt32(handle){
	var str = fread(handle,4);
	var buf = pack('a4',str);
	var res = unpack('l',buf);
	return(res[1]||res[""]);
}
function getInt8(handle){
	var str = fread(handle,1);
	var buf = pack('a',str);
	var res = unpack('c',buf);
	return(res[1]||res[""]);
}
function getString(handle,length){
	var str =  fread(handle,length);
	var buf = pack('a'+length,str);
	var res = unpack('a'+length,buf);
	return(res[1]||res[""]);
}
function getFloat(handle){
	var str = fread(handle, 4);
	var buf = pack('a4',str);
	var res = unpack('f',buf);
	return(res[1]||res[""]);
}

function writeInt32(handle,val){
	var buf = pack('l',val);
	return fwrite(handle, buf,4);
}
function writeInt8(handle,val){
	var buf = pack('c',val);
	return fwrite(handle, buf,1);
}
function writeFloat(handle,val){
	buf = pack('f',val);
	return fwrite(handle, buf,4);
}
function writeString(handle,val,length){
	var buf = pack('a'+length,val);
	return fwrite(handle, buf,length);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <plurals name="listTotalAllContacts">
        <item quantity="other">Контактов: %d</item>
        <item quantity="one">Контактов: 1</item>
    </plurals>
    <plurals name="searchFoundContacts">
        <item quantity="other">Найдено: %d</item>
        <item quantity="one">Найдено: 1</item>
    </plurals>
    <plurals name="num_contacts_in_group">
        <item quantity="other">Людей: %1$d из %2$s</item>
        <item quantity="one">Людей: %1$d из %2$s</item>
    </plurals>
    <plurals name="group_list_num_contacts_in_group">
        <item quantity="other">Людей: %1$d</item>
        <item quantity="one">Людей: %1$d</item>
    </plurals>
    <plurals name="notification_voicemail_title">
        <item quantity="other">Голосовых сообщений: %1$d</item>
        <item quantity="one">Голосовая почта</item>
    </plurals>
    <plurals name="searchFoundCalllogs">
        <item quantity="other">Журналов вызовов: %d</item>
        <item quantity="one">Журналов вызовов: 1</item>
    </plurals>
    <plurals name="search_listTotalAllContacts">
        <item quantity="other">Поиск контактов | Всего %d контак.</item>
        <item quantity="one">Поиск контактов | Всего 1 контакт</item>
    </plurals>
    <plurals name="group_member_number">
        <item quantity="other">%d пользователь(ей)</item>
        <item quantity="one">1 пользователь</item>
    </plurals>
    <plurals name="confirm_delete_conversation">
        <item quantity="other">Будет удалено бесед: %1$s</item>
        <item quantity="one">Будет удалена одна беседа</item>
    </plurals>
    <plurals name="notification_multiple">
        <item quantity="other">Непрочитанных сообщений: %d</item>
        <item quantity="one">Непрочитанных сообщений: %d.</item>
    </plurals>
    <plurals name="slide_duration">
        <item quantity="other">%s с</item>
        <item quantity="one">%s с</item>
        <item quantity="few">%s с</item>
    </plurals>
    <plurals name="search_results_title">
        <item quantity="other">Результатов для \"%2$s\": %1$s</item>
        <item quantity="one">Результатов для \"%2$s\": %1$s</item>
    </plurals>
    <plurals name="recipient_count">
        <item quantity="other">Людей: %1$s</item>
    </plurals>
    <plurals name="read_report_toast_msg">
        <item quantity="other">отправка %d отч. о прочтении</item>
        <item quantity="one">отправка %d отчета о прочтении</item>
    </plurals>
    <plurals name="message_view_selected_message_count">
        <item quantity="other">Выбрано: %d</item>
        <item quantity="one">Выбрано: %d</item>
    </plurals>
    <plurals name="group_messages_sending">
        <item quantity="other">%1$s сообщения об отправке...</item>
        <item quantity="one">%1$s отправка сообщений...</item>
    </plurals>
    <plurals name="group_messages_sent">
        <item quantity="other">%1$s отправлено сообщений.</item>
        <item quantity="one">%1$s сообщение было отправлено.</item>
    </plurals>
    <plurals name="group_messages_failed">
        <item quantity="other">%1$s сообщений не удалось отправить.</item>
        <item quantity="one">%1$s сообщение не удалось отправить.</item>
    </plurals>
    <plurals name="group_messages_address_title">
        <item quantity="other">%1$s получатели.</item>
        <item quantity="one">%1$s получатель.</item>
    </plurals>
</resources>


text:
package org.apache.camel.impl;

import org.apache.camel.AsyncCallback;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.spi.RouteContext;
import org.slf4j.MDC;

/**
 * This unit of work supports MDC.
 *
 * @version
 */
public class MDCUnitOfWork extends DefaultUnitOfWork {

    public static final String MDC_EXCHANGE_ID = "exchangeId";
    public static final String MDC_CORRELATION_ID = "correlationId";
    public static final String MDC_ROUTE_ID = "routeId";
    public static final String MDC_TRANSACTION_KEY = "transactionKey";

    public MDCUnitOfWork(Exchange exchange) {
        super(exchange);
        // must add exchange id in constructor
        MDC.put(MDC_EXCHANGE_ID, exchange.getExchangeId());
        // and add optional correlation id
        String corrId = exchange.getProperty(Exchange.CORRELATION_ID, String.class);
        if (corrId != null) {
            MDC.put(MDC_CORRELATION_ID, corrId);
        }
    }

    @Override
    public void stop() throws Exception {
        super.stop();
        // and remove when stopping
        clear();
    }

    @Override
    public void pushRouteContext(RouteContext routeContext) {
        MDC.put(MDC_ROUTE_ID, routeContext.getRoute().getId());
        super.pushRouteContext(routeContext);
    }

    @Override
    public RouteContext popRouteContext() {
        MDC.remove(MDC_ROUTE_ID);
        return super.popRouteContext();
    }

    @Override
    public void beginTransactedBy(Object key) {
        MDC.put(MDC_TRANSACTION_KEY, key.toString());
        super.beginTransactedBy(key);
    }

    @Override
    public void endTransactedBy(Object key) {
        MDC.remove(MDC_TRANSACTION_KEY);
        super.endTransactedBy(key);
    }

    @Override
    public AsyncCallback beforeProcess(Processor processor, Exchange exchange, AsyncCallback callback) {
        return new MDCCallback(callback);
    }

    @Override
    public void afterProcess(Processor processor, Exchange exchange, AsyncCallback callback, boolean doneSync) {
        if (!doneSync) {
            // must clear MDC on current thread as the exchange is being processed asynchronously
            // by another thread
            clear();
        }
    }

    /**
     * Clears information put on the MDC by this {@link MDCUnitOfWork}
     */
    public void clear() {
        MDC.remove(MDC_EXCHANGE_ID);
        MDC.remove(MDC_CORRELATION_ID);
        MDC.remove(MDC_ROUTE_ID);
    }

    @Override
    public String toString() {
        return "MDCUnitOfWork";
    }

    /**
     * {@link AsyncCallback} which preserves {@link org.slf4j.MDC} when
     * the asynchronous routing engine is being used.
     */
    private static final class MDCCallback implements AsyncCallback {

        private final AsyncCallback delegate;
        private final String exchangeId;
        private final String correlationId;
        private final String routeId;

        private MDCCallback(AsyncCallback delegate) {
            this.delegate = delegate;
            this.exchangeId = MDC.get(MDC_EXCHANGE_ID);
            this.correlationId = MDC.get(MDC_CORRELATION_ID);

            String routeId = MDC.get(MDC_ROUTE_ID);
            if (routeId != null) {
                // intern route id as this reduces memory allocations
                this.routeId = routeId.intern();
            } else {
                this.routeId = null;
            }
        }

        public void done(boolean doneSync) {
            if (!doneSync) {
                // when done asynchronously then restore information from previous thread
                if (exchangeId != null) {
                    MDC.put(MDC_EXCHANGE_ID, exchangeId);
                }
                if (correlationId != null) {
                    MDC.put(MDC_CORRELATION_ID, correlationId);
                }
                if (routeId != null) {
                    MDC.put(MDC_ROUTE_ID, routeId);
                }
            }
            delegate.done(doneSync);
        }

        @Override
        public String toString() {
            return delegate.toString();
        }
    }

}