text:
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <title>Digital Scholarship Laboratory</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="Bootstrap Template">
    <meta name="Mark Stacy" content="OU IT Informatics">
    <link rel="stylesheet" href="bower_components/ou_css/OULib_Bootswatch_Full.css">

    <link rel="stylesheet" href="style.css">

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
        Toggle navigation

      </button>
      U.S. Congressional Hearings Search Engine

About

Help

              Login

User Profile

Log out

Search

Task History

User Profile

Task History

                  Task Name
                  Timestamp
                  Metadata Tags

← Previous

Next →

© Copyright

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Hearing Metadata

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Help

      <embed src="help_dsl.pdf" width="100%" height="80%" alt="pdf" pluginspage="http://www.adobe.com/products/acrobat/readstep2.html">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

About

      <embed src="about.html" width="100%" height="60%">

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Task Result

Login to Your Account

                  <form>
                    <input type="text" name="user" placeholder="Username">
                    <input type="password" name="pass" placeholder="Password">
                    <input type="submit" name="login" class="login loginmodal-submit" value="Login">
                  </form>

                    Register - Forgot Password

redpajama_set_name: RedPajamaGithub


text:
NS_CC_EXT_BEGIN

typedef enum {
    CCStoreReceiptVerifyModeNone = 0,
    CCStoreReceiptVerifyModeDevice = 1,
    CCStoreReceiptVerifyModeServer
} CCStoreReceiptVerifyMode;

static const int CCStoreReceiptVerifyStatusUnknownError = -5;
static const int CCStoreReceiptVerifyStatusInvalidReceipt = -4;
static const int CCStoreReceiptVerifyStatusRequestFailed = -3;
static const int CCStoreReceiptVerifyStatusInvalidResult = -2;
static const int CCStoreReceiptVerifyStatusNone = -1;
static const int CCStoreReceiptVerifyStatusOK = 0;
typedef int CCStoreReceiptVerifyStatus;

typedef enum {
    CCStorePaymentTransactionStateNull = 0,
    CCStorePaymentTransactionStatePurchasing = 1,
    CCStorePaymentTransactionStatePurchased,
    CCStorePaymentTransactionStateFailed,
    CCStorePaymentTransactionStateRestored,
    CCStorePaymentTransactionStateCancelled,
} CCStorePaymentTransactionState;

static const char* const CCStorePaymentTransactionStateNames[] = {
    "unknown",
    "purchasing",
    "purchased",
    "failed",
    "restored",
    "cancelled"
};

class CCStorePaymentTransaction : public cocos2d::CCObject
{
public:
    static CCStorePaymentTransaction* transactionWithState(CCStorePaymentTransactionWrapper* transactionWapper,
                                                           CCStorePaymentTransactionState state,
                                                           const char* transactionId,
                                                           const char* productId,
                                                           int quantity,
                                                           double dateTime,
                                                           int receiptDataLength,
                                                           const void* receiptData,
                                                           int errorCode,
                                                           const char* errorDescription,
                                                           CCStorePaymentTransaction* originalTransaction,
                                                           CCStoreReceiptVerifyMode receiptVerifyMode,
                                                           CCStoreReceiptVerifyStatus receiptVerifyStatus);
    ~CCStorePaymentTransaction(void);

    CCStorePaymentTransactionWrapper* getTransactionWrapper(void)
    {
        return m_transactionWapper;
    }

    CCStorePaymentTransactionState getTransactionState(void)
    {
        return m_transactionState;
    }

    const std::string& getTransactionIdentifier(void)
    {
        return m_transactionIdentifier;
    }

    const std::string& getProductIdentifier(void)
    {
        return m_productIdentifier;
    }

    int getQuantity(void)
    {
        return m_quantity;
    }

    double getDateTime(void)
    {
        return m_dateTime;
    }

    int getReceiptDataLength(void)
    {
        return m_receiptDataLength;
    }

    const void* const getReceiptData(void)
    {
        return m_receiptData;
    }

    int getErrorCode(void)
    {
        return m_errorCode;
    }

    const std::string& getErrorDescription(void)
    {
        return m_errorDescription;
    }

    CCStorePaymentTransaction* getOriginalTransaction(void)
    {
        return m_originalTransaction;
    }

    CCStoreReceiptVerifyMode getReceiptVerifyMode(void)
    {
        return m_receiptVerifyMode;
    }

    int getReceiptVerifyStatus(void)
    {
        return m_receiptVerifyStatus;
    }

#if CC_LUA_ENGINE_ENABLED > 0
    const cocos2d::CCLuaValueDict convertToLuaTable(void);
#endif

private:
    CCStorePaymentTransaction(void) {}

    bool initWithState(CCStorePaymentTransactionWrapper *transactionWapper,
                       CCStorePaymentTransactionState state,
                       const char* transactionId,
                       const char* productId,
                       int quantity,
                       double dateTime,
                       int receiptDataLength,
                       const void* receiptData,
                       int errorCode,
                       const char* errorDescription,
                       CCStorePaymentTransaction* originalTransaction,
                       CCStoreReceiptVerifyMode receiptVerifyMode,
                       CCStoreReceiptVerifyStatus receiptVerifyStatus);

    CCStorePaymentTransactionWrapper*   m_transactionWapper;
    CCStorePaymentTransactionState      m_transactionState;
    std::string                         m_transactionIdentifier;
    std::string                         m_productIdentifier;
    int                                 m_quantity;
    double                              m_dateTime;
    int                                 m_receiptDataLength;
    void*                               m_receiptData;
    int                                 m_errorCode;
    std::string                         m_errorDescription;
    CCStorePaymentTransaction*          m_originalTransaction;
    CCStoreReceiptVerifyMode            m_receiptVerifyMode;
    CCStoreReceiptVerifyStatus          m_receiptVerifyStatus;
};

NS_CC_EXT_END

#endif // __CC_EXTENSION_CCSTORE_PAYMENT_TRANSACTION_H_


text:
var services = angular.module('sos.services');
services.service('skeletalService', function($rootScope, $log) {

  this.createSocket = function() {

    var socket = io.connect('http://localhost:8008', {
      'reconnect': true,
      'reconnection delay': 500,
      'forceNew': true
    });

    // set up logger for error
    socket.on('error', function(err) {
      $log.warn("socket.io error:", err);
    });

    socket.on('disconnect', function(disc) {
      $log.warn("socket.io disconnect:", disc);
    });

    socket.on('reconnect_attempt', function(attempt) {
      $log.warn("socket.io reconnect attempt");
    });

    var trackedSkeletons = {};
    var TRACKINGID_PREFIX = "skel-";
    var XOFFSET = new SkeletalBody().SHAPESXOFFSET;
    var YOFFSET = new SkeletalBody().SHAPESYOFFSET;

    socket.on('bodyFrame', function(bodies){

      // sweep all tracked skeletons to mark as false (for eventual removal)
      angular.forEach(trackedSkeletons, function(skel, key) {
        skel.setActiveStatus(false);
      });

      angular.forEach(bodies, function(body) {
        var trackingId = TRACKINGID_PREFIX + body.trackingId;
        var skel = trackedSkeletons[trackingId];

        // if skeleton exists, just set active status to true and
        // update the data payload
        if(skel) {
	  trackedSkeletons[trackingId].setActiveStatus(true);
	  trackedSkeletons[trackingId].setBodyData(body);
        } else {
	  skel = new SkeletalBody();
	  trackedSkeletons[trackingId] = skel;
	  skel.setBodyData(body);
          $rootScope.$broadcast('kinectNewSkeleton', skel);
        }
      });

      $rootScope.$broadcast('kinectBodiesUpdate', trackedSkeletons);

      // why for the love of $DEITY is there no `map`?
      var inputs = [];
      angular.forEach(trackedSkeletons, function(skel, key) {
        var input = skel.getHandPointerPoint();
        inputs.push(input.x + XOFFSET);
        inputs.push(input.y + YOFFSET);
      });
      $rootScope.$broadcast('kinectInput', inputs);

      // we need to send a refresh because socket.io might not flush?
      // TODO: fix this, eliminate the need for this.
      socket.emit("refresh", "callback hell", function(data) {
        //console.log(data);
        // no-op.
        data = null;
      });
    });

    return socket;
  };
});


text:
// Lexical scanning for BUILD file parser.

package build

import (
	"bytes"
	"fmt"
	"strings"
	"unicode/utf8"

	"github.com/bazelbuild/buildtools/tables"
)

// Parse parses the input data and returns the corresponding parse tree.
//
// The filename is used only for generating error messages.
func Parse(filename string, data []byte) (*File, error) {
	in := newInput(filename, data)
	return in.parse()
}

// An input represents a single input file being parsed.
type input struct {
	// Lexing state.
	filename  string    // name of input file, for errors
	complete  []byte    // entire input
	remaining []byte    // remaining input
	token     []byte    // token being scanned
	lastToken string    // most recently returned token, for error messages
	pos       Position  // current input position
	comments  []Comment // accumulated comments
	endStmt   int       // position of the end of the current statement
	depth     int       // nesting of [ ] { } ( )
	cleanLine bool      // true if the current line only contains whitespace before the current position
	indent    int       // current line indentation in spaces
	indents   []int     // stack of indentation levels in spaces

	// Parser state.
	file       *File // returned top-level syntax tree
	parseError error // error encountered during parsing

	// Comment assignment state.
	pre  []Expr // all expressions, in preorder traversal
	post []Expr // all expressions, in postorder traversal
}

func newInput(filename string, data []byte) *input {
	return &input{
		filename:  filename,
		complete:  data,
		remaining: data,
		pos:       Position{Line: 1, LineRune: 1, Byte: 0},
		cleanLine: true,
		indents:   []int{0},
	}
}

func (in *input) currentIndent() int {
	return in.indents[len(in.indents)-1]
}

// parse parses the input file.
func (in *input) parse() (f *File, err error) {
	// The parser panics for both routine errors like syntax errors
	// and for programmer bugs like array index errors.
	// Turn both into error returns. Catching bug panics is
	// especially important when processing many files.
	defer func() {
		if e := recover(); e != nil {
			if e == in.parseError {
				err = in.parseError
			} else {
				err = fmt.Errorf("%s:%d:%d: internal error: %v", in.filename, in.pos.Line, in.pos.LineRune, e)
			}
		}
	}()

	// Invoke the parser generated from parse.y.
	yyParse(in)
	if in.parseError != nil {
		return nil, in.parseError
	}
	in.file.Path = in.filename

	// Assign comments to nearby syntax.
	in.assignComments()

	return in.file, nil
}

// Error is called to report an error.
// When called by the generated code s is always "syntax error".
// Error does not return: it panics.
func (in *input) Error(s string) {
	if s == "syntax error" && in.lastToken != "" {
		s += " near " + in.lastToken
	}
	in.parseError = fmt.Errorf("%s:%d:%d: %v", in.filename, in.pos.Line, in.pos.LineRune, s)
	panic(in.parseError)
}

// eof reports whether the input has reached end of file.
func (in *input) eof() bool {
	return len(in.remaining) == 0
}

// peekRune returns the next rune in the input without consuming it.
func (in *input) peekRune() int {
	if len(in.remaining) == 0 {
		return 0
	}
	r, _ := utf8.DecodeRune(in.remaining)
	return int(r)
}

// readRune consumes and returns the next rune in the input.
func (in *input) readRune() int {
	if len(in.remaining) == 0 {
		in.Error("internal lexer error: readRune at EOF")
	}
	r, size := utf8.DecodeRune(in.remaining)
	in.remaining = in.remaining[size:]
	if r == '\n' {
		in.pos.Line++
		in.pos.LineRune = 1
	} else {
		in.pos.LineRune++
	}
	in.pos.Byte += size
	return int(r)
}

// startToken marks the beginning of the next input token.
// It must be followed by a call to endToken, once the token has
// been consumed using readRune.
func (in *input) startToken(val *yySymType) {
	in.token = in.remaining
	val.tok = ""
	val.pos = in.pos
}

// yySymType (used in the next few functions) is defined by the
// generated parser. It is a struct containing all the fields listed
// in parse.y's %union [sic] section.

// endToken marks the end of an input token.
// It records the actual token string in val.tok if the caller
// has not done that already.
func (in *input) endToken(val *yySymType) {
	if val.tok == "" {
		tok := string(in.token[:len(in.token)-len(in.remaining)])
		val.tok = tok
		in.lastToken = val.tok
	}
}

// Lex is called from the generated parser to obtain the next input token.
// It returns the token value (either a rune like '+' or a symbolic token _FOR)
// and sets val to the data associated with the token.
//
// For all our input tokens, the associated data is
// val.Pos (the position where the token begins)
// and val.Token (the input string corresponding to the token).
func (in *input) Lex(val *yySymType) int {
	// Skip past spaces, stopping at non-space or EOF.
	countNL := 0 // number of newlines we've skipped past
	for !in.eof() {
		// If a single statement is split into multiple lines, we don't need
		// to track indentations and unindentations within these lines. For example:
		//
		// def f(
		//     # This indentation should be ignored
		//     x):
		//  # This unindentation should be ignored
		//  # Actual indentation is from 0 to 2 spaces here
		//  return x
		//
		// If the --format_bzl flag is set to false, for legacy reason we track the end of each
		// code block defined at the top level instead the end of the current statement.
		//
		// To handle these cases, when we reach the beginning of a statement (or
		// top-level code block), we scan forward to see where
		// it should end and record the number of input bytes remaining
		// at that endpoint. When we reach that point in the input, we
		// insert an implicit semicolon to force the two expressions
		// to stay separate (only if --format_bzl is set to false, for legacy reasons).
		// We also set in.endStmt = 0 as a signal that we nee to track indentation levels.
		//
		if in.endStmt != 0 && len(in.remaining) == in.endStmt {
			in.endStmt = 0
			if !tables.FormatBzlFiles {
				in.lastToken = "implicit ;"
				val.tok = ";"
				return ';'
			}
		}

		// Skip over spaces. Count newlines so we can give the parser
		// information about where top-level blank lines are,
		// for top-level comment assignment.
		c := in.peekRune()
		if c == ' ' || c == '\t' || c == '\r' || c == '\n' {
			if c == '\n' {
				in.indent = 0
				in.cleanLine = true
				if in.endStmt == 0 {
					// Not in a statememt. Tell parser about top-level blank line.
					in.startToken(val)
					in.readRune()
					in.endToken(val)
					return '\n'
				}
				countNL++
			} else if c == ' ' && in.cleanLine {
				in.indent++
			}
			in.readRune()
			continue
		}

		// Comment runs to end of line.
		if c == '#' {
			// If a line contains just a comment its indentation level doesn't matter.
			// Reset it to zero.
			in.indent = 0
			in.cleanLine = true

			// Is this comment the only thing on its line?
			// Find the last \n before this # and see if it's all
			// spaces from there to here.
			// If it's a suffix comment but the last non-space symbol before
			// it is one of (, [, or {, treat it as a line comment that should be
			// put inside the corresponding block.
			i := bytes.LastIndex(in.complete[:in.pos.Byte], []byte("\n"))
			prefix := bytes.TrimSpace(in.complete[i+1 : in.pos.Byte])
			isSuffix := true
			if len(prefix) == 0 ||
				prefix[len(prefix)-1] == '[' ||
				prefix[len(prefix)-1] == '(' ||
				prefix[len(prefix)-1] == '{' {
				isSuffix = false
			}

			// Consume comment.
			in.startToken(val)
			for len(in.remaining) > 0 && in.readRune() != '\n' {
			}
			in.endToken(val)

			val.tok = strings.TrimRight(val.tok, "\n")
			in.lastToken = "comment"

			// If we are at top level (not in a rule), hand the comment to
			// the parser as a _COMMENT token. The grammar is written
			// to handle top-level comments itself.
			if in.endStmt == 0 {
				// Not in a statement. Tell parser about top-level comment.
				return _COMMENT
			}

			// Otherwise, save comment for later attachment to syntax tree.
			if countNL > 1 {
				in.comments = append(in.comments, Comment{val.pos, "", false})
			}
			in.comments = append(in.comments, Comment{val.pos, val.tok, isSuffix})
			countNL = 1
			continue
		}

		if c == '\\' && len(in.remaining) >= 2 && in.remaining[1] == '\n' {
			// We can ignore a trailing \ at end of line.
			in.readRune()
			continue
		}

		// Found non-space non-comment.
		break
	}

	// Check for changes in indentation
	// Skip if --format_bzl is set to false, if we're inside a statement, or if there were non-space
	// characters before in the current line.
	if tables.FormatBzlFiles && in.endStmt == 0 && in.cleanLine {
		if in.indent > in.currentIndent() {
			// A new indentation block starts
			in.indents = append(in.indents, in.indent)
			in.lastToken = "indent"
			in.cleanLine = false
			return _INDENT
		} else if in.indent < in.currentIndent() {
			// An indentation block ends
			in.indents = in.indents[:len(in.indents)-1]

			// It's a syntax error if the current line indentation level in now greater than
			// currentIndent(), should be either equal (a parent block continues) or still less
			// (need to unindent more).
			if in.indent > in.currentIndent() {
				in.pos = val.pos
				in.Error("unexpected indentation")
			}
			in.lastToken = "unindent"
			return _UNINDENT
		}
	}

	in.cleanLine = false

	// If the file ends with an indented block, return the corresponding amounts of unindents.
	if in.eof() && in.currentIndent() > 0 {
		in.indents = in.indents[:len(in.indents)-1]
		in.lastToken = "unindent"
		return _UNINDENT
	}

	// Found the beginning of the next token.
	in.startToken(val)
	defer in.endToken(val)

	// End of file.
	if in.eof() {
		in.lastToken = "EOF"
		return _EOF
	}

	// If endStmt is 0, we need to recompute where the end
	// of the next statement is, so that we can
	// generate a virtual end-of-rule semicolon (see above).
	if in.endStmt == 0 {
		in.endStmt = len(in.skipStmt(in.remaining))
		if in.endStmt == 0 {
			// skipStmt got confused.
			// No more virtual semicolons.
			in.endStmt = -1
		}
	}

	// Punctuation tokens.
	switch c := in.peekRune(); c {
	case '[', '(', '{':
		in.depth++
		in.readRune()
		return c

	case ']', ')', '}':
		in.depth--
		in.readRune()
		return c

	case '.', '-', '%', ':', ';', ',', '/', '*': // single-char tokens
		in.readRune()
		return c

	case '<', '>', '=', '!', '+': // possibly followed by =
		in.readRune()
		if in.peekRune() == '=' {
			in.readRune()
			switch c {
			case '<':
				return _LE
			case '>':
				return _GE
			case '=':
				return _EQ
			case '!':
				return _NE
			case '+':
				return _ADDEQ
			}
		}
		return c

	case 'r': // possible beginning of raw quoted string
		if len(in.remaining) < 2 || in.remaining[1] != '"' && in.remaining[1] != '\'' {
			break
		}
		in.readRune()
		c = in.peekRune()
		fallthrough

	case '"', '\'': // quoted string
		quote := c
		if len(in.remaining) >= 3 && in.remaining[0] == byte(quote) && in.remaining[1] == byte(quote) && in.remaining[2] == byte(quote) {
			// Triple-quoted string.
			in.readRune()
			in.readRune()
			in.readRune()
			var c1, c2, c3 int
			for {
				if in.eof() {
					in.pos = val.pos
					in.Error("unexpected EOF in string")
				}
				c1, c2, c3 = c2, c3, in.readRune()
				if c1 == quote && c2 == quote && c3 == quote {
					break
				}
				if c3 == '\\' {
					if in.eof() {
						in.pos = val.pos
						in.Error("unexpected EOF in string")
					}
					in.readRune()
				}
			}
		} else {
			in.readRune()
			for {
				if in.eof() {
					in.pos = val.pos
					in.Error("unexpected EOF in string")
				}
				if in.peekRune() == '\n' {
					in.Error("unexpected newline in string")
				}
				c := in.readRune()
				if c == quote {
					break
				}
				if c == '\\' {
					if in.eof() {
						in.pos = val.pos
						in.Error("unexpected EOF in string")
					}
					in.readRune()
				}
			}
		}
		in.endToken(val)
		s, triple, err := unquote(val.tok)
		if err != nil {
			in.Error(fmt.Sprint(err))
		}
		val.str = s
		val.triple = triple
		return _STRING
	}

	// Checked all punctuation. Must be identifier token.
	if c := in.peekRune(); !isIdent(c) {
		in.Error(fmt.Sprintf("unexpected input character %#q", c))
	}

	if !tables.FormatBzlFiles {
		// Look for raw Python block (class, def, if, etc at beginning of line) and pass through.
		if in.depth == 0 && in.pos.LineRune == 1 && hasPythonPrefix(in.remaining) {
			// Find end of Python block and advance input beyond it.
			// Have to loop calling readRune in order to maintain line number info.
			rest := in.skipStmt(in.remaining)
			for len(in.remaining) > len(rest) {
				in.readRune()
			}
			return _PYTHON
		}
	}

	// Scan over alphanumeric identifier.
	for {
		c := in.peekRune()
		if !isIdent(c) {
			break
		}
		in.readRune()
	}

	// Call endToken to set val.tok to identifier we just scanned,
	// so we can look to see if val.tok is a keyword.
	in.endToken(val)
	if k := keywordToken[val.tok]; k != 0 {
		return k
	}

	return _IDENT
}

// isIdent reports whether c is an identifier rune.
// We treat all non-ASCII runes as identifier runes.
func isIdent(c int) bool {
	return '0' <= c && c <= '9' ||
		'A' <= c && c <= 'Z' ||
		'a' <= c && c <= 'z' ||
		c == '_' ||
		c >= 0x80
}

// keywordToken records the special tokens for
// strings that should not be treated as ordinary identifiers.
var keywordToken = map[string]int{
	"and":    _AND,
	"for":    _FOR,
	"if":     _IF,
	"else":   _ELSE,
	"in":     _IN,
	"is":     _IS,
	"lambda": _LAMBDA,
	"not":    _NOT,
	"or":     _OR,
	"def":    _DEF,
}

// Python scanning.
// About 1% of BUILD files embed arbitrary Python into the file.
// We do not attempt to parse it. Instead, we lex just enough to scan
// beyond it, treating the Python block as an unintepreted blob.

// hasPythonPrefix reports whether p begins with a keyword that would
// introduce an uninterpreted Python block.
func hasPythonPrefix(p []byte) bool {
	if tables.FormatBzlFiles {
		return false
	}

	for _, pre := range prefixes {
		if hasPrefixSpace(p, pre) {
			return true
		}
	}
	return false
}

// These keywords introduce uninterpreted Python blocks.
var prefixes = []string{
	"assert",
	"class",
	"def",
	"del",
	"for",
	"if",
	"try",
}

// hasPrefixSpace reports whether p begins with pre followed by a space or colon.
func hasPrefixSpace(p []byte, pre string) bool {
	if len(p) <= len(pre) || p[len(pre)] != ' ' && p[len(pre)] != '\t' && p[len(pre)] != ':' {
		return false
	}
	for i := range pre {
		if p[i] != pre[i] {
			return false
		}
	}
	return true
}

func isBlankOrComment(b []byte) bool {
	for _, c := range b {
		if c == '#' || c == '\n' {
			return true
		}
		if c != ' ' && c != '\t' && c != '\r' {
			return false
		}
	}
	return true
}

// hasPythonContinuation reports whether p begins with a keyword that
// continues an uninterpreted Python block.
func hasPythonContinuation(p []byte) bool {
	for _, pre := range continuations {
		if hasPrefixSpace(p, pre) {
			return true
		}
	}
	return false
}

// These keywords continue uninterpreted Python blocks.
var continuations = []string{
	"except",
	"else",
}

// skipStmt returns the data remaining after the uninterpreted
// Python block beginning at p. It does not advance the input position.
// (The only reason for the input receiver is to be able to call in.Error.)
func (in *input) skipStmt(p []byte) []byte {
	quote := byte(0)     // if non-zero, the kind of quote we're in
	tripleQuote := false // if true, the quote is a triple quote
	depth := 0           // nesting depth for ( ) [ ] { }
	var rest []byte      // data after the Python block

	defer func() {
		if quote != 0 {
			in.Error("EOF scanning Python quoted string")
		}
	}()

	// Scan over input one byte at a time until we find
	// an unindented, non-blank, non-comment line
	// outside quoted strings and brackets.
	for i := 0; i < len(p); i++ {
		c := p[i]
		if quote != 0 && c == quote && !tripleQuote {
			quote = 0
			continue
		}
		if quote != 0 && c == quote && tripleQuote && i+2 < len(p) && p[i+1] == quote && p[i+2] == quote {
			i += 2
			quote = 0
			tripleQuote = false
			continue
		}
		if quote != 0 {
			if c == '\\' {
				i++ // skip escaped char
			}
			continue
		}
		if c == '\'' || c == '"' {
			if i+2 < len(p) && p[i+1] == c && p[i+2] == c {
				quote = c
				tripleQuote = true
				i += 2
				continue
			}
			quote = c
			continue
		}

		if depth == 0 && i > 0 && p[i-1] == '\n' && (i < 2 || p[i-2] != '\\') {
			// Possible stopping point. Save the earliest one we find.
			if rest == nil {
				rest = p[i:]
			}

			if tables.FormatBzlFiles {
				// In the bzl files mode we only care about the end of the statement, we've found it.
				return rest
			}
			// In the legacy mode we need to find where the current block ends
			if !isBlankOrComment(p[i:]) {
				if !hasPythonContinuation(p[i:]) && c != ' ' && c != '\t' {
					// Yes, stop here.
					return rest
				}
				// Not a stopping point after all.
				rest = nil
			}
		}

		switch c {
		case '#':
			// Skip comment.
			for i < len(p) && p[i] != '\n' {
				i++
			}

		case '(', '[', '{':
			depth++

		case ')', ']', '}':
			depth--
		}
	}
	return rest
}

// Comment assignment.
// We build two lists of all subexpressions, preorder and postorder.
// The preorder list is ordered by start location, with outer expressions first.
// The postorder list is ordered by end location, with outer expressions last.
// We use the preorder list to assign each whole-line comment to the syntax
// immediately following it, and we use the postorder list to assign each
// end-of-line comment to the syntax immediately preceding it.

// order walks the expression adding it and its subexpressions to the
// preorder and postorder lists.
func (in *input) order(v Expr) {
	if v != nil {
		in.pre = append(in.pre, v)
	}
	switch v := v.(type) {
	default:
		panic(fmt.Errorf("order: unexpected type %T", v))
	case nil:
		// nothing
	case *End:
		// nothing
	case *File:
		for _, stmt := range v.Stmt {
			in.order(stmt)
		}
	case *CommentBlock:
		// nothing
	case *CallExpr:
		in.order(v.X)
		for _, x := range v.List {
			in.order(x)
		}
		in.order(&v.End)
	case *PythonBlock:
		// nothing
	case *LiteralExpr:
		// nothing
	case *StringExpr:
		// nothing
	case *DotExpr:
		in.order(v.X)
	case *ListExpr:
		for _, x := range v.List {
			in.order(x)
		}
		in.order(&v.End)
	case *ListForExpr:
		in.order(v.X)
		for _, c := range v.For {
			in.order(c)
		}
		in.order(&v.End)
	case *SetExpr:
		for _, x := range v.List {
			in.order(x)
		}
		in.order(&v.End)
	case *ForClauseWithIfClausesOpt:
		in.order(v.For)
		for _, c := range v.Ifs {
			in.order(c)
		}
	case *ForClause:
		for _, name := range v.Var {
			in.order(name)
		}
		in.order(v.Expr)
	case *IfClause:
		in.order(v.Cond)
	case *KeyValueExpr:
		in.order(v.Key)
		in.order(v.Value)
	case *DictExpr:
		for _, x := range v.List {
			in.order(x)
		}
		in.order(&v.End)
	case *TupleExpr:
		for _, x := range v.List {
			in.order(x)
		}
		in.order(&v.End)
	case *UnaryExpr:
		in.order(v.X)
	case *BinaryExpr:
		in.order(v.X)
		in.order(v.Y)
	case *ConditionalExpr:
		in.order(v.Then)
		in.order(v.Test)
		in.order(v.Else)
	case *ParenExpr:
		in.order(v.X)
		in.order(&v.End)
	case *SliceExpr:
		in.order(v.X)
		in.order(v.From)
		in.order(v.To)
		in.order(v.Step)
	case *IndexExpr:
		in.order(v.X)
		in.order(v.Y)
	case *LambdaExpr:
		for _, name := range v.Var {
			in.order(name)
		}
		in.order(v.Expr)
	case *FuncDef:
		for _, x := range v.Args {
			in.order(x)
		}
		for _, x := range v.Body.Statements {
			in.order(x)
		}
	}
	if v != nil {
		in.post = append(in.post, v)
	}
}

// assignComments attaches comments to nearby syntax.
func (in *input) assignComments() {
	// Generate preorder and postorder lists.
	in.order(in.file)

	// Split into whole-line comments and suffix comments.
	var line, suffix []Comment
	for _, com := range in.comments {
		if com.Suffix {
			suffix = append(suffix, com)
		} else {
			line = append(line, com)
		}
	}

	// Assign line comments to syntax immediately following.
	for _, x := range in.pre {
		start, _ := x.Span()
		xcom := x.Comment()
		for len(line) > 0 && start.Byte >= line[0].Start.Byte {
			xcom.Before = append(xcom.Before, line[0])
			line = line[1:]
		}
	}

	// Remaining line comments go at end of file.
	in.file.After = append(in.file.After, line...)

	// Assign suffix comments to syntax immediately before.
	for i := len(in.post) - 1; i >= 0; i-- {
		x := in.post[i]

		// Do not assign suffix comments to file
		switch x.(type) {
		case *File:
			continue
		}

		_, end := x.Span()
		xcom := x.Comment()
		for len(suffix) > 0 && end.Byte <= suffix[len(suffix)-1].Start.Byte {
			xcom.Suffix = append(xcom.Suffix, suffix[len(suffix)-1])
			suffix = suffix[:len(suffix)-1]
		}
	}

	// We assigned suffix comments in reverse.
	// If multiple suffix comments were appended to the same
	// expression node, they are now in reverse. Fix that.
	for _, x := range in.post {
		reverseComments(x.Comment().Suffix)
	}

	// Remaining suffix comments go at beginning of file.
	in.file.Before = append(in.file.Before, suffix...)
}

// reverseComments reverses the []Comment list.
func reverseComments(list []Comment) {
	for i, j := 0, len(list)-1; i < j; i, j = i+1, j-1 {
		list[i], list[j] = list[j], list[i]
	}
}


text:
require 'test_helper'

module WebConsole
  class SessionTest < ActiveSupport::TestCase
    class LineAwareError < StandardError
      def self.raise
        ::Kernel.raise new(__LINE__)
      rescue => exc
        exc
      end

      attr_reader :line

      def initialize(line)
        @line = line
      end
    end

    setup do
      Session.inmemory_storage.clear
      @session = Session.new([binding])
    end

    test 'returns nil when a session is not found' do
      assert_nil Session.find("nonexistent session")
    end

    test 'find returns a persisted object' do
      assert_equal @session, Session.find(@session.id)
    end

    test 'can evaluate code in the currently selected binding' do
      assert_equal "=> 42\n", @session.eval('40 + 2')
    end

    test 'use first binding if no application bindings' do
      binding = Object.new.instance_eval do
        def eval(string)
          case string
          when '__FILE__' then framework
          when 'called?' then 'yes'
          end
        end

        self
      end

      session = Session.new([binding])
      assert_equal session.eval('called?'), "=> \"yes\"\n"
    end

    test '#from can create session from a single binding' do
      saved_line, saved_binding = __LINE__, binding
      Thread.current[:__web_console_binding] = saved_binding

      session = Session.from(__web_console_binding: saved_binding)

      assert_equal "=> #{saved_line}\n", session.eval('__LINE__')
    end

    test '#from can create session from an exception' do
      exc = LineAwareError.raise

      session = Session.from(__web_console_exception: exc)

      assert_equal "=> #{exc.line}\n", session.eval('__LINE__')
    end

    test '#from can switch to bindings' do
      exc, saved_line = LineAwareError.raise, __LINE__

      session = Session.from(__web_console_exception: exc)
      session.switch_binding_to(1)

      assert_equal "=> #{saved_line}\n", session.eval('__LINE__')
    end

    test '#from prioritizes exceptions over bindings' do
      exc, saved_line = LineAwareError.raise, __LINE__

      session = Session.from(__web_console_exception: exc, __web_console_binding: binding)
      session.switch_binding_to(1)

      assert_equal "=> #{saved_line}\n", session.eval('__LINE__')
    end
  end
end


text:
"""Runs a compilation command.

This script exists to avoid using complex shell commands in
gcc_toolchain.gni's tool("cxx") and tool("cc") in case the host running the
compiler does not have a POSIX-like shell (e.g. Windows).
"""

import argparse
import sys

import wrapper_utils

def main():
  parser = argparse.ArgumentParser(description=__doc__)
  parser.add_argument('--resource-whitelist',
                      help='Generate a resource whitelist for this target.',
                      metavar='PATH')
  parser.add_argument('command', nargs=argparse.REMAINDER,
                      help='Compilation command')
  args = parser.parse_args()

  returncode, stderr = wrapper_utils.CaptureCommandStderr(
      wrapper_utils.CommandToRun(args.command))

  used_resources = wrapper_utils.ExtractResourceIdsFromPragmaWarnings(stderr)
  sys.stderr.write(stderr)

  if args.resource_whitelist:
    with open(args.resource_whitelist, 'w') as f:
      if used_resources:
        f.write('\n'.join(str(resource) for resource in used_resources))
        f.write('\n')

  return returncode

if __name__ == "__main__":
  sys.exit(main())


text:
[![No Maintenance Intended](http://unmaintained.tech/badge.svg)](http://unmaintained.tech/)

postgresql
==========

[![Build Status](https://travis-ci.org/kbrebanov/ansible-postgresql.svg?branch=master)](https://travis-ci.org/kbrebanov/ansible-postgresql)

Installs PostgreSQL

Requirements
------------

This role requires Ansible 1.9 or higher.

Role Variables
--------------

| Name               | Default | Description                      |
|:-------------------|:--------|:---------------------------------|
| postgresql_version | 9.5     | Version of PostgreSQL to install |

Dependencies
------------

None

Example Playbook
----------------

Install PostgreSQL
```yaml
- hosts: all
  roles:
    - kbrebanov.postgresql
```

License
-------

BSD

Author Information
------------------

Kevin Brebanov


text:
package org.apache.druid.math.expr;

import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import org.apache.druid.annotations.SubclassesMustOverrideEqualsAndHashCode;
import org.apache.druid.java.util.common.Cacheable;
import org.apache.druid.java.util.common.ISE;
import org.apache.druid.math.expr.vector.ExprVectorProcessor;
import org.apache.druid.query.cache.CacheKeyBuilder;

import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Base interface of Druid expression language abstract syntax tree nodes. All {@link Expr} implementations are
 * immutable.
 */
@SubclassesMustOverrideEqualsAndHashCode
public interface Expr extends Cacheable
{

  String NULL_LITERAL = "null";
  Joiner ARG_JOINER = Joiner.on(", ");

  /**
   * Indicates expression is a constant whose literal value can be extracted by {@link Expr#getLiteralValue()},
   * making evaluating with arguments and bindings unecessary
   */
  default boolean isLiteral()
  {
    // Overridden by things that are literals.
    return false;
  }

  default boolean isNullLiteral()
  {
    // Overridden by things that are null literals.
    return false;
  }

  /**
   * Returns the value of expr if expr is a literal, or throws an exception otherwise.
   *
   * @return {@link ConstantExpr}'s literal value
   *
   * @throws IllegalStateException if expr is not a literal
   */
  @Nullable
  default Object getLiteralValue()
  {
    // Overridden by things that are literals.
    throw new ISE("Not a literal");
  }

  /**
   * Returns an {@link IdentifierExpr} if it is one, else null
   */
  @Nullable
  default IdentifierExpr getIdentifierExprIfIdentifierExpr()
  {
    return null;
  }

  /**
   * Returns the string identifier of an {@link IdentifierExpr}, else null. Use this method to analyze an {@link Expr}
   * tree when trying to distinguish between different {@link IdentifierExpr} with the same
   * {@link IdentifierExpr#binding}. Do NOT use this method to analyze the input binding (e.g. backing column name),
   * use {@link #getBindingIfIdentifier} instead.
   */
  @Nullable
  default String getIdentifierIfIdentifier()
  {
    // overridden by things that are identifiers
    return null;
  }

  /**
   * Returns the string key to use to get a value from {@link Expr.ObjectBinding} of an {@link IdentifierExpr},
   * else null. Use this method to analyze the inputs required to an {@link Expr} tree (e.g. backing column name).
   */
  @Nullable
  default String getBindingIfIdentifier()
  {
    // overridden by things that are identifiers
    return null;
  }

  /**
   * Evaluate the {@link Expr} with the bindings which supply {@link IdentifierExpr} with their values, producing an
   * {@link ExprEval} with the result.
   */
  ExprEval eval(ObjectBinding bindings);

  /**
   * Convert the {@link Expr} back into parseable string that when parsed with
   * {@link Parser#parse(String, ExprMacroTable)} will produce an equivalent {@link Expr}.
   */
  String stringify();

  /**
   * Programatically rewrite the {@link Expr} tree with a {@link Shuttle}. Each {@link Expr} is responsible for
   * ensuring the {@link Shuttle} can visit all of its {@link Expr} children, as well as updating its children
   * {@link Expr} with the results from the {@link Shuttle}, before finally visiting an updated form of itself.
   */
  Expr visit(Shuttle shuttle);

  /**
   * Examine the usage of {@link IdentifierExpr} children of an {@link Expr}, constructing a {@link BindingAnalysis}
   */
  BindingAnalysis analyzeInputs();

  /**
   * Given an {@link InputBindingInspector}, compute what the output {@link ExprType} will be for this expression.
   *
   * In the vectorized expression engine, if {@link #canVectorize(InputBindingInspector)} returns true, a return value
   * of null MUST ONLY indicate that the expression has all null inputs (non-existent columns) or null constants for
   * the entire expression. Otherwise, all vectorizable expressions must produce an output type to correctly operate
   * with the vectorized engine.
   *
   * Outside of the context of vectorized expressions, a return value of null can also indicate that the given type
   * information was not enough to resolve the output type, so the expression must be evaluated using default
   * {@link #eval} handling where types are only known after evaluation, through {@link ExprEval#type}, such as
   * transform expressions at ingestion time
   */
  @Nullable
  default ExprType getOutputType(InputBindingInspector inspector)
  {
    return null;
  }

  /**
   * Check if an expression can be 'vectorized', for a given set of inputs. If this method returns true,
   * {@link #buildVectorized} is expected to produce a {@link ExprVectorProcessor} which can evaluate values in batches
   * to use with vectorized query engines.
   * @param inspector
   */
  default boolean canVectorize(InputBindingInspector inspector)
  {
    return false;
  }

  /**
   * Builds a 'vectorized' expression processor, that can operate on batches of input values for use in vectorized
   * query engines.
   * @param inspector
   */
  default <T> ExprVectorProcessor<T> buildVectorized(VectorInputBindingInspector inspector)
  {
    throw Exprs.cannotVectorize(this);
  }

  @Override
  default byte[] getCacheKey()
  {
    return new CacheKeyBuilder(Exprs.EXPR_CACHE_KEY).appendString(stringify()).build();
  }

  /**
   * Mechanism to supply input types for the bindings which will back {@link IdentifierExpr}, to use in the aid of
   * inferring the output type of an expression with {@link #getOutputType}. A null value means that either the binding
   * doesn't exist, or, that the type information is unavailable.
   */
  interface InputBindingInspector
  {
    /**
     * Get the {@link ExprType} from the backing store for a given identifier (this is likely a column, but could be other
     * things depending on the backing adapter)
     */
    @Nullable
    ExprType getType(String name);

    /**
     * Check if all provided {@link Expr} can infer the output type as {@link ExprType#isNumeric} with a value of true.
     *
     * There must be at least one expression with a computable numeric output type for this method to return true.
     */
    default boolean areNumeric(List<Expr> args)
    {
      boolean numeric = true;
      for (Expr arg : args) {
        ExprType argType = arg.getOutputType(this);
        if (argType == null) {
          continue;
        }
        numeric &= argType.isNumeric();
      }
      return numeric;
    }

    /**
     * Check if all provided {@link Expr} can infer the output type as {@link ExprType#isNumeric} with a value of true.
     *
     * There must be at least one expression with a computable numeric output type for this method to return true.
     */
    default boolean areNumeric(Expr... args)
    {
      return areNumeric(Arrays.asList(args));
    }

    /**
     * Check if all provided {@link Expr} can infer the output type as {@link ExprType#isScalar()} (non-array) with a
     * value of true.
     *
     * There must be at least one expression with a computable scalar output type for this method to return true.
     */
    default boolean areScalar(List<Expr> args)
    {
      boolean scalar = true;
      for (Expr arg : args) {
        ExprType argType = arg.getOutputType(this);
        if (argType == null) {
          continue;
        }
        scalar &= argType.isScalar();
      }
      return scalar;
    }

    /**
     * Check if all provided {@link Expr} can infer the output type as {@link ExprType#isScalar()} (non-array) with a
     * value of true.
     *
     * There must be at least one expression with a computable scalar output type for this method to return true.
     */
    default boolean areScalar(Expr... args)
    {
      return areScalar(Arrays.asList(args));
    }

    /**
     * Check if every provided {@link Expr} computes {@link Expr#canVectorize(InputBindingInspector)} to a value of true
     */
    default boolean canVectorize(List<Expr> args)
    {
      boolean canVectorize = true;
      for (Expr arg : args) {
        canVectorize &= arg.canVectorize(this);
      }
      return canVectorize;
    }

    /**
     * Check if every provided {@link Expr} computes {@link Expr#canVectorize(InputBindingInspector)} to a value of true
     */
    default boolean canVectorize(Expr... args)
    {
      return canVectorize(Arrays.asList(args));
    }
  }

  /**
   * {@link InputBindingInspector} + vectorizations stuff for {@link #buildVectorized}
   */
  interface VectorInputBindingInspector extends InputBindingInspector
  {
    int getMaxVectorSize();
  }

  /**
   * Mechanism to supply values to back {@link IdentifierExpr} during expression evaluation
   */
  interface ObjectBinding
  {
    /**
     * Get value binding for string identifier of {@link IdentifierExpr}
     */
    @Nullable
    Object get(String name);
  }

  /**
   * Mechanism to supply batches of input values to a {@link ExprVectorProcessor} for optimized processing. Mirrors
   * the vectorized column selector interfaces, and includes {@link ExprType} information about all input bindings
   * which exist
   */
  interface VectorInputBinding extends VectorInputBindingInspector
  {
    <T> T[] getObjectVector(String name);

    long[] getLongVector(String name);

    double[] getDoubleVector(String name);

    @Nullable
    boolean[] getNullVector(String name);

    int getCurrentVectorSize();

    /**
     * Returns an integer that uniquely identifies the current position of the underlying vector offset, if this
     * binding is backed by a segment. This is useful for caching: it is safe to assume nothing has changed in the
     * offset so long as the id remains the same. See also: ReadableVectorOffset (in druid-processing)
     */
    int getCurrentVectorId();
  }

  /**
   * Mechanism to rewrite an {@link Expr}, implementing a {@link Shuttle} allows visiting all children of an
   * {@link Expr}, and replacing them as desired.
   */
  interface Shuttle
  {
    /**
     * Provide the {@link Shuttle} with an {@link Expr} to inspect and potentially rewrite.
     */
    Expr visit(Expr expr);
  }

  /**
   * Information about the context in which {@link IdentifierExpr} are used in a greater {@link Expr}, listing
   * the 'free variables' (total set of required input columns or values) and distinguishing between which identifiers
   * are used as scalar inputs and which are used as array inputs.
   *
   * This type is primarily used at query time when creating expression column selectors to decide if an expression
   * can properly deal with a multi-valued column input, and also to determine if certain optimizations can be taken.
   *
   * Current implementations of {@link #analyzeInputs()} provide context about {@link Function} and
   * {@link ApplyFunction} arguments which are direct children {@link IdentifierExpr} as scalar or array typed.
   * This is defined by {@link Function#getScalarInputs(List)}, {@link Function#getArrayInputs(List)} and
   * {@link ApplyFunction#getArrayInputs(List)}. Identifiers that are nested inside of argument expressions which
   * are other expression types will not be considered to belong directly to that function, and so are classified by the
   * context their children are using them as instead.
   *
   * This means in rare cases and mostly for "questionable" expressions which we still allow to function 'correctly',
   * these lists might not be fully reliable without a complete type inference system in place. Due to this shortcoming,
   * boolean values {@link BindingAnalysis#hasInputArrays()} and {@link BindingAnalysis#isOutputArray()} are provided to
   * allow functions to explicitly declare that they utilize array typed values, used when determining if some types of
   * optimizations can be applied when constructing the expression column value selector.
   *
   * @see Function#getScalarInputs
   * @see Function#getArrayInputs
   * @see ApplyFunction#getArrayInputs
   * @see Parser#applyUnappliedBindings
   * @see Parser#applyUnapplied
   * @see Parser#liftApplyLambda
   * @see org.apache.druid.segment.virtual.ExpressionSelectors#makeDimensionSelector
   * @see org.apache.druid.segment.virtual.ExpressionSelectors#makeColumnValueSelector
   */
  @SuppressWarnings("JavadocReference")
  class BindingAnalysis
  {
    private final ImmutableSet<IdentifierExpr> freeVariables;
    private final ImmutableSet<IdentifierExpr> scalarVariables;
    private final ImmutableSet<IdentifierExpr> arrayVariables;
    private final boolean hasInputArrays;
    private final boolean isOutputArray;

    BindingAnalysis()
    {
      this(ImmutableSet.of(), ImmutableSet.of(), ImmutableSet.of(), false, false);
    }

    BindingAnalysis(IdentifierExpr expr)
    {
      this(ImmutableSet.of(expr), ImmutableSet.of(), ImmutableSet.of(), false, false);
    }

    private BindingAnalysis(
        ImmutableSet<IdentifierExpr> freeVariables,
        ImmutableSet<IdentifierExpr> scalarVariables,
        ImmutableSet<IdentifierExpr> arrayVariables,
        boolean hasInputArrays,
        boolean isOutputArray
    )
    {
      this.freeVariables = freeVariables;
      this.scalarVariables = scalarVariables;
      this.arrayVariables = arrayVariables;
      this.hasInputArrays = hasInputArrays;
      this.isOutputArray = isOutputArray;
    }

    /**
     * Get the list of required column inputs to evaluate an expression ({@link IdentifierExpr#binding})
     */
    public List<String> getRequiredBindingsList()
    {
      return new ArrayList<>(getRequiredBindings());
    }

    /**
     * Get the set of required column inputs to evaluate an expression ({@link IdentifierExpr#binding})
     */
    public Set<String> getRequiredBindings()
    {
      return map(freeVariables, IdentifierExpr::getBindingIfIdentifier);
    }

    /**
     * Set of {@link IdentifierExpr#binding} which are used as scalar inputs to operators and functions.
     */
    Set<String> getScalarBindings()
    {
      return map(scalarVariables, IdentifierExpr::getBindingIfIdentifier);
    }

    /**
     * Set of {@link IdentifierExpr#binding} which are used as array inputs to operators, functions, and apply
     * functions.
     */
    public Set<String> getArrayBindings()
    {
      return map(arrayVariables, IdentifierExpr::getBindingIfIdentifier);
    }

    /**
     * Total set of 'free' inputs of an {@link Expr}, that are not supplied by a {@link LambdaExpr} binding
     */
    public Set<IdentifierExpr> getFreeVariables()
    {
      return freeVariables;
    }

    /**
     * Set of {@link IdentifierExpr#identifier} which are used as scalar inputs to operators and functions.
     */
    Set<String> getScalarVariables()
    {
      return map(scalarVariables, IdentifierExpr::getIdentifier);
    }

    /**
     * Set of {@link IdentifierExpr#identifier} which are used as array inputs to operators, functions, and apply
     * functions.
     */
    Set<String> getArrayVariables()
    {
      return map(arrayVariables, IdentifierExpr::getIdentifier);
    }

    /**
     * Returns true if any expression in the expression tree has any array inputs. Note that in some cases, this can be
     * true and {@link #getArrayBindings()} or {@link #getArrayVariables()} can be empty.
     *
     * This is because these collections contain identifiers/bindings which were classified as either scalar or array
     * inputs based on the context of their usage by {@link Expr#analyzeInputs()}, where as this value and
     * {@link #isOutputArray()} are set based on information reported by {@link Function#hasArrayInputs()},
     * {@link Function#hasArrayOutput()}, and {@link ApplyFunction#hasArrayOutput(LambdaExpr)}, without regards to
     * identifiers or anything else.
     */
    public boolean hasInputArrays()
    {
      return hasInputArrays;
    }

    /**
     * Returns true if any expression in this expression tree produces array outputs as reported by
     * {@link Function#hasArrayOutput()} or {@link ApplyFunction#hasArrayOutput(LambdaExpr)}
     */
    public boolean isOutputArray()
    {
      return isOutputArray;
    }

    /**
     * Combine with {@link BindingAnalysis} from {@link Expr#analyzeInputs()}
     */
    public BindingAnalysis with(Expr other)
    {
      return with(other.analyzeInputs());
    }

    /**
     * Combine (union) another {@link BindingAnalysis}
     */
    public BindingAnalysis with(BindingAnalysis other)
    {
      return new BindingAnalysis(
          ImmutableSet.copyOf(Sets.union(freeVariables, other.freeVariables)),
          ImmutableSet.copyOf(Sets.union(scalarVariables, other.scalarVariables)),
          ImmutableSet.copyOf(Sets.union(arrayVariables, other.arrayVariables)),
          hasInputArrays || other.hasInputArrays,
          isOutputArray || other.isOutputArray
      );
    }

    /**
     * Add set of arguments as {@link BindingAnalysis#scalarVariables} that are *directly* {@link IdentifierExpr},
     * else they are ignored.
     */
    public BindingAnalysis withScalarArguments(Set<Expr> scalarArguments)
    {
      Set<IdentifierExpr> moreScalars = new HashSet<>();
      for (Expr expr : scalarArguments) {
        final boolean isIdentiferExpr = expr.getIdentifierExprIfIdentifierExpr() != null;
        if (isIdentiferExpr) {
          moreScalars.add((IdentifierExpr) expr);
        }
      }
      return new BindingAnalysis(
          ImmutableSet.copyOf(Sets.union(freeVariables, moreScalars)),
          ImmutableSet.copyOf(Sets.union(scalarVariables, moreScalars)),
          arrayVariables,
          hasInputArrays,
          isOutputArray
      );
    }

    /**
     * Add set of arguments as {@link BindingAnalysis#arrayVariables} that are *directly* {@link IdentifierExpr},
     * else they are ignored.
     */
    BindingAnalysis withArrayArguments(Set<Expr> arrayArguments)
    {
      Set<IdentifierExpr> arrayIdentifiers = new HashSet<>();
      for (Expr expr : arrayArguments) {
        final boolean isIdentifierExpr = expr.getIdentifierExprIfIdentifierExpr() != null;
        if (isIdentifierExpr) {
          arrayIdentifiers.add((IdentifierExpr) expr);
        }
      }
      return new BindingAnalysis(
          ImmutableSet.copyOf(Sets.union(freeVariables, arrayIdentifiers)),
          scalarVariables,
          ImmutableSet.copyOf(Sets.union(arrayVariables, arrayIdentifiers)),
          hasInputArrays || !arrayArguments.isEmpty(),
          isOutputArray
      );
    }

    /**
     * Copy, setting if an expression has array inputs
     */
    BindingAnalysis withArrayInputs(boolean hasArrays)
    {
      return new BindingAnalysis(
          freeVariables,
          scalarVariables,
          arrayVariables,
          hasArrays || !arrayVariables.isEmpty(),
          isOutputArray
      );
    }

    /**
     * Copy, setting if an expression produces an array output
     */
    BindingAnalysis withArrayOutput(boolean isOutputArray)
    {
      return new BindingAnalysis(
          freeVariables,
          scalarVariables,
          arrayVariables,
          hasInputArrays,
          isOutputArray
      );
    }

    /**
     * Remove any {@link IdentifierExpr} that are from a {@link LambdaExpr}, since the {@link ApplyFunction} will
     * provide bindings for these variables.
     */
    BindingAnalysis removeLambdaArguments(Set<String> lambda)
    {
      return new BindingAnalysis(
          ImmutableSet.copyOf(freeVariables.stream().filter(x -> !lambda.contains(x.getIdentifier())).iterator()),
          ImmutableSet.copyOf(scalarVariables.stream().filter(x -> !lambda.contains(x.getIdentifier())).iterator()),
          ImmutableSet.copyOf(arrayVariables.stream().filter(x -> !lambda.contains(x.getIdentifier())).iterator()),
          hasInputArrays,
          isOutputArray
      );
    }

    // Use this instead of streams for better performance
    private static Set<String> map(
        Set<IdentifierExpr> variables,
        java.util.function.Function<IdentifierExpr, String> mapper
    )
    {
      Set<String> results = Sets.newHashSetWithExpectedSize(variables.size());
      for (IdentifierExpr variable : variables) {
        results.add(mapper.apply(variable));
      }
      return results;
    }
  }
}


text:
template<>
TestingPrefServiceBase<PrefServiceSyncable, PrefRegistrySyncable>::
TestingPrefServiceBase(TestingPrefStore* managed_prefs,
                       TestingPrefStore* user_prefs,
                       TestingPrefStore* recommended_prefs,
                       PrefRegistrySyncable* pref_registry,
                       PrefNotifierImpl* pref_notifier)
    : PrefServiceSyncable(
        pref_notifier,
        new PrefValueStore(
            managed_prefs,
            NULL,
            NULL,
            user_prefs,
            recommended_prefs,
            pref_registry->defaults(),
            pref_notifier),
        user_prefs,
        pref_registry,
        base::Bind(
            &TestingPrefServiceBase<PrefServiceSyncable,
                                    PrefRegistrySyncable>::HandleReadError),
        false),
      managed_prefs_(managed_prefs),
      user_prefs_(user_prefs),
      recommended_prefs_(recommended_prefs) {
}

TestingPrefServiceSyncable::TestingPrefServiceSyncable()
    : TestingPrefServiceBase<PrefServiceSyncable, PrefRegistrySyncable>(
        new TestingPrefStore(),
        new TestingPrefStore(),
        new TestingPrefStore(),
        new PrefRegistrySyncable(),
        new PrefNotifierImpl()) {
}

TestingPrefServiceSyncable::~TestingPrefServiceSyncable() {
}

PrefRegistrySyncable* TestingPrefServiceSyncable::registry() {
  return static_cast<PrefRegistrySyncable*>(DeprecatedGetPrefRegistry());
}


text:
#ifndef SPIRE_ENTITY_SYSTEM_GENERICSYSTEM_HPP
#define SPIRE_ENTITY_SYSTEM_GENERICSYSTEM_HPP

// GenericSystems are not associated with any one core. You can use a system
// with any number of cores. All important functions are static and don't
// use any stored state. You can create instances of this class and use
// the BaseSystem interface to iterate over all systems with the
// walkComponentsOver override.

#include <es-log/trace-log.h>
#include <iostream>
#include <array>
#include <set>          // Only used in a corner case of walkComponents where
                        // all components are optional.
#include <type_traits>
#include "ESCoreBase.hpp"
#include "src/ComponentContainer.hpp"
#include "src/TemplateID.hpp"
#include "src/ComponentGroup.hpp"
#include <spire/scishare.h>

namespace spire {

namespace gs_detail
{

/// See: http://stackoverflow.com/questions/10766112/c11-i-can-go-from-multiple-args-to-tuple-but-can-i-go-from-tuple-to-multiple
template <typename C, typename F, typename Tuple, bool Done, int Total, int... N>
struct call_impl
{
  static void call(ESCoreBase& core, uint64_t sequence, C c, F f, Tuple && t)
  {
    call_impl<C, F, Tuple, Total == 1 + sizeof...(N), Total, N..., sizeof...(N)>::call(core, sequence, c, f, std::forward<Tuple>(t));
  }
};

template <typename C, typename F, typename Tuple, int Total, int... N>
struct call_impl<C, F, Tuple, bool(true), Total, N...>
{
  static void call(ESCoreBase& core, uint64_t sequence, C c, F f, Tuple && t)
  {
    // Call the variadic member function (c.*f) with expanded template
    // parameter list (std::get<N>(std::forward<Tuple>(t))...).
    (c->*f)(core, sequence, std::get<N>(std::forward<Tuple>(t))...);
  }
};

/// C = class type, F = function type.
/// c = class instance, f = member function pointer.
template <typename C, typename F, typename Tuple>
void call(ESCoreBase& core, uint64_t sequence, C c, F f, Tuple && t)
{
  typedef typename std::decay<Tuple>::type ttype;
  call_impl<C, F, Tuple, 0 == std::tuple_size<ttype>::value, std::tuple_size<ttype>::value>::call(core, sequence, c, f, std::forward<Tuple>(t));
}

}

// Unfortunately, this part still does not compile in VS2013. Seems safe to comment out.
#ifndef WIN32
/// See: http://stackoverflow.com/questions/18986560/check-variadic-templates-parameters-for-uniqueness?lq=1
/// The mpl namespace contains everything to implement is_unique. It is used in
/// the static assertion at the beginning of GenericSystem below.
namespace mpl
{
template< class T > using invoke = typename T :: type ;
template< class C, class I, class E > using if_t     = invoke< std::conditional< C{}, I, E> >;
template< class T > struct id{};
struct empty{};
template< class A, class B > struct base : A, B {};
template< class B , class ... > struct is_unique_impl;
template< class B > struct is_unique_impl<B>: std::true_type{};
template< class B, class T, class ... U>
struct is_unique_impl<B, T, U...> : if_t< std::is_base_of< id<T>, B>, std::false_type, is_unique_impl< base<B,id<T>>, U...> >{};

template< class ...T >struct is_unique : is_unique_impl< empty, T ... > {};
} // mpl
#endif

/// Base class implementation of generic system. You do not need instances of
/// this class in order to use it. All important functions are static.
template <bool GroupComponents, typename... Ts>
class GenericSystem : public BaseSystem
{
public:
#ifndef WIN32
  static_assert(mpl::is_unique<Ts...>::value, "GenericSystem does not allow duplicate component types.");
#endif
  GenericSystem()           {}
  virtual ~GenericSystem()  {}

  bool walkEntity(ESCoreBase& core, uint64_t entityID) override
  {
    if (sizeof...(Ts) == 0)
      return false;

    std::array<BaseComponentContainer*, sizeof...(Ts)> baseComponents = { core.getComponentContainer(TemplateID<Ts>::getID())... };
    std::array<int, sizeof...(Ts)> indices;
    std::array<int, sizeof...(Ts)> nextIndices;
    std::array<bool, sizeof...(Ts)> isStatic;
    std::array<int, sizeof...(Ts)> numComponents;
    std::array<bool, sizeof...(Ts)> optionalComponents = { isComponentOptional(TemplateID<Ts>::getID())... }; // Detect optional components via overriden function call (simplest).

    // Arrays containing components arrays. BuildComponentArrays was made to be
    // called before we correct baseComponents with getEmptyContainer.
    std::tuple<typename ComponentContainer<Ts>::ComponentItem*...> componentArrays;
    BuildComponentArraysAndIndicesWithID<0, Ts...>::exec(baseComponents, componentArrays, indices, entityID);

    std::tuple<Ts*...> values;  ///< Values that will be passed into execute.
    std::tuple<ComponentGroup<Ts>...> groupValues;  ///< Grouped values that will be passed into group execute.

    AddComponentsToGroupInputs<0, Ts...>::exec(core, baseComponents, groupValues);

    bool execute = true;
    for (size_t i = 0; i < sizeof...(Ts); i++)
    {
      if (!baseComponents[i])
        baseComponents[i] = ESCoreBase::getEmptyContainer();

      isStatic[i] = baseComponents[i]->isStatic();
      numComponents[i] = static_cast<int>(baseComponents[i]->getNumComponents());

      // Note: For static components, getComponentItemIndexWithSequence always
      //       returns 0. Which is the correct index to start at.
      if (indices[i] == -1)
      {
        if (!optionalComponents[i])
        {
          execute = false;
          break;
        }
        else
        {
          // For optional components that we don't find, we set the index to the
          // size of the components array. When recursively executing, this
          // will continue the recursion with no extra branches as a result
          // of this component.
          indices[i] = numComponents[i];
        }
      }
    }

    if (execute)
    {
      if (!GroupComponents)
        RecurseExecute<0, Ts...>::exec(core, this, componentArrays, numComponents,
                                       indices, optionalComponents, isStatic,
                                       nextIndices, values, entityID);
      else
        GroupExecute<0, Ts...>::exec(core, this, componentArrays, numComponents,
                                     indices, optionalComponents, isStatic,
                                     nextIndices, groupValues, entityID);
      return true;
    }
    else
    {
      return false;
    }
  }

  void walkComponents(ESCoreBase& core) override
  {
    preWalkComponents(core);
    walkComponentsInternal(core);
    postWalkComponents(core);
  }

  //TODO: log the **** out of this function
  void walkComponentsInternal(ESCoreBase& core)
  {
    if (sizeof...(Ts) == 0)
      return;

    std::array<BaseComponentContainer*, sizeof...(Ts)> baseComponents = { core.getComponentContainer(TemplateID<Ts>::getID())... };
    std::array<int, sizeof...(Ts)> indices;
    std::array<int, sizeof...(Ts)> nextIndices;
    std::array<int, sizeof...(Ts)> numComponents;
    std::array<bool, sizeof...(Ts)> isStatic;
    std::array<bool, sizeof...(Ts)> optionalComponents = { isComponentOptional(TemplateID<Ts>::getID())... }; // Detect optional components via overriden function call (simplest).

    // Arrays containing components arrays. BuildComponentArrays was made to be
    // called before we correct baseComponents with getEmptyContainer.
    std::tuple<typename ComponentContainer<Ts>::ComponentItem*...> componentArrays;
    BuildComponentArrays<0, Ts...>::exec(baseComponents, componentArrays);

    // Start off with std::numeric_limits max on lowest upper sequence,
    // and check for optional components. No optional components are allowed
    // to be the leading sequence. If all we find are optional components,
    // we write out a warning. We could also iterate through all components
    // and combinations in existence. We may implement this later and warn
    // the user about possible performance problems when doing this.
    uint64_t lowestUpperSequence = std::numeric_limits<uint64_t>::max();
    int leadingComponent = -1;
    for (size_t i = 0; i < sizeof...(Ts); ++i)
    {
      if (!baseComponents[i])
        baseComponents[i] = ESCoreBase::getEmptyContainer();

      bool optional = optionalComponents[i];
      // An empty mandatory component results in an immediate termination
      // of the walk. Even if the component is static.
      if (baseComponents[i]->getNumComponents() == 0 && !optional)
        return;

      indices[i] = 0;
      nextIndices[i] = 0;
      numComponents[i] = static_cast<int>(baseComponents[i]->getNumComponents());
      isStatic[i] = baseComponents[i]->isStatic();

      // Optional and static components are not allowed to be leading components
      if (optional || isStatic[i])
        continue;

      if (baseComponents[i]->getUpperSequence() < lowestUpperSequence)
      {
        leadingComponent = static_cast<int>(i);
        lowestUpperSequence = baseComponents[i]->getUpperSequence();
      }
    }

    std::tuple<Ts*...> values;                      ///< Values that will be passed into execute.
    std::tuple<ComponentGroup<Ts>...> groupValues;  ///< Grouped values that will be passed into group execute.

    AddComponentsToGroupInputs<0, Ts...>::exec(core, baseComponents, groupValues);

    // leadingComponent == -1 if and only if the number of optional and static
    // components == sizeof...(Ts). Because the if statement following the
    // "if (optional || isStatic) contitue;" statement will always succeed
    // due to the numeric_limits setting, leading to a valid value of
    // loading component.
    if (leadingComponent != -1)
    {
      // This clause is called when there is at least 1 non-optional
      // (mandatory) non-static component in the system.

      // Start off at the first target sequence and march forward from there.
      uint64_t targetSequence = baseComponents[leadingComponent]->getSequenceFromIndex(indices[leadingComponent]);
      while (targetSequence != 0)
      {
        // Find the target sequence in the other components.
        bool failed = false;
        for (size_t i = 0; i < baseComponents.size(); ++i)
        {
          uint64_t curSequence = baseComponents[i]->getSequenceFromIndex(indices[i]);
          bool optional = optionalComponents[i];
          bool compStatic = isStatic[i];

          // Static components don't have associated sequences.
          // They are always at index 0 and always valid. Existance of some
          // static components were guaranteed above.
          if (!compStatic)
          {
            // Note: when indices[i] = numComponents[i], we necessarily have an
            // optional component. This is because of the check for a zero number
            // of components above, in conjunction with the iteration logic
            // below. We always exit the function if we reach the end of a
            // mandatory component's array; but for an optional we break out and
            // continue.
            while (curSequence < targetSequence && indices[i] != numComponents[i])
            {
              ++indices[i];
              // Check to see if this is an optional component! If it is, then
              // we shouldn't return!
              if (indices[i] == numComponents[i])
              {
                if (!optional)
                  return;   // We are done -- this was a mandatory component and we reached the end of its list.
                else
                  break;    // Can't go any further.
              }
              curSequence = baseComponents[i]->getSequenceFromIndex(indices[i]);
            }

            if (curSequence != targetSequence && !optional)
            {
              failed = true;
              break;
            }
          }
        }

        if (!failed)
        {
          // Execute with indices. This recursive execute will perform a cartesian
          // product.
          if (!GroupComponents)
          {
            if (!RecurseExecute<0, Ts...>::exec(core, this, componentArrays,
                                                numComponents, indices,
                                                optionalComponents, isStatic,
                                                nextIndices, values,
                                                targetSequence))
            {
              return; // We have reached the end of an array.
            }
          }
          else
          {
            if (!GroupExecute<0, Ts...>::exec(core, this, componentArrays,
                                              numComponents, indices,
                                              optionalComponents, isStatic,
                                              nextIndices, groupValues,
                                              targetSequence))
            {
              return;
            }
          }

          // Copy nextIndices into indices.
          indices = nextIndices;
        }

        // Find new target sequence.
        while (baseComponents[leadingComponent]->getSequenceFromIndex(indices[leadingComponent]) == targetSequence)
        {
          ++indices[leadingComponent];
          if (indices[leadingComponent] == numComponents[leadingComponent])
            return;   // We are done.
        }
        targetSequence = baseComponents[leadingComponent]->getSequenceFromIndex(indices[leadingComponent]);
      }
    }
    else
    {
      // This else clause is called when *all* components are optional or
      // static. Not a single one is mandatory other than the static components,
      // whose existence has already been tested above.

      // Now we walk in a different fashion than above.

      // Determine list of entity ids that need to be walked. We use these as
      // the list of target sequences to be used when walking all components.
      // We must keep the sequenced sorted. So we use a map to accomplish this.

      // Instead of a target sequence, we will use this list of sorted sequences
      // to walk the components.

      // Create the target sequence list by recursing through our parameters.
      /// Optimize? Set will cause dynamic memory allocation. *But*, this
      /// is only a corner case and very few, if any, systems need
      /// this case where all components are optional.
      std::set<uint64_t> sequenceSet;
      GenSequenceSet<0, Ts...>::exec(sequenceSet, componentArrays,
                                     isStatic, numComponents);

      if (sequenceSet.size() != 0)
      {
        // Use the set as a list of target sequences when iterating over the
        // sequences.
        for (auto it = sequenceSet.begin(); it != sequenceSet.end(); ++it)
        {
          uint64_t targetSequence = *it;

          // Find the target sequence in the components.
          for (size_t i = 0; i < baseComponents.size(); ++i)
          {
            if (!isStatic[i])
            {
              uint64_t curSequence = baseComponents[i]->getSequenceFromIndex(indices[i]);
              while (curSequence < targetSequence && indices[i] != numComponents[i])
              {
                ++indices[i];
                if (indices[i] == numComponents[i])
                  break;   // We are done.
                curSequence = baseComponents[i]->getSequenceFromIndex(indices[i]);
              }
            }

            // We are never going to fail finding this sequence in at least one
            // of the optional components.
          }

          // Execute with indices. This recursive execute will perform a cartesian
          // product.
          if (!GroupComponents)
          {
            if (!RecurseExecute<0, Ts...>::exec(core, this, componentArrays,
                                                numComponents, indices,
                                                optionalComponents, isStatic,
                                                nextIndices, values,
                                                targetSequence))
            {
              return; // We have reached the end of an array.
            }
          }
          else
          {
            if (!GroupExecute<0, Ts...>::exec(core, this, componentArrays,
                                              numComponents, indices,
                                              optionalComponents, isStatic,
                                              nextIndices, groupValues,
                                              targetSequence))
            {
              return; // We have reached the end of an arry
            }
          }

          // Copy nextIndices into indices.
          indices = nextIndices;
        }
      }
      else // if (sequenceSet.size() != 0)
      {
        // When the sequence set is zero, that means that we could have a corner
        // case where all of the components are static. If that is the case,
        // then we simply iterate over all static members, either as a group
        // or recursively. If there are any optional components, then we don't
        // execute at all.
        bool allStatic = true;
        for (size_t i = 0; i < sizeof...(Ts); ++i)
        {
          if (!isStatic[i])
          {
            allStatic = false;
            break;
          }
        }

        if (allStatic)
        {
          if (!GroupComponents)
          {
            if (!RecurseExecute<0, Ts...>::exec(core, this, componentArrays,
                                                numComponents, indices,
                                                optionalComponents, isStatic,
                                                nextIndices, values,
                                                BaseComponentContainer::StaticEntID))
            {
              return; // We have reached the end of an array.
            }
          }
          else
          {
            if (!GroupExecute<0, Ts...>::exec(core, this, componentArrays,
                                              numComponents, indices,
                                              optionalComponents, isStatic,
                                              nextIndices, groupValues,
                                              BaseComponentContainer::StaticEntID))
            {
              return; // We have reached the end of an arry
            }
          }
        }
      }
    }
  }

  std::vector<uint64_t> getComponents() const override
  {
    std::vector<uint64_t> components = { TemplateID<Ts>::getID()... };
    return components;
  }

  template <int TupleIndex, typename... RTs>
  struct GenSequenceSet;

  template <int TupleIndex, typename RT, typename... RTs>
  struct GenSequenceSet<TupleIndex, RT, RTs...>
  {
    static void exec(std::set<uint64_t>& sequenceSet,
                     const std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>& componentArrays,
                     const std::array<bool, sizeof...(Ts)>& componentStatic,
                     const std::array<int, sizeof...(Ts)>& componentSizes)
    {
      // array may be a nullptr!
      typename ComponentContainer<RT>::ComponentItem* array = std::get<TupleIndex>(componentArrays);
      bool isStatic     = componentStatic[TupleIndex];

      // Only generate set of sequences if we do not have a static component.
      // Static componets always have 1 sequence, and they are handled
      // internally by the RecurseExecute and GroupExecute template structures.
      if (!isStatic)
      {
        // Loop over components at this RT.
        for (int i = 0; i < componentSizes[TupleIndex]; ++i)
        {
          sequenceSet.insert(array[i].sequence);
        }
      }

      // Recurse into corresponding container.
      GenSequenceSet<TupleIndex + 1, RTs...>::exec(
          sequenceSet, componentArrays, componentStatic, componentSizes);
    }
  };

  template <int TupleIndex>
  struct GenSequenceSet<TupleIndex>
  {
    static void exec(std::set<uint64_t>& /*sequenceSet*/,
                     const std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>& /* componentArrays */,
                     const std::array<bool, sizeof...(Ts)>& /* componentStatic */,
                     const std::array<int, sizeof...(Ts)>& /* componentSizes */)
    {}
  };

  template <int TupleIndex, typename... RTs>
  struct BuildComponentArrays;

  template <int TupleIndex, typename RT, typename... RTs>
  struct BuildComponentArrays<TupleIndex, RT, RTs...>
  {
    static void exec(
        std::array<BaseComponentContainer*, sizeof...(Ts)>& baseComponents,
        std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>& componentArrays)
    {
      if (baseComponents[TupleIndex] != nullptr)
      {
        std::get<TupleIndex>(componentArrays) =
            dynamic_cast<ComponentContainer<RT>*>(baseComponents[TupleIndex])->getComponentArray();
      }
      else
      {
        std::get<TupleIndex>(componentArrays) = nullptr;
      }
      BuildComponentArrays<TupleIndex + 1, RTs...>::exec(baseComponents, componentArrays);
    }
  };

  template <int TupleIndex>
  struct BuildComponentArrays<TupleIndex>
  {
    static void exec(
        std::array<BaseComponentContainer*, sizeof...(Ts)>&,
        std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>&)
    {}
  };

  template <int TupleIndex, typename... RTs>
  struct BuildComponentArraysAndIndicesWithID;

  template <int TupleIndex, typename RT, typename... RTs>
  struct BuildComponentArraysAndIndicesWithID<TupleIndex, RT, RTs...>
  {
    static void exec(
        std::array<BaseComponentContainer*, sizeof...(Ts)>& baseComponents,
        std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>& componentArrays,
        std::array<int, sizeof...(Ts)>& indices, uint64_t entityID)
    {
      if (baseComponents[TupleIndex] != nullptr)
      {
        ComponentContainer<RT>* derived = dynamic_cast<ComponentContainer<RT>*>(baseComponents[TupleIndex]);

        std::get<TupleIndex>(componentArrays) = derived->getComponentArray();
        int foundIndex = derived->getComponentItemIndexWithSequence(entityID);
        indices[TupleIndex] = foundIndex;
      }
      else
      {
        std::get<TupleIndex>(componentArrays) = nullptr;
        indices[TupleIndex] = 0;
      }
      BuildComponentArraysAndIndicesWithID<TupleIndex + 1, RTs...>::exec(
          baseComponents, componentArrays, indices, entityID);
    }
  };

  template <int TupleIndex>
  struct BuildComponentArraysAndIndicesWithID<TupleIndex>
  {
    static void exec(
        std::array<BaseComponentContainer*, sizeof...(Ts)>&,
        std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>&,
        std::array<int, sizeof...(Ts)>&, uint64_t)
    {}
  };

  template <int TupleIndex, typename... RTs>
  struct AddComponentsToGroupInputs;

  template <int TupleIndex, typename RT, typename... RTs>
  struct AddComponentsToGroupInputs<TupleIndex, RT, RTs...>
  {
    static void exec(ESCoreBase& core, std::array<BaseComponentContainer*, sizeof...(Ts)>& baseComponents,
                     std::tuple<ComponentGroup<Ts>...>& input)
    {
      if (baseComponents[TupleIndex] != nullptr)
      {
        std::get<TupleIndex>(input).container
            = dynamic_cast<ComponentContainer<RT>*>(core.getComponentContainer(TemplateID<RT>::getID()));
      }
      else
      {
        std::get<TupleIndex>(input).container = nullptr;
      }
      AddComponentsToGroupInputs<TupleIndex + 1, RTs...>::exec(core, baseComponents, input);
    }
  };

  template <int TupleIndex>
  struct AddComponentsToGroupInputs<TupleIndex>
  {
    static void exec(ESCoreBase& /* core */, std::array<BaseComponentContainer*, sizeof...(Ts)>& /* baseComponents */,
                     std::tuple<ComponentGroup<Ts>...>& /* input */) {}
  };

  template <int TupleIndex, typename... RTs>
  struct RecurseExecute;

  template <int TupleIndex, typename RT, typename... RTs>
  struct RecurseExecute<TupleIndex, RT, RTs...>
  {
    static bool exec(ESCoreBase& core, GenericSystem<GroupComponents, Ts...>* ptr,
                     const std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>& componentArrays,
                     const std::array<int, sizeof...(Ts)>& componentSizes,
                     const std::array<int, sizeof...(Ts)>& indices,
                     const std::array<bool, sizeof...(Ts)>& componentOptional,
                     const std::array<bool, sizeof...(Ts)>& componentStatic,
                     std::array<int, sizeof...(Ts)>& nextIndices,
                     std::tuple<Ts*...>& input,
                     uint64_t targetSequence)
    {
      int arraySize     = componentSizes[TupleIndex];
      int currentIndex  = indices[TupleIndex];
      bool optional     = componentOptional[TupleIndex];
      bool isStatic     = componentStatic[TupleIndex];
      typename ComponentContainer<RT>::ComponentItem* array = std::get<TupleIndex>(componentArrays);

      // Check to see if we are at the end of the array. This will happen with
      // optional components.
      if (currentIndex == arraySize)
      {
        if (optional)
        {
          std::get<TupleIndex>(input) = nullptr;
        }
        else
        {
          // Terminate early if we are at the end of the array and are not an
          // optional component.
          return false;
        }
      }
      else
      {
        // Only pass target sequence. We won't get here if arraySize == 0.
        if (array[currentIndex].sequence != targetSequence || isStatic)
        {
          if (isStatic && arraySize > 0)
          {
            std::get<TupleIndex>(input) = &array[0].component;
          }
          else
          {
            if (!optional)
              std::cerr << "Generic System: invalid sequence on non-optional component!!" << std::endl;
            std::get<TupleIndex>(input) = nullptr;
          }
        }
        else
        {
          std::get<TupleIndex>(input) = &array[currentIndex].component;
        }
      }

      // Depth first this will perform one execution with the target sequence
      // we found.
      bool reachedEnd = false;
      if (!RecurseExecute<TupleIndex + 1, RTs...>::exec(core, ptr,
              componentArrays, componentSizes, indices, componentOptional,
              componentStatic, nextIndices, input, targetSequence))
      {
        reachedEnd = true;
      }

      // Only increment current index if we are currently on the target
      // sequence. This *can* happen if we have an optional component that
      // passed nullptr in as its parameter.
      if (!isStatic)
      {
        if (array && array[currentIndex].sequence == targetSequence)
          ++currentIndex;

        if (currentIndex == arraySize)
        {
          if (nextIndices[TupleIndex] < currentIndex)
            nextIndices[TupleIndex] = currentIndex;

          // Terminate early in either case, but with different return values.
          // For optional components, reaching the end of the array does not
          // necessarily mean we should terminate the algorithm.
          return optional;
        }

        // Loop until we find a sequence that is not in our target.
        while (array[currentIndex].sequence == targetSequence)
        {
          std::get<TupleIndex>(input) = &array[currentIndex].component;
          // We don't need to check return value of RecurseExecute since any
          // lower component would have returned false on the first call. The
          // result of the first call is cached in reachedEnd.
          RecurseExecute<TupleIndex + 1, RTs...>::exec(core,
              ptr, componentArrays, componentSizes, indices, componentOptional,
              componentStatic, nextIndices, input, targetSequence);

          ++currentIndex;
          if (currentIndex == arraySize)
          {
            if (optional)
              break;
            else
              return false;
          }
        }

        if (nextIndices[TupleIndex] < currentIndex)
          nextIndices[TupleIndex] = currentIndex;
      }
      else // if (!isStatic)
      {
        // Loop over static array (we've already executed the first element above).
        for (int i = 1; i < arraySize; ++i)
        {
          std::get<TupleIndex>(input) = &array[i].component;
          // We don't need to check return value of RecurseExecute since any
          // lower component would have returned false on the first call. The
          // result of the first call is cached in reachedEnd.
          RecurseExecute<TupleIndex + 1, RTs...>::exec(core,
              ptr, componentArrays, componentSizes, indices, componentOptional,
              componentStatic, nextIndices, input, targetSequence);
        }
      }

      return !reachedEnd;
    }
  };

  template <int TupleIndex>
  struct RecurseExecute<TupleIndex>
  {
    static bool exec(ESCoreBase& core, GenericSystem<GroupComponents, Ts...>* ptr,
                     const std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>& componentArrays,
                     const std::array<int, sizeof...(Ts)>& componentSizes,
                     const std::array<int, sizeof...(Ts)>& indices,
                     const std::array<bool, sizeof...(Ts)>& componentOptional,
                     const std::array<bool, sizeof...(Ts)>& componentStatic,
                     std::array<int, sizeof...(Ts)>& nextIndices,
                     std::tuple<Ts*...>& input,
                     uint64_t targetSequence)
    {
      // Call our execute function with 'targetSequence' and 'input'.
      gs_detail::call(core, targetSequence, ptr, &GenericSystem<GroupComponents, Ts...>::execute, input);
      return true;
    }
  };

  template <int TupleIndex, typename... RTs>
  struct GroupExecute;

  template <int TupleIndex, typename RT, typename... RTs>
  struct GroupExecute<TupleIndex, RT, RTs...>
  {
    static bool exec(ESCoreBase& core, GenericSystem<GroupComponents, Ts...>* ptr,
                     const std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>& componentArrays,
                     const std::array<int, sizeof...(Ts)>& componentSizes,
                     const std::array<int, sizeof...(Ts)>& indices,
                     const std::array<bool, sizeof...(Ts)>& componentOptional,
                     const std::array<bool, sizeof...(Ts)>& componentStatic,
                     std::array<int, sizeof...(Ts)>& nextIndices,
                     std::tuple<ComponentGroup<Ts>...>& input,
                     uint64_t targetSequence)
    {
      int arraySize     = componentSizes[TupleIndex];
      int currentIndex  = indices[TupleIndex];
      bool optional     = componentOptional[TupleIndex];
      bool isStatic     = componentStatic[TupleIndex];
      typename ComponentContainer<RT>::ComponentItem* array = std::get<TupleIndex>(componentArrays);
      bool endOfArray   = false;

      std::get<TupleIndex>(input).containerIndex = currentIndex;

      // Check to see if we are at the end of the array. This will happen with
      // optional components. Static components will never enter this case.
      if (currentIndex == arraySize)
      {
        if (optional)
        {
          std::get<TupleIndex>(input).numComponents = 0;
          std::get<TupleIndex>(input).components = nullptr;
        }
        else
        {
          // Terminate early if we are at the end of the array and are not an
          // optional component (this works for isStatic as well).
          return false;
        }
      }
      else
      {
        // Only pass target sequence. array may be a nullptr, but we will never
        // reach this condition if that is the case. arraySize will be 0 as will
        // be currentIndex.
        if (array[currentIndex].sequence != targetSequence || isStatic)
        {
          if (isStatic && arraySize > 0)
          {
            std::get<TupleIndex>(input).numComponents = arraySize;
            std::get<TupleIndex>(input).components = &array[0];
          }
          else
          {
            if (!optional) std::cerr << "Generic System: invalid sequence on non-optional or static component!!" << std::endl;
            std::get<TupleIndex>(input).numComponents = 0;
            std::get<TupleIndex>(input).components = nullptr;
          }
        }
        else
        {
          /// This is the only case in which we need to determine the number
          /// of components.
          int numComponents = 0;

          // Set value before we reassign currentIndex.
          std::get<TupleIndex>(input).components = &array[currentIndex];

          // Loop until we find a sequence that is not in our target.
          while (array[currentIndex].sequence == targetSequence)
          {
            ++currentIndex;
            ++numComponents;
            if (currentIndex == arraySize)
            {
              endOfArray = true;
              break;
            }
          }

          // Now set how many components should exist.
          std::get<TupleIndex>(input).numComponents = numComponents;
        }
      }

      // Depth first this will perform one execution with the target sequence
      // we found.
      if (!GroupExecute<TupleIndex + 1, RTs...>::exec(core, ptr,
              componentArrays, componentSizes, indices, componentOptional,
              componentStatic, nextIndices, input, targetSequence))
      {
        return false;
      }

      if (nextIndices[TupleIndex] < currentIndex)
        nextIndices[TupleIndex] = currentIndex;

      if (endOfArray && !optional)
        return false;
      else
        return true;
    }
  };

  template <int TupleIndex>
  struct GroupExecute<TupleIndex>
  {
    static bool exec(ESCoreBase& core, GenericSystem<GroupComponents, Ts...>* ptr,
                     const std::tuple<typename ComponentContainer<Ts>::ComponentItem*...>& componentArrays,
                     const std::array<int, sizeof...(Ts)>& componentSizes,
                     const std::array<int, sizeof...(Ts)>& indices,
                     const std::array<bool, sizeof...(Ts)>& componentOptional,
                     const std::array<bool, sizeof...(Ts)>& componentStatic,
                     std::array<int, sizeof...(Ts)>& nextIndices,
                     std::tuple<ComponentGroup<Ts>...>& input,
                     uint64_t targetSequence)
    {
      // Call our execute function with 'targetSequence' and 'input'.
      gs_detail::call(core, targetSequence, ptr, &GenericSystem<GroupComponents, Ts...>::groupExecute, input);
      return true;
    }
  };

  // Non-grouped version of execute.
  virtual void execute(ESCoreBase&, uint64_t, const Ts*... vs)
  {
    std::cerr << "entity-system: Unimplmented system execute." << std::endl;
    throw std::runtime_error("entity-system: Unimplemented system execute.");
  }

  // Grouped version of execute.
  virtual void groupExecute(ESCoreBase&, uint64_t, const ComponentGroup<Ts>&... groups)
  {
    std::cerr << "entity-system: Unimplmented system group execute." << std::endl;
    throw std::runtime_error("entity-system: Unimplemented system group execute.");
  }

  /// This function should be overriden and return true for all components
  /// which may be optional.
  virtual bool isComponentOptional(uint64_t templateID) override {return false;}

  /// This function gets called before we start walking components from the
  /// walkComponents function.
  virtual void preWalkComponents(ESCoreBase& core)            {}

  /// This function gets called after we finish walking components from the
  /// walkComponents function.
  virtual void postWalkComponents(ESCoreBase& core)           {}
};

namespace optional_components_impl
{
template <typename... RTs>
struct OptionalCompImpl;

template <typename RT, typename... RTs>
struct OptionalCompImpl<RT, RTs...>
{
  static bool exec(uint64_t templateID)
  {
    if (TemplateID<RT>::getID() == templateID) return true;
    else return OptionalCompImpl<RTs...>::exec(templateID);
  }
};

template <>
struct OptionalCompImpl<>
{
  static bool exec(uint64_t templateID)  {return false;}
};
} // namespace optional_components_impl

template <typename... RTs>
bool OptionalComponents(uint64_t templateID)
{
  // Recursively determine if any of the given template parameters match the
  // given templateID.
  return optional_components_impl::OptionalCompImpl<RTs...>::exec(templateID);
}

} // namespace spire

#endif


text:
#include <aws/swf/model/RequestCancelActivityTaskFailedEventAttributes.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace SWF
{
namespace Model
{

RequestCancelActivityTaskFailedEventAttributes::RequestCancelActivityTaskFailedEventAttributes() :
    m_activityIdHasBeenSet(false),
    m_causeHasBeenSet(false),
    m_decisionTaskCompletedEventId(0),
    m_decisionTaskCompletedEventIdHasBeenSet(false)
{
}

RequestCancelActivityTaskFailedEventAttributes::RequestCancelActivityTaskFailedEventAttributes(const JsonValue& jsonValue) :
    m_activityIdHasBeenSet(false),
    m_causeHasBeenSet(false),
    m_decisionTaskCompletedEventId(0),
    m_decisionTaskCompletedEventIdHasBeenSet(false)
{
  *this = jsonValue;
}

RequestCancelActivityTaskFailedEventAttributes& RequestCancelActivityTaskFailedEventAttributes::operator =(const JsonValue& jsonValue)
{
  if(jsonValue.ValueExists("activityId"))
  {
    m_activityId = jsonValue.GetString("activityId");

    m_activityIdHasBeenSet = true;
  }

  if(jsonValue.ValueExists("cause"))
  {
    m_cause = RequestCancelActivityTaskFailedCauseMapper::GetRequestCancelActivityTaskFailedCauseForName(jsonValue.GetString("cause"));

    m_causeHasBeenSet = true;
  }

  if(jsonValue.ValueExists("decisionTaskCompletedEventId"))
  {
    m_decisionTaskCompletedEventId = jsonValue.GetInt64("decisionTaskCompletedEventId");

    m_decisionTaskCompletedEventIdHasBeenSet = true;
  }

  return *this;
}

JsonValue RequestCancelActivityTaskFailedEventAttributes::Jsonize() const
{
  JsonValue payload;

  if(m_activityIdHasBeenSet)
  {
   payload.WithString("activityId", m_activityId);

  }

  if(m_causeHasBeenSet)
  {
   payload.WithString("cause", RequestCancelActivityTaskFailedCauseMapper::GetNameForRequestCancelActivityTaskFailedCause(m_cause));
  }

  if(m_decisionTaskCompletedEventIdHasBeenSet)
  {
   payload.WithInt64("decisionTaskCompletedEventId", m_decisionTaskCompletedEventId);

  }

  return payload;
}

} // namespace Model
} // namespace SWF
} // namespace Aws


text: Implémenter et utiliser partiellement le SyliusResourceBundle au sein d'un projet symfony