text:
package jet

import (
	"bytes"
	"fmt"
	"runtime"
	"strconv"
	"strings"
)

func unquote(text string) (string, error) {
	return strconv.Unquote(text)
}

// Template is the representation of a single parsed template.
type Template struct {
	Name      string // name of the template represented by the tree.
	ParseName string // name of the top-level template during parsing, for error messages.

	set     *Set
	extends *Template
	imports []*Template

	processedBlocks map[string]*BlockNode
	passedBlocks    map[string]*BlockNode
	Root            *ListNode // top-level root of the tree.

	text string // text parsed to create the template (or its parent)

	// Parsing only; cleared after parse.
	lex       *lexer
	token     [3]item // three-token lookahead for parser.
	peekCount int
}

func (t *Template) String() (template string) {
	if t.extends != nil {
		if len(t.Root.Nodes) > 0 && len(t.imports) == 0 {
			template += fmt.Sprintf("{{extends %q}}", t.extends.ParseName)
		} else {
			template += fmt.Sprintf("{{extends %q}}", t.extends.ParseName)
		}
	}

	for k, _import := range t.imports {
		if t.extends == nil && k == 0 {
			template += fmt.Sprintf("{{import %q}}", _import.ParseName)
		} else {
			template += fmt.Sprintf("\n{{import %q}}", _import.ParseName)
		}
	}

	if t.extends != nil || len(t.imports) > 0 {
		if len(t.Root.Nodes) > 0 {
			template += "\n" + t.Root.String()
		}
	} else {
		template += t.Root.String()
	}
	return
}

func (t *Template) addBlocks(blocks map[string]*BlockNode) {
	if len(blocks) == 0 {
		return
	}
	if t.processedBlocks == nil {
		t.processedBlocks = make(map[string]*BlockNode)
	}
	for key, value := range blocks {
		t.processedBlocks[key] = value
	}
}

// next returns the next token.
func (t *Template) next() item {
	if t.peekCount > 0 {
		t.peekCount--
	} else {
		t.token[0] = t.lex.nextItem()
	}
	return t.token[t.peekCount]
}

// backup backs the input stream up one token.
func (t *Template) backup() {
	t.peekCount++
}

// backup2 backs the input stream up two tokens.
// The zeroth token is already there.
func (t *Template) backup2(t1 item) {
	t.token[1] = t1
	t.peekCount = 2
}

// backup3 backs the input stream up three tokens
// The zeroth token is already there.
func (t *Template) backup3(t2, t1 item) {
	// Reverse order: we're pushing back.
	t.token[1] = t1
	t.token[2] = t2
	t.peekCount = 3
}

// peek returns but does not consume the next token.
func (t *Template) peek() item {
	if t.peekCount > 0 {
		return t.token[t.peekCount-1]
	}
	t.peekCount = 1
	t.token[0] = t.lex.nextItem()
	return t.token[0]
}

// nextNonSpace returns the next non-space token.
func (t *Template) nextNonSpace() (token item) {
	for {
		token = t.next()
		if token.typ != itemSpace {
			break
		}
	}
	return token
}

// peekNonSpace returns but does not consume the next non-space token.
func (t *Template) peekNonSpace() (token item) {
	for {
		token = t.next()
		if token.typ != itemSpace {
			break
		}
	}
	t.backup()
	return token
}

// errorf formats the error and terminates processing.
func (t *Template) errorf(format string, args ...interface{}) {
	t.Root = nil
	format = fmt.Sprintf("template: %s:%d: %s", t.ParseName, t.lex.lineNumber(), format)
	panic(fmt.Errorf(format, args...))
}

// error terminates processing.
func (t *Template) error(err error) {
	t.errorf("%s", err)
}

// expect consumes the next token and guarantees it has the required type.
func (t *Template) expect(expectedType itemType, context, expected string) item {
	token := t.nextNonSpace()
	if token.typ != expectedType {
		t.unexpected(token, context, expected)
	}
	return token
}

func (t *Template) expectRightDelim(context string) item {
	return t.expect(itemRightDelim, context, "closing delimiter")
}

// expectOneOf consumes the next token and guarantees it has one of the required types.
func (t *Template) expectOneOf(expected1, expected2 itemType, context, expectedAs string) item {
	token := t.nextNonSpace()
	if token.typ != expected1 && token.typ != expected2 {
		t.unexpected(token, context, expectedAs)
	}
	return token
}

// unexpected complains about the token and terminates processing.
func (t *Template) unexpected(token item, context, expected string) {
	switch {
	case token.typ == itemImport,
		token.typ == itemExtends:
		t.errorf("parsing %s: unexpected keyword '%s' ('%s' statements must be at the beginning of the template)", context, token.val, token.val)
	case token.typ > itemKeyword:
		t.errorf("parsing %s: unexpected keyword '%s' (expected %s)", context, token.val, expected)
	default:
		t.errorf("parsing %s: unexpected token '%s' (expected %s)", context, token.val, expected)
	}
}

// recover is the handler that turns panics into returns from the top level of Parse.
func (t *Template) recover(errp *error) {
	e := recover()
	if e != nil {
		if _, ok := e.(runtime.Error); ok {
			panic(e)
		}
		if t != nil {
			t.lex.drain()
			t.stopParse()
		}
		*errp = e.(error)
	}
	return
}

func (s *Set) parse(name, text string, cacheAfterParsing bool) (t *Template, err error) {
	t = &Template{
		Name:         name,
		ParseName:    name,
		text:         text,
		set:          s,
		passedBlocks: make(map[string]*BlockNode),
	}
	defer t.recover(&err)

	lexer := lex(name, text, false)
	lexer.setDelimiters(s.leftDelim, s.rightDelim)
	lexer.run()
	t.startParse(lexer)
	t.parseTemplate(cacheAfterParsing)
	t.stopParse()

	if t.extends != nil {
		t.addBlocks(t.extends.processedBlocks)
	}

	for _, _import := range t.imports {
		t.addBlocks(_import.processedBlocks)
	}

	t.addBlocks(t.passedBlocks)

	return t, err
}

func (t *Template) expectString(context string) string {
	token := t.expectOneOf(itemString, itemRawString, context, "string literal")
	s, err := unquote(token.val)
	if err != nil {
		t.error(err)
	}
	return s
}

// parse is the top-level parser for a template, essentially the same
// It runs to EOF.
func (t *Template) parseTemplate(cacheAfterParsing bool) (next Node) {
	t.Root = t.newList(t.peek().pos)
	// {{ extends|import stringLiteral }}
	for t.peek().typ != itemEOF {
		delim := t.next()
		if delim.typ == itemText && strings.TrimSpace(delim.val) == "" {
			continue //skips empty text nodes
		}
		if delim.typ == itemLeftDelim {
			token := t.nextNonSpace()
			if token.typ == itemExtends || token.typ == itemImport {
				s := t.expectString("extends|import")
				if token.typ == itemExtends {
					if t.extends != nil {
						t.errorf("Unexpected extends clause: each template can only extend one template")
					} else if len(t.imports) > 0 {
						t.errorf("Unexpected extends clause: the 'extends' clause should come before all import clauses")
					}
					var err error
					t.extends, err = t.set.getSiblingTemplate(s, t.Name, cacheAfterParsing)
					if err != nil {
						t.error(err)
					}
				} else {
					tt, err := t.set.getSiblingTemplate(s, t.Name, cacheAfterParsing)
					if err != nil {
						t.error(err)
					}
					t.imports = append(t.imports, tt)
				}
				t.expect(itemRightDelim, "extends|import", "closing delimiter")
			} else {
				t.backup2(delim)
				break
			}
		} else {
			t.backup()
			break
		}
	}

	for t.peek().typ != itemEOF {
		switch n := t.textOrAction(); n.Type() {
		case nodeEnd, nodeElse, nodeContent:
			t.errorf("unexpected %s", n)
		default:
			t.Root.append(n)
		}
	}
	return nil
}

// startParse initializes the parser, using the lexer.
func (t *Template) startParse(lex *lexer) {
	t.Root = nil
	t.lex = lex
}

// stopParse terminates parsing.
func (t *Template) stopParse() {
	t.lex = nil
}

// IsEmptyTree reports whether this tree (node) is empty of everything but space.
func IsEmptyTree(n Node) bool {
	switch n := n.(type) {
	case nil:
		return true
	case *ActionNode:
	case *IfNode:
	case *ListNode:
		for _, node := range n.Nodes {
			if !IsEmptyTree(node) {
				return false
			}
		}
		return true
	case *RangeNode:
	case *IncludeNode:
	case *TextNode:
		return len(bytes.TrimSpace(n.Text)) == 0
	case *BlockNode:
	case *YieldNode:
	default:
		panic("unknown node: " + n.String())
	}
	return false
}

func (t *Template) blockParametersList(isDeclaring bool, context string) *BlockParameterList {
	block := &BlockParameterList{}

	t.expect(itemLeftParen, context, "opening parenthesis")
	for {
		var expression Expression
		next := t.nextNonSpace()
		if next.typ == itemIdentifier {
			identifier := next.val
			next2 := t.nextNonSpace()
			switch next2.typ {
			case itemComma, itemRightParen:
				block.List = append(block.List, BlockParameter{Identifier: identifier})
				next = next2
			case itemAssign:
				expression, next = t.parseExpression(context)
				block.List = append(block.List, BlockParameter{Identifier: identifier, Expression: expression})
			default:
				if !isDeclaring {
					switch next2.typ {
					case itemComma, itemRightParen:
					default:
						t.backup2(next)
						expression, next = t.parseExpression(context)
						block.List = append(block.List, BlockParameter{Expression: expression})
					}
				} else {
					t.unexpected(next2, context, "comma, assignment, or closing parenthesis")
				}
			}
		} else if !isDeclaring {
			switch next.typ {
			case itemComma, itemRightParen:
			default:
				t.backup()
				expression, next = t.parseExpression(context)
				block.List = append(block.List, BlockParameter{Expression: expression})
			}
		}

		if next.typ != itemComma {
			t.backup()
			break
		}
	}
	t.expect(itemRightParen, context, "closing parenthesis")
	return block
}

func (t *Template) parseBlock() Node {
	const context = "block clause"
	var pipe Expression

	name := t.expect(itemIdentifier, context, "name")
	bplist := t.blockParametersList(true, context)

	if t.peekNonSpace().typ != itemRightDelim {
		pipe = t.expression(context, "context")
	}

	t.expectRightDelim(context)

	list, end := t.itemList(nodeContent, nodeEnd)
	var contentList *ListNode

	if end.Type() == nodeContent {
		contentList, end = t.itemList(nodeEnd)
	}

	block := t.newBlock(name.pos, t.lex.lineNumber(), name.val, bplist, pipe, list, contentList)
	t.passedBlocks[block.Name] = block
	return block
}

func (t *Template) parseYield() Node {
	const context = "yield clause"

	var (
		pipe    Expression
		name    item
		bplist  *BlockParameterList
		content *ListNode
	)

	// parse block name
	name = t.nextNonSpace()
	if name.typ == itemContent {
		// content yield {{yield content}}
		if t.peekNonSpace().typ != itemRightDelim {
			pipe = t.expression(context, "content context")
		}
		t.expectRightDelim(context)
		return t.newYield(name.pos, t.lex.lineNumber(), "", nil, pipe, nil, true)
	} else if name.typ != itemIdentifier {
		t.unexpected(name, context, "block name")
	}

	// parse block parameters
	bplist = t.blockParametersList(false, context)

	// parse optional context & content
	typ := t.peekNonSpace().typ
	if typ == itemRightDelim {
		t.expectRightDelim(context)
	} else {
		if typ != itemContent {
			// parse context expression
			pipe = t.expression("yield", "context")
			typ = t.peekNonSpace().typ
		}
		if typ == itemRightDelim {
			t.expectRightDelim(context)
		} else if typ == itemContent {
			// parse content from following nodes (until {{end}})
			t.nextNonSpace()
			t.expectRightDelim(context)
			content, _ = t.itemList(nodeEnd)
		} else {
			t.unexpected(t.nextNonSpace(), context, "content keyword or closing delimiter")
		}
	}

	return t.newYield(name.pos, t.lex.lineNumber(), name.val, bplist, pipe, content, false)
}

func (t *Template) parseInclude() Node {
	var context Expression
	name := t.expression("include", "template name")
	if t.peekNonSpace().typ != itemRightDelim {
		context = t.expression("include", "context")
	}
	t.expectRightDelim("include invocation")
	return t.newInclude(name.Position(), t.lex.lineNumber(), name, context)
}

func (t *Template) parseReturn() Node {
	value := t.expression("return", "value")
	t.expectRightDelim("return")
	return t.newReturn(value.Position(), t.lex.lineNumber(), value)
}

// itemList:
//	textOrAction*
// Terminates at any of the given nodes, returned separately.
func (t *Template) itemList(terminatedBy ...NodeType) (list *ListNode, next Node) {
	list = t.newList(t.peekNonSpace().pos)
	for t.peekNonSpace().typ != itemEOF {
		n := t.textOrAction()
		for _, terminatorType := range terminatedBy {
			if n.Type() == terminatorType {
				return list, n
			}
		}
		list.append(n)
	}
	t.errorf("unexpected EOF")
	return
}

// textOrAction:
//	text | action
func (t *Template) textOrAction() Node {
	switch token := t.nextNonSpace(); token.typ {
	case itemText:
		return t.newText(token.pos, token.val)
	case itemLeftDelim:
		return t.action()
	default:
		t.unexpected(token, "input", "text or action")
	}
	return nil
}

func (t *Template) action() (n Node) {
	switch token := t.nextNonSpace(); token.typ {
	case itemInclude:
		return t.parseInclude()
	case itemBlock:
		return t.parseBlock()
	case itemEnd:
		return t.endControl()
	case itemYield:
		return t.parseYield()
	case itemContent:
		return t.contentControl()
	case itemIf:
		return t.ifControl()
	case itemElse:
		return t.elseControl()
	case itemRange:
		return t.rangeControl()
	case itemTry:
		return t.parseTry()
	case itemCatch:
		return t.parseCatch()
	case itemReturn:
		return t.parseReturn()
	}

	t.backup()
	action := t.newAction(t.peek().pos, t.lex.lineNumber())

	expr := t.assignmentOrExpression("command")
	if expr.Type() == NodeSet {
		action.Set = expr.(*SetNode)
		expr = nil
		if t.expectOneOf(itemSemicolon, itemRightDelim, "command", "semicolon or right delimiter").typ == itemSemicolon {
			expr = t.expression("command", "pipeline base expression")
		}
	}
	if expr != nil {
		action.Pipe = t.pipeline("command", expr)
	}
	return action
}

func (t *Template) logicalExpression(context string) (Expression, item) {
	left, endtoken := t.comparativeExpression(context)
	for endtoken.typ == itemAnd || endtoken.typ == itemOr {
		right, rightendtoken := t.comparativeExpression(context)
		left, endtoken = t.newLogicalExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
	}
	return left, endtoken
}

func (t *Template) parseExpression(context string) (Expression, item) {
	expression, endtoken := t.logicalExpression(context)
	if endtoken.typ == itemTernary {
		var left, right Expression
		left, endtoken = t.parseExpression(context)
		if endtoken.typ != itemColon {
			t.unexpected(endtoken, "ternary expression", "colon in ternary expression")
		}
		right, endtoken = t.parseExpression(context)
		expression = t.newTernaryExpr(expression.Position(), t.lex.lineNumber(), expression, left, right)
	}
	return expression, endtoken
}

func (t *Template) comparativeExpression(context string) (Expression, item) {
	left, endtoken := t.numericComparativeExpression(context)
	for endtoken.typ == itemEquals || endtoken.typ == itemNotEquals {
		right, rightendtoken := t.numericComparativeExpression(context)
		left, endtoken = t.newComparativeExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
	}
	return left, endtoken
}

func (t *Template) numericComparativeExpression(context string) (Expression, item) {
	left, endtoken := t.additiveExpression(context)
	for endtoken.typ >= itemGreat && endtoken.typ <= itemLessEquals {
		right, rightendtoken := t.additiveExpression(context)
		left, endtoken = t.newNumericComparativeExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
	}
	return left, endtoken
}

func (t *Template) additiveExpression(context string) (Expression, item) {
	left, endtoken := t.multiplicativeExpression(context)
	for endtoken.typ == itemAdd || endtoken.typ == itemMinus {
		right, rightendtoken := t.multiplicativeExpression(context)
		left, endtoken = t.newAdditiveExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
	}
	return left, endtoken
}

func (t *Template) multiplicativeExpression(context string) (left Expression, endtoken item) {
	left, endtoken = t.unaryExpression(context)
	for endtoken.typ >= itemMul && endtoken.typ <= itemMod {
		right, rightendtoken := t.unaryExpression(context)
		left, endtoken = t.newMultiplicativeExpr(left.Position(), t.lex.lineNumber(), left, right, endtoken), rightendtoken
	}

	return left, endtoken
}

func (t *Template) unaryExpression(context string) (Expression, item) {
	next := t.nextNonSpace()
	switch next.typ {
	case itemNot:
		expr, endToken := t.comparativeExpression(context)
		return t.newNotExpr(expr.Position(), t.lex.lineNumber(), expr), endToken
	case itemMinus, itemAdd:
		return t.newAdditiveExpr(next.pos, t.lex.lineNumber(), nil, t.operand("additive expression"), next), t.nextNonSpace()
	default:
		t.backup()
	}
	operand := t.operand(context)
	return operand, t.nextNonSpace()
}

func (t *Template) assignmentOrExpression(context string) (operand Expression) {
	t.peekNonSpace()
	line := t.lex.lineNumber()
	var right, left []Expression

	var isSet bool
	var isLet bool
	var returned item
	operand, returned = t.parseExpression(context)
	pos := operand.Position()
	if returned.typ == itemComma || returned.typ == itemAssign {
		isSet = true
	} else {
		if operand == nil {
			t.unexpected(returned, context, "operand")
		}
		t.backup()
		return operand
	}

	if isSet {
	leftloop:
		for {
			switch operand.Type() {
			case NodeField, NodeChain, NodeIdentifier, NodeUnderscore:
				left = append(left, operand)
			default:
				t.errorf("unexpected node in assign")
			}

			switch returned.typ {
			case itemComma:
				operand, returned = t.parseExpression(context)
			case itemAssign:
				isLet = returned.val == ":="
				break leftloop
			default:
				t.unexpected(returned, "assignment", "comma or assignment")
			}
		}

		if isLet {
			for _, operand := range left {
				if operand.Type() != NodeIdentifier && operand.Type() != NodeUnderscore {
					t.errorf("unexpected node type %s in variable declaration", operand)
				}
			}
		}

		for {
			operand, returned = t.parseExpression("assignment")
			right = append(right, operand)
			if returned.typ != itemComma {
				t.backup()
				break
			}
		}

		var isIndexExprGetLookup bool

		if context == "range" {
			if len(left) > 2 || len(right) > 1 {
				t.errorf("unexpected number of operands in assign on range")
			}
		} else {
			if len(left) != len(right) {
				if len(left) == 2 && len(right) == 1 && right[0].Type() == NodeIndexExpr {
					isIndexExprGetLookup = true
				} else {
					t.errorf("unexpected number of operands in assign on range")
				}
			}
		}
		operand = t.newSet(pos, line, isLet, isIndexExprGetLookup, left, right)
		return

	}
	return
}

func (t *Template) expression(context, as string) Expression {
	expr, tk := t.parseExpression(context)
	if expr == nil {
		t.unexpected(tk, context, as)
	}
	t.backup()
	return expr
}

func (t *Template) pipeline(context string, baseExprMutate Expression) (pipe *PipeNode) {
	pos := t.peekNonSpace().pos
	pipe = t.newPipeline(pos, t.lex.lineNumber())

	if baseExprMutate == nil {
		pipe.errorf("parsing pipeline: first expression cannot be nil")
	}
	pipe.append(t.command(baseExprMutate))

	for {
		token := t.expectOneOf(itemPipe, itemRightDelim, "pipeline", "pipe or right delimiter")
		if token.typ == itemRightDelim {
			break
		}
		token = t.nextNonSpace()
		switch token.typ {
		case itemField, itemIdentifier:
			t.backup()
			pipe.append(t.command(nil))
		default:
			t.unexpected(token, "pipeline", "field or identifier")
		}
	}

	return
}

func (t *Template) command(baseExpr Expression) *CommandNode {
	cmd := t.newCommand(t.peekNonSpace().pos)

	if baseExpr == nil {
		baseExpr = t.expression("command", "name")
	}

	if baseExpr.Type() == NodeCallExpr {
		call := baseExpr.(*CallExprNode)
		cmd.CallExprNode = *call
		return cmd
	}

	cmd.BaseExpr = baseExpr

	next := t.nextNonSpace()
	switch next.typ {
	case itemColon:
		cmd.CallArgs = t.parseArguments()
	default:
		t.backup()
	}

	if cmd.BaseExpr == nil {
		t.errorf("empty command")
	}

	return cmd
}

// operand:
//	term .Field*
// An operand is a space-separated component of a command,
// a term possibly followed by field accesses.
// A nil return means the next item is not an operand.
func (t *Template) operand(context string) Expression {
	node := t.term()
	if node == nil {
		t.unexpected(t.next(), context, "term")
	}
RESET:
	if t.peek().typ == itemField {
		chain := t.newChain(t.peek().pos, node)
		for t.peekNonSpace().typ == itemField {
			chain.Add(t.next().val)
		}
		// Compatibility with original API: If the term is of type NodeField
		// or NodeVariable, just put more fields on the original.
		// Otherwise, keep the Chain node.
		// Obvious parsing errors involving literal values are detected here.
		// More complex error cases will have to be handled at execution time.
		switch node.Type() {
		case NodeField:
			node = t.newField(chain.Position(), chain.String())
		case NodeBool, NodeString, NodeNumber, NodeNil:
			t.errorf("unexpected . after term %q", node.String())
		default:
			node = chain
		}
	}
	nodeTYPE := node.Type()
	if nodeTYPE == NodeIdentifier ||
		nodeTYPE == NodeCallExpr ||
		nodeTYPE == NodeField ||
		nodeTYPE == NodeChain ||
		nodeTYPE == NodeIndexExpr {
		switch t.nextNonSpace().typ {
		case itemLeftParen:
			callExpr := t.newCallExpr(node.Position(), t.lex.lineNumber(), node)
			callExpr.CallArgs = t.parseArguments()
			t.expect(itemRightParen, "call expression", "closing parenthesis")
			node = callExpr
			goto RESET
		case itemLeftBrackets:
			base := node
			var index Expression
			var next item

			//found colon is slice expression
			if t.peekNonSpace().typ != itemColon {
				index, next = t.parseExpression("index|slice expression")
			} else {
				next = t.nextNonSpace()
			}

			switch next.typ {
			case itemColon:
				var endIndex Expression
				if t.peekNonSpace().typ != itemRightBrackets {
					endIndex = t.expression("slice expression", "end indexß")
				}
				node = t.newSliceExpr(node.Position(), node.line(), base, index, endIndex)
			case itemRightBrackets:
				node = t.newIndexExpr(node.Position(), node.line(), base, index)
				fallthrough
			default:
				t.backup()
			}

			t.expect(itemRightBrackets, "index expression", "closing bracket")
			goto RESET
		default:
			t.backup()
		}
	}
	return node
}

func (t *Template) parseArguments() (args CallArgs) {
	context := "call expression argument list"
	args.Exprs = []Expression{}
loop:
	for {
		peek := t.peekNonSpace()
		if peek.typ == itemRightParen {
			break
		}
		var (
			expr     Expression
			endtoken item
		)
		expr, endtoken = t.parseExpression(context)
		if expr.Type() == NodeUnderscore {
			// slot for piped argument
			if args.HasPipeSlot {
				t.errorf("found two pipe slot markers ('_') for the same function call")
			}
			args.HasPipeSlot = true
		}
		args.Exprs = append(args.Exprs, expr)
		switch endtoken.typ {
		case itemComma:
			// continue with closing parens (allowed because of multiline syntax) or next arg
		default:
			t.backup()
			break loop
		}
	}
	return
}

func (t *Template) parseControl(allowElseIf bool, context string) (pos Pos, line int, set *SetNode, expression Expression, list, elseList *ListNode) {
	line = t.lex.lineNumber()

	expression = t.assignmentOrExpression(context)
	pos = expression.Position()
	if expression.Type() == NodeSet {
		set = expression.(*SetNode)
		if context != "range" {
			t.expect(itemSemicolon, context, "semicolon between assignment and expression")
			expression = t.expression(context, "expression after assignment")
		} else {
			expression = nil
		}
	}

	t.expectRightDelim(context)
	var next Node
	list, next = t.itemList(nodeElse, nodeEnd)
	if next.Type() == nodeElse {
		if allowElseIf && t.peek().typ == itemIf {
			// Special case for "else if". If the "else" is followed immediately by an "if",
			// the elseControl will have left the "if" token pending. Treat
			//	{{if a}}_{{else if b}}_{{end}}
			// as
			//	{{if a}}_{{else}}{{if b}}_{{end}}{{end}}.
			// To do this, parse the if as usual and stop at it {{end}}; the subsequent{{end}}
			// is assumed. This technique works even for long if-else-if chains.
			t.next() // Consume the "if" token.
			elseList = t.newList(next.Position())
			elseList.append(t.ifControl())
			// Do not consume the next item - only one {{end}} required.
		} else {
			elseList, next = t.itemList(nodeEnd)
		}
	}
	return pos, line, set, expression, list, elseList
}

// If:
//	{{if expression}} itemList {{end}}
//	{{if expression}} itemList {{else}} itemList {{end}}
// If keyword is past.
func (t *Template) ifControl() Node {
	return t.newIf(t.parseControl(true, "if"))
}

// Range:
//	{{range expression}} itemList {{end}}
//	{{range expression}} itemList {{else}} itemList {{end}}
// Range keyword is past.
func (t *Template) rangeControl() Node {
	return t.newRange(t.parseControl(false, "range"))
}

// End:
//	{{end}}
// End keyword is past.
func (t *Template) endControl() Node {
	return t.newEnd(t.expectRightDelim("end").pos)
}

// Content:
//	{{content}}
// Content keyword is past.
func (t *Template) contentControl() Node {
	return t.newContent(t.expectRightDelim("content").pos)
}

// Else:
//	{{else}}
// Else keyword is past.
func (t *Template) elseControl() Node {
	// Special case for "else if".
	peek := t.peekNonSpace()
	if peek.typ == itemIf {
		// We see "{{else if ... " but in effect rewrite it to {{else}}{{if ... ".
		return t.newElse(peek.pos, t.lex.lineNumber())
	}
	return t.newElse(t.expectRightDelim("else").pos, t.lex.lineNumber())
}

// Try-catch:
//	{{try}}
//    itemList
//  {{catch <ident>}}
//    itemList
//  {{end}}
// try keyword is past.
func (t *Template) parseTry() *TryNode {
	var recov *catchNode
	line := t.lex.lineNumber()
	pos := t.expectRightDelim("try").pos
	list, next := t.itemList(nodeCatch, nodeEnd)
	if next.Type() == nodeCatch {
		recov = next.(*catchNode)
	}

	return t.newTry(pos, line, list, recov)
}

// catch:
//  {{catch <ident>}}
//    itemList
//  {{end}}
// catch keyword is past.
func (t *Template) parseCatch() *catchNode {
	line := t.lex.lineNumber()
	var errVar *IdentifierNode
	peek := t.peekNonSpace()
	if peek.typ != itemRightDelim {
		_errVar := t.term()
		if typ := _errVar.Type(); typ != NodeIdentifier {
			t.errorf("unexpected node type '%s' in catch", typ)
		}
		errVar = _errVar.(*IdentifierNode)
	}
	t.expectRightDelim("catch")
	list, _ := t.itemList(nodeEnd)
	return t.newCatch(peek.pos, line, errVar, list)
}

// term:
//	literal (number, string, nil, boolean)
//	function (identifier)
//	.
//	.Field
//	variable
//	'(' expression ')'
// A term is a simple "expression".
// A nil return means the next item is not a term.
func (t *Template) term() Node {
	switch token := t.nextNonSpace(); token.typ {
	case itemError:
		t.errorf("%s", token.val)
	case itemIdentifier:
		return t.newIdentifier(token.val, token.pos, t.lex.lineNumber())
	case itemUnderscore:
		return t.newUnderscore(token.pos, t.lex.lineNumber())
	case itemNil:
		return t.newNil(token.pos)
	case itemField:
		return t.newField(token.pos, token.val)
	case itemBool:
		return t.newBool(token.pos, token.val == "true")
	case itemCharConstant, itemComplex, itemNumber:
		number, err := t.newNumber(token.pos, token.val, token.typ)
		if err != nil {
			t.error(err)
		}
		return number
	case itemLeftParen:
		pipe := t.expression("parenthesized expression", "expression")
		if token := t.next(); token.typ != itemRightParen {
			t.unexpected(token, "parenthesized expression", "closing parenthesis")
		}
		return pipe
	case itemString, itemRawString:
		s, err := unquote(token.val)
		if err != nil {
			t.error(err)
		}
		return t.newString(token.pos, token.val, s)
	}
	t.backup()
	return nil
}


text:
This project acts as [Spring Boot starter](http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-maven-parent-pom)
for web applications which want to leverage the MarkLogic database server
as their central repository for storing and searching data and documents.

## Use the starter in your Maven project

To make use of the Spring Boot starter for MarkLogic in your
own Maven-based project, please add in the `dependencies`
section the following dependency:

    <dependency>
        <groupId>de.nava</groupId>
        <artifactId>spring-boot-starter-marklogic</artifactId>
        <version>0.1.3</version>
    </dependency>

Add the following section to your `repositories` element to allow Maven
to retrieve the POM and jar file via github:

    <repository>
        <id>nikos-spring-boot-starter-marklogic</id>
        <url>https://raw.github.com/nikos/spring-boot-starter-marklogic/mvn-repo/</url>
    </repository>

## Use the starter in your Gradle project

Inside your `dependencies` please add

    compile("de.nava:spring-boot-starter-marklogic:0.1.3")

Pluse add the link to the location where to resolve this dependency as
part of `repositories` section:

    maven { url "https://raw.github.com/nikos/spring-boot-starter-marklogic/mvn-repo/" }

## Sample project using this Spring Boot Starter

If you are interested in a real-world project making use of the MarkLogic Spring Boot starter please visit the [wm14](https://github.com/jojrg/wm14) github project.

redpajama_set_name: RedPajamaGithub


text:
package org.apache.pig.parser;

import org.antlr.runtime.Token;
import org.antlr.runtime.tree.CommonTreeAdaptor;

public class PigParserNodeAdaptor extends CommonTreeAdaptor {

    private String source;

    private int lineOffset;

    PigParserNodeAdaptor(String source, int lineOffset) {
        this.source = source;
        this.lineOffset = lineOffset;
    }

    @Override
    public Object create(Token t) {
        return new PigParserNode(t, source, lineOffset);
    }

}


text:
package demo.controller;

import org.springframework.web.bind.annotation.ModelAttribute;

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

/**
 * Created by bonismo@hotmail.com
 * 下午4:21 on 16/6/28.
 */
public class BaseController {
    HttpServletRequest request;
    HttpServletResponse response;
    HttpSession session;
    ServletContext application;

    @ModelAttribute
    private void set(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        session = request.getSession();
        application = request.getServletContext();
    }
}


text:
package cli

import (
	"bytes"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"os"
	"sync"

	"github.com/flynn/flynn/Godeps/_workspace/src/github.com/docker/docker/pkg/term"
	"github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-docopt"
	tuf "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-tuf/client"
	"github.com/flynn/flynn/Godeps/_workspace/src/gopkg.in/inconshreveable/log15.v2"
	"github.com/flynn/flynn/pinkerton/layer"
	"github.com/flynn/flynn/pkg/cluster"
	"github.com/flynn/flynn/pkg/exec"
)

func init() {
	Register("update", runUpdate, `
usage: flynn-host update [--driver=<name>] [--root=<path>] [--repository=<uri>] [--tuf-db=<path>]

Options:
  -d --driver=<name>       image storage driver [default: aufs]
  -r --root=<path>         image storage root [default: /var/lib/docker]
  -u --repository=<uri>    image repository URI [default: https://dl.flynn.io/tuf]
  -t --tuf-db=<path>       local TUF file [default: /etc/flynn/tuf.db]

Update Flynn components`)
}

func runUpdate(args *docopt.Args) error {
	log := log15.New()

	// create and update a TUF client
	log.Info("initializing TUF client")
	local, err := tuf.FileLocalStore(args.String["--tuf-db"])
	if err != nil {
		log.Error("error creating local TUF client", "err", err)
		return err
	}
	remote, err := tuf.HTTPRemoteStore(args.String["--repository"], tufHTTPOpts("updater"))
	if err != nil {
		log.Error("error creating remote TUF client", "err", err)
		return err
	}
	client := tuf.NewClient(local, remote)

	log.Info("updating TUF data")
	if _, err := client.Update(); err != nil && !tuf.IsLatestSnapshot(err) {
		log.Error("error updating TUF client", "err", err)
		return err
	}

	// read the TUF db so we can pass it to hosts
	log.Info("reading TUF database")
	tufDB, err := ioutil.ReadFile(args.String["--tuf-db"])
	if err != nil {
		log.Error("error reading the TUF database", "err", err)
		return err
	}

	log.Info("getting host list")
	clusterClient, err := cluster.NewClient()
	if err != nil {
		log.Error("error creating cluster client", "err", err)
		return err
	}
	hosts, err := clusterClient.ListHosts()
	if err != nil {
		log.Error("error getting host list", "err", err)
		return err
	}
	if len(hosts) == 0 {
		return errors.New("no hosts found")
	}

	log.Info("pulling images on all hosts")
	images := make(map[string]string)
	var imageMtx sync.Mutex
	hostErrs := make(chan error)
	for _, h := range hosts {
		go func(hostID string) {
			log := log.New("host", hostID)

			log.Info("connecting to host")
			host, err := clusterClient.DialHost(hostID)
			if err != nil {
				log.Error("error connecting to host", "err", err)
				hostErrs <- err
				return
			}

			log.Info("pulling images")
			ch := make(chan *layer.PullInfo)
			stream, err := host.PullImages(
				args.String["--repository"],
				args.String["--driver"],
				args.String["--root"],
				bytes.NewReader(tufDB),
				ch,
			)
			if err != nil {
				log.Error("error pulling images", "err", err)
				hostErrs <- err
				return
			}
			defer stream.Close()
			for info := range ch {
				if info.Type == layer.TypeLayer {
					continue
				}
				log.Info("pulled image", "name", info.Repo)
				imageURI := fmt.Sprintf("%s?name=%s&id=%s", args.String["--repository"], info.Repo, info.ID)
				imageMtx.Lock()
				images[info.Repo] = imageURI
				imageMtx.Unlock()
			}
			hostErrs <- stream.Err()
		}(h.ID)
	}
	var hostErr error
	for _, h := range hosts {
		if err := <-hostErrs; err != nil {
			log.Error("error pulling images", "host", h.ID, "err", err)
			hostErr = err
			continue
		}
		log.Info("images pulled successfully", "host", h.ID)
	}
	if hostErr != nil {
		return hostErr
	}

	updaterImage, ok := images["flynn/updater"]
	if !ok {
		e := "missing flynn/updater image"
		log.Error(e)
		return errors.New(e)
	}
	imageJSON, err := json.Marshal(images)
	if err != nil {
		log.Error("error encoding images", "err", err)
		return err
	}

	// use a flag to determine whether to use a TTY log formatter because actually
	// assigning a TTY to the job causes reading images via stdin to fail.
	cmd := exec.Command(exec.DockerImage(updaterImage), fmt.Sprintf("--tty=%t", term.IsTerminal(os.Stdout.Fd())))
	cmd.Stdin = bytes.NewReader(imageJSON)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		return err
	}
	log.Info("update complete")
	return nil
}


text:
package org.gradle.api.internal.file.pattern;

public class FixedStepPathMatcher implements PathMatcher {
    private final PatternStep step;
    private final PathMatcher next;
    private final int minSegments;
    private final int maxSegments;

    public FixedStepPathMatcher(PatternStep step, PathMatcher next) {
        this.step = step;
        this.next = next;
        minSegments = 1 + next.getMinSegments();
        maxSegments = next.getMaxSegments() == Integer.MAX_VALUE ? Integer.MAX_VALUE : next.getMaxSegments() + 1;
    }

    @Override
    public String toString() {
        return "{fixed-step: " + step + ", next: " + next + "}";
    }

    public int getMinSegments() {
        return minSegments;
    }

    public int getMaxSegments() {
        return maxSegments;
    }

    public boolean matches(String[] segments, int startIndex) {
        int remaining = segments.length - startIndex;
        if (remaining < minSegments || remaining > maxSegments) {
            return false;
        }
        if (!step.matches(segments[startIndex])) {
            return false;
        }
        return next.matches(segments, startIndex + 1);
    }

    public boolean isPrefix(String[] segments, int startIndex) {
        if (startIndex == segments.length) {
            // Empty path, might match when more elements added
            return true;
        }
        if (!step.matches(segments[startIndex])) {
            // Does not match element, will never match when more elements added
            return false;
        }
        if (startIndex +1 == segments.length) {
            // End of path, might match when more elements added
            return true;
        }
        return next.isPrefix(segments, startIndex + 1);
    }
}


text:
Will "subscribe" to a web RSS/Atom/JSON feed and emit any new items it reads from it. The events are in the form of

`*::name::item`

Where `name` is the name of the feed. So if you are using the example [`config.json`](/fent/hook.io-feedsub/tree/master/examples/config.json) that looks like this

```javascript
{
  "feeds": [
    {
      "name": "cnn",
      "url": "http://rss.cnn.com/rss/cnn_latest.rss",
      "interval": 10,
      "emitOnStart": false
    }
  ]
}
```

Programatically, this is how you would listen for new feed items..

```javascript
hook.on('*::cnn:item', function(item) {
  console.log('New Story!:', item.title);
});

hook.on('*::item', function(feed) {
  console.log('New Story from: ', feed.name);
  console.log(feed.item);
});
```

It uses [feedsub](https://github.com/fent/node-feedsub) to read feeds. Take a look at its constructor API for all the options that can be passed to it.

# Usage

```bash
hookio-feedsub
```

# Install

```bash
npm -g install hook.io-feedsub
```

# Tests

The single test is written with [vows](http://vowsjs.org/)

```bash
npm test
```

# Licence

MIT


text:
(function () { 'use strict';

    var UG = (function () {
        function UG(numberOfVertices) {
            this.numberOfVertices = numberOfVertices;
            this.vertices = [];
            this.adjacencyList = [];
            this.init();
        }

        var Vertex = (function () {
            function Vertex(id) {
                this.id = id;
                this.visited = false;
                this.componentId = 0;
            }
            return Vertex;
        })();

        UG.prototype = {
            constructor: UG,

            init: function () {
                for (var v = 1; v <= this.numberOfVertices; v++) {
                    this.vertices[v] = new Vertex(v);
                    this.adjacencyList[v] = [];
                }
            },

            buildAdjacencyList: function (edges) {
                for (var i = 0; i < edges.length; i++) {
                    var from = parseInt(edges[i].split(' ')[0]);
                    var to = parseInt(edges[i].split(' ')[1]);
                    this.addEdge(from, to);
                }
            },

            addEdge: function (from, to) {
                var vertexFrom = this.vertices[from];
                var vertexTo = this.vertices[to];
                if (this.adjacencyList[vertexFrom.id].indexOf(vertexTo.id) === -1) {
                    this.adjacencyList[vertexFrom.id].push(vertexTo);
                }
                if (this.adjacencyList[vertexTo.id].indexOf(vertexFrom.id) === -1) {
                    this.adjacencyList[vertexTo.id].push(vertexFrom);
                }
            },

            dfs: function () {
                var numberOfComponents = 0;
                for (var v = 1; v <= this.numberOfVertices; v++) {
                    var currentVertex = this.vertices[v];
                    if (currentVertex.visited === false) {
                        this.explore(currentVertex, ++numberOfComponents);
                    }
                }
                return numberOfComponents;
            },

            explore: function (vertex, componentId) {
                vertex.visited = true;
                vertex.componentId = componentId;
                for (var i = 0; i < this.adjacencyList[vertex.id].length; i++) {
                    var currentVertex = this.adjacencyList[vertex.id][i];
                    if (currentVertex instanceof Vertex && currentVertex.visited === false) {
                        this.explore(currentVertex, componentId);
                    }
                }
            }
        };

        return UG;
    })();

    ////////////////////////////////

    var fs = require('fs');
    var input = (process.argv.length === 3) ? process.argv[2] : '/dev/stdin';
    var data = fs.readFileSync(input, 'utf8');

    var lines = data.match(/[^\r\n]+/g);

    var verticesEdges = lines.shift();
    var numberOfVertices = parseInt(verticesEdges.split(' ')[0]);

    var ug = new UG(numberOfVertices);
    ug.buildAdjacencyList(lines);
    console.log(ug.dfs());

})();


text:
[![Build Status](https://travis-ci.org/charles-oder/rest-fetcher-swift.svg?branch=master)](https://travis-ci.org/charles-oder/rest-fetcher-swift)
[![Version](https://img.shields.io/cocoapods/v/RestFetcher.svg?style=flat)](http://cocoapods.org/pods/RestFetcher)
[![Swift](https://img.shields.io/badge/Swift-4-orange.svg)](https://swift.org)
[![Xcode](https://img.shields.io/badge/Xcode-9-blue.svg)](https://developer.apple.com/xcode)
[![License](https://img.shields.io/cocoapods/l/RestFetcher.svg?style=flat)](http://cocoapods.org/pods/RestFetcher)
[![Platform](https://img.shields.io/cocoapods/p/RestFetcher.svg?style=flat)](http://cocoapods.org/pods/RestFetcher)

## Usage

To run the example project, clone the repo, and run `pod install` from the Example directory first.

## Requirements

## Installation

RestFetcher is available through [CocoaPods](http://cocoapods.org). To install
it, simply add the following line to your Podfile:

```ruby
pod "RestFetcher"
```
## Usage

# RFRequest
RFRequest<T: RFDecodable>
This is a base intended to be extended to support a family of REST requests. T defines the class of the response to be generated by each request.

You may customize each request and any child requests by overriding the following:

```swift
var logger: RFLogger
default = RFConsoleLogger
Allows child classes to inject their own logging framework with any object that conforms to the RFLogger protocol

var timeout: TimeInterval
default = 30
Allows child classes to modify the amount of time a request will wait for a response.

var keysToScrub: [String]
default = ["password"]
Allows child classes to define what JSON keys are obscured when logged

var restMethod: RFMethod
default = .get
Allows child classes to define the rest method to use (e.g GET, POST, PUT, DELETE, etc.)

var domain: String
Allows child classes to define the root domain of their REST service (e.g. https://google.com)

var rootPath: String
Allows child classes to defile the root api path for their REST service (e.g. /api/v1)

var pathResource: String
Allows child classes to define the restful resource path for each endpoint (e.g. /user/auth)

var queryArguments: [String: String]
Allows child classes to define the list of query arguments to include in the request URL
All keys and values will be URL encoded by the framework

var requestBody: String
Allows child classes to set the body of the request (i.e. JSON string, http url ecoded string)

var requestHeaders: [String: String]
Allows child classes to define the request headers to be sent to the server

func createResponse(responseTime: Double, code: Int, headers: [String: String], data: Data?) -> T.ResponseType?
default = instance of generic type provided from response string
Allows child classes to perform additional processing on response objects before reporting success
responseTime - The amount of time in seconds the response took
code - the response code reported by the service
headers - a key-value mapping of response headers
data - the raw data sent by the service response
```

# Invoking a request

```swift
let request = MyRequest()
request.successCallback = { code, response in // process response }
request.errorCallback = { error in // process error }
request.setCustomRequestVariables() // set any arguments for the request defined by the subclass
request.fetch()
```

# Response Wrapper Types
This library is wquipped to handle most kinds of responses, but users can define additional behavior by implementing the RFDecodable protocol

```swift
associatedType ResponseType // the generic type that this response will return in callbacks
acceptType: String? // the value to auto-inject into the Accept http header
object: ResponseType // the value of the response
init?(data: Data) // an init method for generating the response object
```

# Included Response Wrappers
```swift
RFVoidResponse // for services that are expected to return no body
RFDataResponse // for services that are expected to return binary data (e.g. files, images, etc.)
RFStringResponse // for services that are expected to return raw string data
RFDecodableResponse<T: Decodable> // for services that return JSON requres a Decodable object to decode the JSON into
RFRawResponse<T> // for responses where the user wishes to generate the response by overriding createResponse()
```
## Author

Charles Oder, charles@oder.us

## License

RestFetcher is available under the MIT license. See the LICENSE file for more info.


text:
Actor::Actor() :
cocos2d::Node(),
body_(nullptr),
rightLeg_(nullptr),
leftLeg_(nullptr),
direction_(),
walking_(false)
{}

Actor *Actor::create()
{
    Actor *actor = new Actor();

    if (actor && actor->init()) {
        return actor;
    }
    CC_SAFE_DELETE(actor);
    return nullptr;
}

bool Actor::init()
{
    if (!cocos2d::Node::init()) {
        return false;
    }

    leftLeg_ = cocos2d::Sprite::createWithSpriteFrameName("playerGreen_leg.png");
    leftLeg_->setPosition(cocos2d::Point(leftLeg_->getContentSize().height, -leftLeg_->getContentSize().width/2.0f));
    addChild(leftLeg_);

    rightLeg_ = cocos2d::Sprite::createWithSpriteFrameName("playerGreen_leg.png");
    rightLeg_->setPosition(cocos2d::Point(rightLeg_->getContentSize().height, rightLeg_->getContentSize().width/2.0f));
    addChild(rightLeg_);

    body_ = cocos2d::Sprite::createWithSpriteFrameName("playerGreen5.png");
    addChild(body_);

    return true;
}

void Actor::update()
{
    // toggle legs visiblity
}

void Actor::startWalking()
{
    walking_ = true;
}


text:
struct Tracer
{
	char const * m_filename;
	unsigned m_line;

	Tracer(char const * filename, unsigned const line) noexcept
		: m_filename(filename)
		, m_line(line)
	{

	}

	void operator()(wchar_t const * format, ...) const noexcept
	{
		wchar_t buffer[512];
		auto count = swprintf_s(buffer, L"%S(%d): ", m_filename, m_line);

		ASSERT(-1 != count);

		va_list args;
		va_start(args, format);
		ASSERT(-1 != _vsnwprintf_s(buffer + count, _countof(buffer) - count, _countof(buffer) - count - 1, format, args));
		va_end(args);

		OutputDebugString(buffer);
	}
};
#endif

#ifdef _DEBUG
#define TRACE Tracer(__FILE__, __LINE__)
#else
#define TRACE __noop
#endif

#ifdef _DEBUG
#define VERIFY ASSERT
#else
#define VERIFY(expression) (expression)
#endif

#ifdef _DEBUG
#define VERIFY_SUCCEEDED(expression) ASSERT(SUCCEEDED(expression))
#else
#define VERIFY_SUCCEEDED(expression) (expression)
#endif


text:
package soy;

import com.github.mati1979.play.soyplugin.global.runtime.RuntimeDataResolver;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Maps;
import com.google.template.soy.data.SoyMapData;
import controllers.MyAssets;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import play.Logger;
import play.Play;
import play.mvc.Http;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by mati on 30/05/2014.
 */
public class AssetsRuntimeResolver implements RuntimeDataResolver {

    private final static Pattern FILE_PATTERN = Pattern.compile(".+/public/(.+)");

    private PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();

    private final static Map<String, String> cache = Maps.newConcurrentMap();

    @PostConstruct
    public void init() {
        if (Play.isProd()) {
            Logger.debug("creating static assets (md5)...");
            final Stopwatch stopwatch = Stopwatch.createStarted();
            try {
                final Resource[] resources = pathMatchingResourcePatternResolver.getResources("classpath*:public/**/*.md5");
                Arrays.asList(resources).stream()
                        .filter(resource -> resource instanceof UrlResource)
                        .map(resource -> (UrlResource) resource)
                        .forEach(resource -> {
                            final Matcher matcher = FILE_PATTERN.matcher(resource.toString());
                            if (matcher.find()) {
                                final String asset = matcher.group(1).replace(".md5]", "");
                                final String key = "assets." + asset.replace("/", ".");
                                String versioned = MyAssets.versioned(asset);
                                Logger.info(String.format("key:%s - value:%s", key, versioned));
                                cache.put(key, versioned);
                            }
                        });
            } catch (IOException e) {
                throw new RuntimeException("failed to inject static md5 data", e);
            }
            stopwatch.stop();
            //Logger.debug("static assets generation took:" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
        }
    }

    @Override
    public void resolveData(Http.Request request, Http.Response response, Map<String, ? extends Object> model, SoyMapData root) {
        final Stopwatch stopwatch = Stopwatch.createStarted();
        if (Play.isDev() || Play.isTest()) {
            final File dir = Play.application().getFile("/public/");
            FileUtils.listFiles(dir, null, true).forEach(f -> {
                final Matcher matcher = FILE_PATTERN.matcher(f.getPath());
                if (matcher.find()) {
                    final String asset = matcher.group(1);
                    final String key = "assets." + asset.replace("/", ".");
                    String versioned = MyAssets.versioned(asset);
                    Logger.debug(String.format("key:%s - value:%s", key, versioned));
                    try {
                        root.put(key, versioned);
                    } catch (Exception e) {
                    } //swallow
                }
            });
        }

        if (Play.isProd()) {
            cache.entrySet().stream().forEach(entry -> {
                try {
                    root.put(entry.getKey(), entry.getValue());
                } catch (Exception e) { //swallow
                }
            });
        }
        //Logger.debug("static assets generation took:" + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms");
    }

}


text:
#ifndef DRAWING_PARITLCES_H
#define DRAWING_PARITLCES_H

class DrawingParticles : public Test
{
private:
	// Set bit 31 to distiguish these values from particle flags.
	enum Parameters {
		e_parameterBegin = (1UL << 31), // Start of this parameter namespace.
		e_parameterMove = e_parameterBegin | (1UL << 0),
		e_parameterRigid = e_parameterBegin | (1UL << 1),
		e_parameterRigidBarrier = e_parameterBegin | (1UL << 2),
		e_parameterElasticBarrier = e_parameterBegin | (1UL << 3),
		e_parameterSpringBarrier = e_parameterBegin | (1UL << 4),
		e_parameterRepulsive = e_parameterBegin | (1UL << 5),
	};

public:

	DrawingParticles()
	{
		{
			b2BodyDef bd;
			b2Body* ground = m_world->CreateBody(&bd);

			{
				b2PolygonShape shape;
				const b2Vec2 vertices[4] = {
					b2Vec2(-4, -2),
					b2Vec2(4, -2),
					b2Vec2(4, 0),
					b2Vec2(-4, 0)};
				shape.Set(vertices, 4);
				ground->CreateFixture(&shape, 0.0f);
			}

			{
				b2PolygonShape shape;
				const b2Vec2 vertices[4] = {
					b2Vec2(-4, -2),
					b2Vec2(-2, -2),
					b2Vec2(-2, 6),
					b2Vec2(-4, 6)};
				shape.Set(vertices, 4);
				ground->CreateFixture(&shape, 0.0f);
			}

			{
				b2PolygonShape shape;
				const b2Vec2 vertices[4] = {
					b2Vec2(2, -2),
					b2Vec2(4, -2),
					b2Vec2(4, 6),
					b2Vec2(2, 6)};
				shape.Set(vertices, 4);
				ground->CreateFixture(&shape, 0.0f);
			}

			{
				b2PolygonShape shape;
				const b2Vec2 vertices[4] = {
					b2Vec2(-4, 4),
					b2Vec2(4, 4),
					b2Vec2(4, 6),
					b2Vec2(-4, 6)};
				shape.Set(vertices, 4);
				ground->CreateFixture(&shape, 0.0f);
			}
		}

		m_colorIndex = 0;
		m_particleSystem->SetRadius(0.05f);
		m_lastGroup = NULL;
		m_drawing = true;

		b2Assert((k_paramDef[0].CalculateValueMask() & e_parameterBegin) == 0);
		TestMain::SetParticleParameters(k_paramDef, k_paramDefCount);
		TestMain::SetRestartOnParticleParameterChange(false);

		m_particleFlags = TestMain::GetParticleParameterValue();
		m_groupFlags = 0;
	}

	// Determine the current particle parameter from the drawing state and
	// group flags.
	uint32 DetermineParticleParameter() const
	{
		if (m_drawing)
		{
			if (m_groupFlags == (b2_rigidParticleGroup |
								 b2_solidParticleGroup))
			{
				return (uint32)e_parameterRigid;
			}
			if (m_groupFlags == b2_rigidParticleGroup &&
				m_particleFlags == b2_barrierParticle)
			{
				return (uint32)e_parameterRigidBarrier;
			}
			if (m_particleFlags == (b2_elasticParticle | b2_barrierParticle))
			{
				return (uint32)e_parameterElasticBarrier;
			}
			if (m_particleFlags == (b2_springParticle | b2_barrierParticle))
			{
				return (uint32)e_parameterSpringBarrier;
			}
			if (m_particleFlags == (b2_wallParticle | b2_repulsiveParticle))
			{
				return (uint32)e_parameterRepulsive;
			}
			return m_particleFlags;
		}
		return (uint32)e_parameterMove;
	}

	void Keyboard(unsigned char key)
	{
		m_drawing = key != 'X';
		m_particleFlags = 0;
		m_groupFlags = 0;
		switch (key)
		{
		case 'E':
			m_particleFlags = b2_elasticParticle;
			m_groupFlags = b2_solidParticleGroup;
			break;
		case 'P':
			m_particleFlags = b2_powderParticle;
			break;
		case 'R':
			m_groupFlags = b2_rigidParticleGroup | b2_solidParticleGroup;
			break;
		case 'S':
			m_particleFlags = b2_springParticle;
			m_groupFlags = b2_solidParticleGroup;
			break;
		case 'T':
			m_particleFlags = b2_tensileParticle;
			break;
		case 'V':
			m_particleFlags = b2_viscousParticle;
			break;
		case 'W':
			m_particleFlags = b2_wallParticle;
			m_groupFlags = b2_solidParticleGroup;
			break;
		case 'B':
			m_particleFlags = b2_barrierParticle | b2_wallParticle;
			break;
		case 'H':
			m_particleFlags = b2_barrierParticle;
			m_groupFlags = b2_rigidParticleGroup;
			break;
		case 'N':
			m_particleFlags = b2_barrierParticle | b2_elasticParticle;
			m_groupFlags = b2_solidParticleGroup;
			break;
		case 'M':
			m_particleFlags = b2_barrierParticle | b2_springParticle;
			m_groupFlags = b2_solidParticleGroup;
			break;
		case 'F':
			m_particleFlags = b2_wallParticle | b2_repulsiveParticle;
			break;
		case 'C':
			m_particleFlags = b2_colorMixingParticle;
			break;
		case 'Z':
			m_particleFlags = b2_zombieParticle;
			break;
		default:
			break;
		}
		TestMain::SetParticleParameterValue(DetermineParticleParameter());
	}

	void MouseMove(const b2Vec2& p)
	{
		Test::MouseMove(p);
		if (m_drawing)
		{
			b2CircleShape shape;
			shape.m_p = p;
			shape.m_radius = 0.2f;
			b2Transform xf;
			xf.SetIdentity();

			m_particleSystem->DestroyParticlesInShape(shape, xf);

			const bool joinGroup =
				m_lastGroup && m_groupFlags == m_lastGroup->GetGroupFlags();
			if (!joinGroup)
			{
				m_colorIndex = (m_colorIndex + 1) % k_ParticleColorsCount;
			}
			b2ParticleGroupDef pd;
			pd.shape = &shape;
			pd.flags = m_particleFlags;
			if ((m_particleFlags &
				(b2_wallParticle | b2_springParticle | b2_elasticParticle)) ||
				(m_particleFlags == (b2_wallParticle | b2_barrierParticle)))
			{
				pd.flags |= b2_reactiveParticle;
			}
			pd.groupFlags = m_groupFlags;
			pd.color = k_ParticleColors[m_colorIndex];
			pd.group = m_lastGroup;
			m_lastGroup = m_particleSystem->CreateParticleGroup(pd);
			m_mouseTracing = false;
		}
	}

	void MouseUp(const b2Vec2& p)
	{
		Test::MouseUp(p);
		m_lastGroup = NULL;
	}

	void ParticleGroupDestroyed(b2ParticleGroup* group) {
		Test::ParticleGroupDestroyed(group);
		if (group == m_lastGroup)
		{
			m_lastGroup = NULL;
		}
	}

	void Step(Settings* settings)
	{
		const uint32 parameterValue = TestMain::GetParticleParameterValue();
		m_drawing = (parameterValue & e_parameterMove) != e_parameterMove;
		if (m_drawing)
		{
			switch (parameterValue)
			{
				case b2_elasticParticle:
				case b2_springParticle:
				case b2_wallParticle:
					m_particleFlags = parameterValue;
					m_groupFlags = b2_solidParticleGroup;
					break;
				case e_parameterRigid:
					// b2_waterParticle is the default particle type in
					// LiquidFun.
					m_particleFlags = b2_waterParticle;
					m_groupFlags = b2_rigidParticleGroup |
					               b2_solidParticleGroup;
					break;
				case e_parameterRigidBarrier:
					m_particleFlags = b2_barrierParticle;
					m_groupFlags = b2_rigidParticleGroup;
					break;
				case e_parameterElasticBarrier:
					m_particleFlags = b2_barrierParticle | b2_elasticParticle;
					m_groupFlags = 0;
					break;
				case e_parameterSpringBarrier:
					m_particleFlags = b2_barrierParticle | b2_springParticle;
					m_groupFlags = 0;
					break;
				case e_parameterRepulsive:
					m_particleFlags = b2_repulsiveParticle | b2_wallParticle;
					m_groupFlags = b2_solidParticleGroup;
					break;
				default:
					m_particleFlags = parameterValue;
					m_groupFlags = 0;
					break;
			}
		}

		Test::Step(settings);
		m_debugDraw.DrawString(
			5, m_textLine, "Keys: (L) liquid, (E) elastic, (S) spring");
		m_textLine += DRAW_STRING_NEW_LINE;
		m_debugDraw.DrawString(
			5, m_textLine, "(R) rigid, (W) wall, (V) viscous, (T) tensile");
		m_textLine += DRAW_STRING_NEW_LINE;
		m_debugDraw.DrawString(
			5, m_textLine, "(F) repulsive wall, (B) wall barrier");
		m_textLine += DRAW_STRING_NEW_LINE;
		m_debugDraw.DrawString(
			5, m_textLine, "(H) rigid barrier, (N) elastic barrier, (M) spring barrier");
		m_textLine += DRAW_STRING_NEW_LINE;
		m_debugDraw.DrawString(
			5, m_textLine, "(C) color mixing, (Z) erase, (X) move");
		m_textLine += DRAW_STRING_NEW_LINE;
	}

	float32 GetDefaultViewZoom() const
	{
		return 0.1f;
	}

	static Test* Create()
	{
		return new DrawingParticles;
	}

	b2ParticleGroup* m_lastGroup;
	bool m_drawing;
	int32 m_particleFlags;
	int32 m_groupFlags;
	uint32 m_colorIndex;

	static const ParticleParameter::Value k_paramValues[];
	static const ParticleParameter::Definition k_paramDef[];
	static const uint32 k_paramDefCount;
};

const ParticleParameter::Value DrawingParticles::k_paramValues[] =
{
	{b2_zombieParticle,
		ParticleParameter::k_DefaultOptions, "erase"},
	{(uint32)e_parameterMove,
		ParticleParameter::k_DefaultOptions, "move"},
	{(uint32)e_parameterRigid,
		ParticleParameter::k_DefaultOptions, "rigid"},
	{(uint32)e_parameterRigidBarrier,
		ParticleParameter::k_DefaultOptions, "rigid barrier"},
	{(uint32)e_parameterElasticBarrier,
		ParticleParameter::k_DefaultOptions, "elastic barrier"},
	{(uint32)e_parameterSpringBarrier,
		ParticleParameter::k_DefaultOptions, "spring barrier"},
	{(uint32)e_parameterRepulsive,
		ParticleParameter::k_DefaultOptions, "repulsive wall"}
};

const ParticleParameter::Definition DrawingParticles::k_paramDef[] =
{
	{
		ParticleParameter::k_particleTypesPtr,
		ParticleParameter::k_particleTypesCount
	},
	{
		DrawingParticles::k_paramValues,
		B2_ARRAY_SIZE(DrawingParticles::k_paramValues)
	},
};
const uint32 DrawingParticles::k_paramDefCount =
	B2_ARRAY_SIZE(DrawingParticles::k_paramDef);

#endif


text:
module.exports = [{
  isActive: true,
  name: "Zachary Allen",
  title: "CEO & Chief Robotics Engineer",
  type: "team",
  img: "/img/zach",
  description: "Zach founded Slate Robotics in 2017 and heads the company as its CEO and Chief Robotics Engineer. He designs and implements the technology that enables our robots to be affordable, reliable, and highly capable. Zach is dedicated to building a future of robot butlers, and in that pursuit, he has made several, key innovations in reducing the costs of these complex machines – including designs for low-cost torque sensing and low-cost, high-payload actuators.",
  socials: [
    "https://www.linkedin.com/in/zachary-allen-674ab8a9/",
    "https://twitter.com/ZachAllen417",
    "https://www.facebook.com/zach.allen.566"
  ],
},{
  isActive: false,
  name: "Isaac Feemster",
  title: "3D Printing Technician",
  type: "team",
  img: "/img/person-icon",
  description: "Isaac's main function is to run, fix, debug, and upgrade our 3D printers as needed. Isaac is a major maker and loves building things. Checkout his YouTube channel!",
  socials: [
    "https://www.youtube.com/channel/UCmPSNJwp1B0MSinUBkZWeXg/featured"
  ]
},{
  isActive: true,
  name: "Tavian Riebold",
  title: "Electronics Engineer",
  type: "team",
  img: "/img/person-icon",
  description: "Tavian is responsible for designing and implementing much of the electronics in our robots. Through his work, we are able to greatly reduce the overall complexity of our robots while introducing key features and capabilities. Tavian also enjoys software development and mechanical design, and he will help out in other areas frequently. Tavian hosts a Minecraft server in his spare time and goes mountain biking when the weather's nice.",
  socials: []
},{
  isActive: true,
  name: "Brian Allen",
  title: "Investor & Board Member",
  type: "investor",
  img: "/img/brian",
  description: "Brian is the founder of Pension Consultants, Inc., and he has served as President and Board Chairperson since its inception in 1994. He serves as Chairperson for Pension Consultants' Investment Committee, which oversees nearly $3.1B in AUM/AUA. He was approached by Zach in May 2017 to help fund the early stages of Slate Robotics, and he has been an unwaivering proponent of the vision of the company and of the company itself.",
  socials: [
    "https://www.linkedin.com/in/brianallenretireadviser1/",
    "https://twitter.com/RetireAdviser1"
  ]
}];


text:
package org.apache.flink.runtime.rest.handler.job;

import org.apache.flink.api.common.time.Time;
import org.apache.flink.runtime.accumulators.StringifiedAccumulatorResult;
import org.apache.flink.runtime.executiongraph.AccessExecutionJobVertex;
import org.apache.flink.runtime.executiongraph.AccessExecutionVertex;
import org.apache.flink.runtime.jobgraph.JobVertexID;
import org.apache.flink.runtime.rest.handler.HandlerRequest;
import org.apache.flink.runtime.rest.handler.RestHandlerException;
import org.apache.flink.runtime.rest.handler.legacy.ExecutionGraphCache;
import org.apache.flink.runtime.rest.messages.EmptyRequestBody;
import org.apache.flink.runtime.rest.messages.JobVertexMessageParameters;
import org.apache.flink.runtime.rest.messages.MessageHeaders;
import org.apache.flink.runtime.rest.messages.job.SubtasksAllAccumulatorsInfo;
import org.apache.flink.runtime.rest.messages.job.UserAccumulator;
import org.apache.flink.runtime.taskmanager.TaskManagerLocation;
import org.apache.flink.runtime.webmonitor.RestfulGateway;
import org.apache.flink.runtime.webmonitor.retriever.GatewayRetriever;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executor;

/**
 * Request handler for the subtasks all accumulators.
 */
public class SubtasksAllAccumulatorsHandler extends AbstractJobVertexHandler<SubtasksAllAccumulatorsInfo, JobVertexMessageParameters> {

	public SubtasksAllAccumulatorsHandler(GatewayRetriever<? extends RestfulGateway> leaderRetriever, Time timeout, Map<String, String> responseHeaders, MessageHeaders<EmptyRequestBody, SubtasksAllAccumulatorsInfo, JobVertexMessageParameters> messageHeaders, ExecutionGraphCache executionGraphCache, Executor executor) {
		super(leaderRetriever, timeout, responseHeaders, messageHeaders, executionGraphCache, executor);
	}

	@Override
	protected SubtasksAllAccumulatorsInfo handleRequest(HandlerRequest<EmptyRequestBody, JobVertexMessageParameters> request, AccessExecutionJobVertex jobVertex) throws RestHandlerException {
		JobVertexID jobVertexId = jobVertex.getJobVertexId();
		int parallelism = jobVertex.getParallelism();

		final List<SubtasksAllAccumulatorsInfo.SubtaskAccumulatorsInfo> subtaskAccumulatorsInfos = new ArrayList<>();

		for (AccessExecutionVertex vertex : jobVertex.getTaskVertices()) {
			TaskManagerLocation location = vertex.getCurrentAssignedResourceLocation();
			String locationString = location == null ? "(unassigned)" : location.getHostname();

			StringifiedAccumulatorResult[] accs = vertex.getCurrentExecutionAttempt().getUserAccumulatorsStringified();
			List<UserAccumulator> userAccumulators = new ArrayList<>(accs.length);
			for (StringifiedAccumulatorResult acc : accs) {
				userAccumulators.add(new UserAccumulator(acc.getName(), acc.getType(), acc.getValue()));
			}

			subtaskAccumulatorsInfos.add(
				new SubtasksAllAccumulatorsInfo.SubtaskAccumulatorsInfo(
					vertex.getCurrentExecutionAttempt().getParallelSubtaskIndex(),
					vertex.getCurrentExecutionAttempt().getAttemptNumber(),
					locationString,
					userAccumulators
				));
		}

		return new SubtasksAllAccumulatorsInfo(jobVertexId, parallelism, subtaskAccumulatorsInfos);
	}

}


text:
import React, { PropTypes } from 'react'

const IncorrectFeedback = ({result}) =>

            La respuesta era

            {result}

const CorrectFeedback = () =>

        ¡Correcto!

const Feedback = ({feedback}) =>
    feedback.input === feedback.result
        ? <CorrectFeedback />
        : <IncorrectFeedback result={feedback.result} />

const FeedbackWrapper = ({feedback}) =>
    feedback.visible
        ? <Feedback feedback={feedback} />
        : null

FeedbackWrapper.propTypes = {
    feedback: PropTypes.object.isRequired,
}

export default FeedbackWrapper


text:
<select name="themePicker" ng-model="model.value"
        ng-controller="Merchello.Plugin.Bazaar.ThemePickerController"
        ng-options="theme for theme in themes">
</select>


text:
var Background = function(keyword, name, description, uri, line) {
  var Cucumber = require('../../cucumber');

  var steps = Cucumber.Type.Collection();

  var self = {
    getKeyword: function getKeyword() {
      return keyword;
    },

    getName: function getName() {
      return name;
    },

    getDescription: function getDescription() {
      return description;
    },

    getUri: function getUri() {
      return uri;
    },

    getLine: function getLine() {
      return line;
    },

    addStep: function addStep(step) {
      var lastStep = self.getLastStep();
      step.setPreviousStep(lastStep);
      steps.add(step);
 	  },

    getLastStep: function getLastStep() {
      return steps.getLast();
    },

 	  getSteps: function getSteps() {
      return steps;
 	  },

    getMaxStepLength: function () {
      var max = 0;
      steps.syncForEach(function(step) {
        var output = step.getKeyword() + step.getName();
        if (output.length > max) max = output.length;
      });
      return max;
    }
  };
  return self;
};
module.exports = Background;


text:
'use strict';

const models = require('./index');

/**
 * A copy activity SQL Data Warehouse source.
 *
 * @extends models['CopySource']
 */
class SqlDWSource extends models['CopySource'] {
  /**
   * Create a SqlDWSource.
   * @member {object} [sqlReaderQuery] SQL Data Warehouse reader query. Type:
   * string (or Expression with resultType string).
   * @member {object} [sqlReaderStoredProcedureName] Name of the stored
   * procedure for a SQL Data Warehouse source. This cannot be used at the same
   * time as SqlReaderQuery. Type: string (or Expression with resultType
   * string).
   * @member {object} [storedProcedureParameters] Value and type setting for
   * stored procedure parameters. Example: "{Parameter1: {value: "1", type:
   * "int"}}". Type: object (or Expression with resultType object), itemType:
   * StoredProcedureParameter.
   */
  constructor() {
    super();
  }

  /**
   * Defines the metadata of SqlDWSource
   *
   * @returns {object} metadata of SqlDWSource
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'SqlDWSource',
      type: {
        name: 'Composite',
        className: 'SqlDWSource',
        modelProperties: {
          sourceRetryCount: {
            required: false,
            serializedName: 'sourceRetryCount',
            type: {
              name: 'Object'
            }
          },
          sourceRetryWait: {
            required: false,
            serializedName: 'sourceRetryWait',
            type: {
              name: 'Object'
            }
          },
          type: {
            required: true,
            serializedName: 'type',
            type: {
              name: 'String'
            }
          },
          sqlReaderQuery: {
            required: false,
            serializedName: 'sqlReaderQuery',
            type: {
              name: 'Object'
            }
          },
          sqlReaderStoredProcedureName: {
            required: false,
            serializedName: 'sqlReaderStoredProcedureName',
            type: {
              name: 'Object'
            }
          },
          storedProcedureParameters: {
            required: false,
            serializedName: 'storedProcedureParameters',
            type: {
              name: 'Object'
            }
          }
        }
      }
    };
  }
}

module.exports = SqlDWSource;


text:
require "toy_robot_simulator/version"
require "robot"
require "board"
require "command_parser"
Dir['./lib/commands/*.rb'].each { |file| require file }

module ToyRobotSimulator
  class Simulator

    def initialize
      @robot = Robot.new
      @board = Board.new(5, 5)
    end

    def start_simulator
      begin
        loop do
          command = CommandParser.parse_command(STDIN.gets)
          command.execute(@robot) if command.valid?(@robot, @board)
        end
      rescue SystemExit, Interrupt => e
        # rescue from CTRL-C
        exit
      end
    end
  end
end


text:
""" Telerivet WebHook gateway

    Supports Receiving and replying SMS from/to Telerivet Service

    See: http://telerivet.com/help/api/webhook/receiving """

import json
import datetime

from django.http import HttpResponse
from django.core.urlresolvers import reverse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from django.utils.translation import ugettext as _

from onadata.apps.sms_support.tools import SMS_API_ERROR,\
    SMS_SUBMISSION_ACCEPTED
from onadata.apps.sms_support.parser import process_incoming_smses

def autodoc(url_root, username, id_string):
    urla = url_root + reverse('sms_submission_api',
                              kwargs={'username': username,
                                      'service': 'telerivet'})
    urlb = url_root + reverse('sms_submission_form_api',
                              kwargs={'username': username,
                                      'id_string': id_string,
                                      'service': 'telerivet'})
    doc = (u'
' +
           _(u"%(service)s Instructions:")
           % {'service': u''
                         u'Telerivet\'s Webhook API'} +
           u'

' +
           _(u"Sign in to Telerivet.com and go to Service Page.") +
           u'

' +
           _(u"Follow instructions to add an application with either URL:") +
           u'
%(urla)s' +
           u'
%(urlb)s
' +
           u'

' +
           _(u"That's it. Now Send an SMS Formhub submission to your Telerivet"
             u" phone number. It will create a submission on Formhub.") +
           u'
') % {'urla': urla, 'urlb': urlb}

    return doc

def get_response(data):

    message = data.get('text')

    if data.get('code') == SMS_API_ERROR:
        message = None
    elif data.get('code') != SMS_SUBMISSION_ACCEPTED:
        message = _(u"[ERROR] %s") % message

    response = {}

    if message:
        messages = [{"content": message}]
        sendouts = data.get('sendouts', [])
        if len(sendouts):
            messages += [{"content": text} for text in sendouts]
        response.update({"messages": messages})
    return HttpResponse(json.dumps(response), content_type='application/json')

@require_POST
@csrf_exempt
def import_submission(request, username):
    """ Proxy to import_submission_for_form with None as id_string """

    return import_submission_for_form(request, username, None)

@require_POST
@csrf_exempt
def import_submission_for_form(request, username, id_string):
    """ Retrieve and process submission from SMSSync Request """

    sms_identity = request.POST.get('from_number', '').strip()
    sms_text = request.POST.get('content', '').strip()
    now_timestamp = datetime.datetime.now().strftime('%s')
    sent_timestamp = request.POST.get('time_created', now_timestamp).strip()
    try:
        sms_time = datetime.datetime.fromtimestamp(float(sent_timestamp))
    except ValueError:
        sms_time = datetime.datetime.now()

    return process_message_for_telerivet(username=username,
                                         sms_identity=sms_identity,
                                         sms_text=sms_text,
                                         sms_time=sms_time,
                                         id_string=id_string)

def process_message_for_telerivet(username,
                                  sms_identity, sms_text, sms_time, id_string):
    """ Process a text instance and return in SMSSync expected format """

    if not sms_identity or not sms_text:
        return get_response({'code': SMS_API_ERROR,
                             'text': _(u"`identity` and `message` are "
                                       u"both required and must not be "
                                       u"empty.")})

    incomings = [(sms_identity, sms_text)]
    response = process_incoming_smses(username, incomings, id_string)[-1]

    return get_response(response)


text:
package au.com.itgeeks.spring.security.oidc.client.filter;

import java.io.IOException;
import java.util.Map;

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

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.client.OAuth2RestOperations;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;

import com.fasterxml.jackson.databind.ObjectMapper;

import au.com.itgeeks.spring.security.user.OIDCUserDetails;

public class OIDCConnectFilter extends AbstractAuthenticationProcessingFilter {

  public OAuth2RestOperations restTemplate;

  public OIDCConnectFilter(String defaultFilterProcessesUrl) {
      super(defaultFilterProcessesUrl);
      setAuthenticationManager(new NoopAuthenticationManager());
  }

  @Override
  public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {

      OAuth2AccessToken accessToken;
      try {
          accessToken = restTemplate.getAccessToken();
      } catch (final OAuth2Exception e) {
          throw new BadCredentialsException("Could not obtain access token", e);
      }
      try {
          final String idToken = accessToken.getAdditionalInformation().get("id_token").toString();
          final Jwt tokenDecoded = JwtHelper.decode(idToken);
          System.out.println("===== : " + tokenDecoded.getClaims());

          @SuppressWarnings("unchecked")
          final Map<String, String> authInfo = new ObjectMapper().readValue(tokenDecoded.getClaims(), Map.class);

          final OIDCUserDetails user = new OIDCUserDetails(authInfo, accessToken);
          return new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
      } catch (final InvalidTokenException e) {
          throw new BadCredentialsException("Could not obtain user details from token", e);
      }

  }

  public void setRestTemplate(OAuth2RestTemplate restTemplate2) {
      restTemplate = restTemplate2;

  }

  private static class NoopAuthenticationManager implements AuthenticationManager {

      @Override
      public Authentication authenticate(Authentication authentication) throws AuthenticationException {
          throw new UnsupportedOperationException("No authentication should be done with this AuthenticationManager");
      }

  }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Radical.Project
{
    public class JsonDataCollector
    {
        private Dictionary<string, dynamic> _data;

        public Dictionary<string, dynamic> Data
        {
            get { return _data; }
        }

        public JsonDataCollector(Func<IEnumerable<FileContent>> jsonFiles)
        {
            _data = new Dictionary<string, dynamic>();

            foreach (var json in jsonFiles())
            {
                try
                {
                    var data = JsonConvert.DeserializeObject(json.Content);
                    _data.Add(json.FileNameWithoutExtension, data);
                }
                catch (Exception e)
                {
                    throw new ApplicationException("Exception at file" + json.Path);
                }
            }
        }
    }
}


text:
var eventName = typeof(Turbolinks) !== 'undefined' ? 'turbolinks:load' : 'DOMContentLoaded';

if (!document.documentElement.hasAttribute("data-turbolinks-preview")) {
  document.addEventListener(eventName, function flash() {
    var flashData = JSON.parse(document.getElementById('shopify-app-flash').dataset.flash);

    var Toast = window['app-bridge'].actions.Toast;

    if (flashData.notice) {
      Toast.create(app, {
        message: flashData.notice,
        duration: 5000,
      }).dispatch(Toast.Action.SHOW);
    }

    if (flashData.error) {
      Toast.create(app, {
        message: flashData.error,
        duration: 5000,
        isError: true,
      }).dispatch(Toast.Action.SHOW);
    }
  });
}


text:
module 'i18n'

function new_variants()
  local variants = {}

  local function reverse(arr, length)
    local result = {}
    for i=1, length do result[i] = arr[length-i+1] end
    return result, length
  end

  local function concat(arr1, len1, arr2, len2)
    for i = 1, len2 do
      arr1[len1 + i] = arr2[i]
    end
    return arr1, len1 + len2
  end

  function variants.ancestry(locale)
    local result, length, accum = {},0,nil
    locale:gsub("[^%-]+", function(c)
      length = length + 1
      accum = accum and (accum .. '-' .. c) or c
      result[length] = accum
    end)
    return reverse(result, length)
  end

  function variants.isParent(parent, child)
    return not not child:match("^".. parent .. "%-")
  end

  function variants.root(locale)
    return locale:match("[^%-]+")
  end

  function variants.fallbacks(locale, fallbackLocale)
    if locale == fallbackLocale or
       variants.isParent(fallbackLocale, locale) then
       return variants.ancestry(locale)
    end
    if variants.isParent(locale, fallbackLocale) then
      return variants.ancestry(fallbackLocale)
    end

    local ancestry1, length1 = variants.ancestry(locale)
    local ancestry2, length2 = variants.ancestry(fallbackLocale)

    return concat(ancestry1, length1, ancestry2, length2)
  end

  return variants
end


text:
package com.mwr.common.tls;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;

public class X509Fingerprint {

	public static final String ALGORITHM = "SHA-1";
	private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7',  '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

	private X509Certificate certificate;

	public X509Fingerprint(X509Certificate certificate) {
		this.certificate = certificate;
	}

	public byte[] getDER() throws CertificateEncodingException {
		return this.certificate.getEncoded();
	}

	public byte[] getFingerprint() throws CertificateEncodingException {
		try {
			MessageDigest digest = MessageDigest.getInstance(ALGORITHM);

			digest.update(this.getDER());
	    	return digest.digest();
		}
		catch (NoSuchAlgorithmException e) {
			return null;
		}
	}

	private String hexify(byte bytes[]) {
    	StringBuffer buf = new StringBuffer(bytes.length * 2);

        for(int i=0; i<bytes.length; ++i) {
        	buf.append(HEX_DIGITS[(bytes[i] & 0xf0) >> 4]);
            buf.append(HEX_DIGITS[(bytes[i] & 0x0f)]);
            buf.append(':');
        }

        return buf.substring(0, buf.length() - 1).toString();
    }

	public String toString() {
		try {
			return this.hexify(this.getFingerprint());
		}
		catch(CertificateEncodingException e) {
			return "was not able to fingerprint certificate";
		}
	}

}


text:
typedef int binID;

// the following are removed in favor of cvec.h
#include "cvec.h"

struct cvec2u {
	unsigned int x, y;
	cvec2u() {}
	cvec2u (unsigned int tx, unsigned int ty) :x(tx), y (ty) {}
	cvec2u& operator= (cvec2u &t) {
		x = t.x;
		y = t.y;
		return *this;
	}
};

struct ConstantState
{
	int screenSizeX;
	int screenSizeY;
  float halfW, halfH;

	// specific states of the scene here
	float projMatrix[16];
	float viewMatrix[16];
	float viewProjMatrix[16];
  int debX, debY;

	void isConstantState() {}
};

struct MutableState
{
  float zBuffer[1024*768];

  void isMutableState() {}
};

struct Primitive
{
	Primitive() : binID(0) {}

	void isPrim() {}

	unsigned binID;
  unsigned launchIdx; // index (within bin) of primitive in launch order
};

struct Pixel : public Primitive
{
	// pos(0,0) is the bottom left corner of the window
	// pos(screenSizeX, screenSizeY) is the top right corner of the window
	cvec2u pos;
	// r, g, and b must be between 0 and 1, inclusive
	// float r;
	// float g;
	// float b;
  unsigned int color;

	//Pixel() : r(0), g(0), b(0) {pos.x = 0; pos.y = 0;}
  Pixel()  {color = 0; pos.x = 0; pos.y = 0;}

	void setColor(float r, float g, float b, float a) {
		color = ((unsigned)(a*255.0f)<<24)
					| ((unsigned)(b*255.0f)<<16)
					| ((unsigned)(g*255.0f)<<8)
					| (unsigned)(r*255.0f);
	}
};

struct boundingBox {
  cvec2f hi, lo;
};

struct pointPrimitive : public Primitive {
  cvec2f pos;
};

struct areaPrimitive : public Primitive {
  //cvec2f bbLo, bbHi;
  boundingBox bb;
};

struct trianglePiko : public areaPrimitive {
  cvec3f v0, v1, v2;
};

struct fragment : public pointPrimitive {
  float depth;
  unsigned color;
};

struct particle : public areaPrimitive {
	cvec4f pos, tpos;
};

#endif //PIKO_BUILTIN_TYPES_H


text:
const {resolver} = require('graphql-sequelize')

import {models} from '~/server/db'

export default (user?: {id: number}) => {
  if (!user) {
    return resolver(models.Post)
  }
  return models.Post.findAll({where: {userId: user.id}})
}


text:
/* eslint-disable import/prefer-default-export */
import {
  getClickedElement,
  getElementText,
  getElementI18nKey,
  getElementNamespace
} from './utils';

export function createClickHandler(cb, options) {
  // eslint-disable-next-line consistent-return
  const handler = (e) => {
    const el = getClickedElement(e);
    if (!el) return {};

    e.preventDefault();
    e.stopPropagation();

    const text = getElementText(el);
    const key = getElementI18nKey(el);

    const rectEl = el.getBoundingClientRect ? el : el.parentElement;
    const {
      top, left, width, height
    } = rectEl.getBoundingClientRect();

    const style = window.getComputedStyle(rectEl, null);
    const pT = parseFloat(style.getPropertyValue('padding-top'));
    const pB = parseFloat(style.getPropertyValue('padding-bottom'));
    const pR = parseFloat(style.getPropertyValue('padding-right'));
    const pL = parseFloat(style.getPropertyValue('padding-left'));
    const sizing = style.getPropertyValue('box-sizing');

    // eslint-disable-next-line consistent-return
    function getFallbackNS() {
      const i18next = options.getI18next();
      if (i18next && i18next.options && i18next.options.isLocizify) return i18next.options.defaultNS;
    }

    cb({
      tagName: rectEl.tagName,
      text,
      key,
      ns: getElementNamespace(el) || getFallbackNS(),
      box: {
        top,
        left,
        width: sizing === 'border-box' ? width : width - pR - pL,
        height: sizing === 'border-box' ? height : height - pT - pB
      },
      style: style.cssText
    });
  };

  return handler;
}


text:
/*
* Responsive
*/

@custom-media --sm-viewport only screen and (max-width: 25em);
@custom-media --md-viewport only screen and (max-width: 48em);
@custom-media --lg-viewport only screen and (max-width: 62em);
@custom-media --xl-viewport only screen and (max-width: 75em);

/*
* Avatar
*/

@custom-selector :--avatar .avatar;
@custom-selector :--avatar-primary .avatar.primary;
@custom-selector :--avatar-outline .avatar.outline;
@custom-selector :--avatar-small .avatar.small;
@custom-selector :--avatar-large .avatar.large;

/*
* Chips
*/

@custom-selector :--chips .chips;
@custom-selector :--chips-primary .chips.primary;
@custom-selector :--chips-error .chips.error;
@custom-selector :--chips-info .chips.info;
@custom-selector :--chips-warning .chips.warning;
@custom-selector :--chips-success .chips.success;
@custom-selector :--chips-dark .chips.dark;
@custom-selector :--chips-outline .chips.outline;
@custom-selector :--chips-small .chips.small;
@custom-selector :--chips-large .chips.large;

/*
* Alert
*/

@custom-selector :--alert .alert;
@custom-selector :--placeholder .placeholder;
@custom-selector :--info .info;
@custom-selector :--error .error;
@custom-selector :--warning .warning;
@custom-selector :--success .success;
@custom-selector :--rounded .rounded;
@custom-selector :--close .close;

/*
* Dialog
*/

@custom-selector :--dialog .dialog;
@custom-selector :--close .close;
@custom-selector :--overlay .overlay;

/*
* Card
*/

@custom-selector :--card .card;
@custom-selector :--header .card-header;
@custom-selector :--footer .card-footer;
@custom-selector :--title .card-title;
@custom-selector :--content .card-content;

/*
* Icons
*/

@custom-selector :--icon .icon;
@custom-selector :--icon-large .icon.lg;
@custom-selector :--icon-small .icon.sm;

/*
 * Grid
*/

@custom-selector :--all-cols-xs
  .col-xs,
  .col-xs-1,
  .col-xs-2,
  .col-xs-3,
  .col-xs-4,
  .col-xs-5,
  .col-xs-6,
  .col-xs-7,
  .col-xs-8,
  .col-xs-9,
  .col-xs-10,
  .col-xs-11,
  .col-xs-12;
@custom-selector :--all-cols-sm
  .col-sm,
  .col-sm-1,
  .col-sm-2,
  .col-sm-3,
  .col-sm-4,
  .col-sm-5,
  .col-sm-6,
  .col-sm-7,
  .col-sm-8,
  .col-sm-9,
  .col-sm-10,
  .col-sm-11,
  .col-sm-12;
@custom-selector :--all-cols-md
  .col-md,
  .col-md-1,
  .col-md-2,
  .col-md-3,
  .col-md-4,
  .col-md-5,
  .col-md-6,
  .col-md-7,
  .col-md-8,
  .col-md-9,
  .col-md-10,
  .col-md-11,
  .col-md-12;
@custom-selector :--all-cols-lg
  .col-lg,
  .col-lg-1,
  .col-lg-2,
  .col-lg-3,
  .col-lg-4,
  .col-lg-5,
  .col-lg-6,
  .col-lg-7,
  .col-lg-8,
  .col-lg-9,
  .col-lg-10,
  .col-lg-11,
  .col-lg-12;

/*
* Toggle
*/

@custom-selector :--toggle .toggle;
@custom-selector :--toggle-label .toggle-label;
@custom-selector :--toggle-activated .toggle.activated;
@custom-selector :--toggle-disabled .toggle.disabled;
@custom-selector :--toggle-checked .toggle-input:checked + .toggle-label;
@custom-selector :--toggle-input .toggle-input;

/*
* Collapse
*/

@custom-selector :--collapse .collapse;
@custom-selector :--collapse-content .collapse-content;
@custom-selector :--collapse-content-checked
  .collapse input:checked ~ .collapse-content;
@custom-selector :--collapse-item .collapse-item;
@custom-selector :--collapse-input .collapse input;
@custom-selector :--collapse-label .collapse label;
@custom-selector :--collapse-icon-left .icon.left;
@custom-selector :--collapse-icon-right .icon.right;


text:
package com.github.anba.es6draft.regexp;

import java.util.BitSet;
import java.util.regex.Pattern;

/**
 * {@link RegExpMatcher} implementation for standard JDK {@link Pattern} regular expressions
 */
final class JDKRegExpMatcher implements RegExpMatcher {
    // Java pattern for the input RegExp
    private final String regex;
    // Java flags for the input RegExp
    private final int flags;
    private final BitSet negativeLAGroups;
    private Pattern pattern;

    public JDKRegExpMatcher(String regex, int flags, BitSet negativeLAGroups) {
        this.regex = regex;
        this.flags = flags;
        this.negativeLAGroups = negativeLAGroups;
    }

    private Pattern getPattern() {
        if (pattern == null) {
            pattern = Pattern.compile(regex, flags);
        }
        return pattern;
    }

    @Override
    public JDKMatchState matcher(String s) {
        return new JDKMatchState(getPattern().matcher(s));
    }

    @Override
    public BitSet getNegativeLookaheadGroups() {
        return negativeLAGroups;
    }
}


text:
/* eslint no-unused-vars: 0, no-console: 0 */
'use strict';

if (process.env.NODE_ENV === 'production') {
  /* eslint-disable no-console */
  console.log('Starting newrelic application monitoring');
  /* eslint-enable */
  require('newrelic'); // eslint-disable-line global-require
}

const express = require('express');
const compression = require('compression');
const responseTime = require('response-time');

const raven = require('raven');
const sentry = require('./lib/sentry');
const HttpError = require('@starefossen/node-http-error');

const app = module.exports = express();

app.set('json spaces', 2);
app.set('x-powered-by', false);
app.set('etag', false);

app.use(compression());
app.use(responseTime());

const origins = new Set((process.env.ALLOW_ORIGINS || '').split(','));
const url = require('url');

app.use((req, res, next) => {
  if (req.get('Origin')) {
    const origin = url.parse(req.get('Origin'));

    if (!origins.has(origin.hostname)) {
      return next(new HttpError(`Bad Origin ${req.get('Origin')}`, 403));
    }

    res.set('Access-Control-Allow-Origin', req.get('Origin'));
    res.set('Access-Control-Allow-Methods', 'GET, POST');
    res.set('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type');
    res.set('Access-Control-Expose-Headers', 'X-Response-Time');
    res.set('Access-Control-Allow-Max-Age', 0);
  }

  if (req.method === 'OPTIONS' && req.path !== '/CloudHealthCheck') {
    return res.status(200).end();
  }

  return next();
});

app.all('/CloudHealthCheck', (req, res) => {
  res.status(200);

  if (req.method === 'HEAD') {
    return res.end();
  }

  return res.json({
    message: 'System OK',
  });
});

app.use('/api/v1/', require('./routes/api_v1'));

app.use((req, res, next) => {
  res.status(404).json({
    message: 'Not Found',
  });
});

app.use(raven.middleware.express.requestHandler(sentry));
app.use(raven.middleware.express.errorHandler(sentry));

app.use((err, req, res, next) => {
  if (err.code === 'LIMIT_UNEXPECTED_FILE') {
    err.message = `Unknown form field "${err.field}"`;
    err.code = 400;
  }

  err.code = err.code || 500;
  res.status(err.code);

  if (err.code >= 500) {
    console.error(err);
    console.error(err.message);
    console.error(err.stack);
  }

  if (req.method === 'HEAD') {
    return res.end();
  }

  return res.json({
    message: err.message || 'Unknown error',
  });
});

if (!module.parent) {
  app.listen(8080);
  console.log('Server is listening on port 8080');
}