text:
/* global PEG */

"use strict";

describe("generated parser behavior", function() {
  function varyOptimizationOptions(block) {
    function clone(object) {
      var result = {}, key;

      for (key in object) {
        if (object.hasOwnProperty(key)) {
          result[key] = object[key];
        }
      }

      return result;
    }

    var optionsVariants = [
          { cache: false, optimize: "speed" },
          { cache: false, optimize: "size"  },
          { cache: true,  optimize: "speed" },
          { cache: true,  optimize: "size"  }
        ],
        i;

    for (i = 0; i < optionsVariants.length; i++) {
      describe(
        "with options " + jasmine.pp(optionsVariants[i]),
        function() { block(clone(optionsVariants[i])); }
      );
    }
  }

  beforeEach(function() {
    this.addMatchers({
      toParse: function(input) {
        var options  = arguments.length > 2 ? arguments[1] : {},
            expected = arguments[arguments.length - 1],
            result;

        try {
          result = this.actual.parse(input, options);

          if (arguments.length > 1) {
            this.message = function() {
              return "Expected " + jasmine.pp(input) + " "
                   + "with options " + jasmine.pp(options) + " "
                   + (this.isNot ? "not " : "")
                   + "to parse as " + jasmine.pp(expected) + ", "
                   + "but it parsed as " + jasmine.pp(result) + ".";
            };

            return this.env.equals_(result, expected);
          } else {
            return true;
          }
        } catch (e) {
          this.message = function() {
            return "Expected " + jasmine.pp(input) + " "
                 + "with options " + jasmine.pp(options) + " "
                 + "to parse" + (arguments.length > 1 ? " as " + jasmine.pp(expected) : "") + ", "
                 + "but it failed to parse with message "
                 + jasmine.pp(e.message) + ".";
          };

          return false;
        }
      },

      toFailToParse: function(input) {
        var options = arguments.length > 2 ? arguments[1] : {},
            details = arguments.length > 1
                        ? arguments[arguments.length - 1]
                        : undefined,
            result;

        try {
          result = this.actual.parse(input, options);

          this.message = function() {
            return "Expected " + jasmine.pp(input) + " "
                 + "with options " + jasmine.pp(options) + " "
                 + "to fail to parse"
                 + (details ? " with details " + jasmine.pp(details) : "") + ", "
                 + "but it parsed as " + jasmine.pp(result) + ".";
          };

          return false;
        } catch (e) {
          /*
           * Should be at the top level but then JSHint complains about bad for
           * in variable.
           */
          var key;

          if (this.isNot) {
            this.message = function() {
              return "Expected " + jasmine.pp(input)
                   + "with options " + jasmine.pp(options) + " "
                   + "to parse, "
                   + "but it failed with message "
                   + jasmine.pp(e.message) + ".";
            };
          } else {
            if (details) {
              for (key in details) {
                if (details.hasOwnProperty(key)) {
                  if (!this.env.equals_(e[key], details[key])) {
                    this.message = function() {
                      return "Expected " + jasmine.pp(input) + " "
                           + "with options " + jasmine.pp(options) + " "
                           + "to fail to parse"
                           + (details ? " with details " + jasmine.pp(details) : "") + ", "
                           + "but " + jasmine.pp(key) + " "
                           + "is " + jasmine.pp(e[key]) + ".";
                    };

                    return false;
                  }
                }
              }
            }
          }

          return true;
        }
      }
    });
  });

  varyOptimizationOptions(function(options) {
    describe("initializer", function() {
      it("executes the code before parsing starts", function() {
        var parser = PEG.buildParser([
              '{ var result = 42; }',
              'start = "a" { return result; }'
            ].join("\n"), options);

        expect(parser).toParse("a", 42);
      });

      describe("available variables and functions", function() {
        it("|parser| contains the parser object", function() {
          var parser = PEG.buildParser([
                '{ var result = parser; }',
                'start = "a" { return result; }'
              ].join("\n"), options);

          expect(parser).toParse("a", parser);
        });

        it("|options| contains options", function() {
          var parser = PEG.buildParser([
                '{ var result = options; }',
                'start = "a" { return result; }'
              ].join("\n"), options);

          expect(parser).toParse("a", { a: 42 }, { a: 42 });
        });
      });
    });

    describe("rule", function() {
      if (options.cache) {
        it("caches rule match results", function() {
          var parser = PEG.buildParser([
                '{ var n = 0; }',
                'start = (a "b") / (a "c") { return n; }',
                'a = "a" { n++; }'
              ].join("\n"), options);

          expect(parser).toParse("ac", 1);
        });
      } else {
        it("doesn't cache rule match results", function() {
          var parser = PEG.buildParser([
                '{ var n = 0; }',
                'start = (a "b") / (a "c") { return n; }',
                'a = "a" { n++; }'
              ].join("\n"), options);

          expect(parser).toParse("ac", 2);
        });
      }

      describe("when the expression matches", function() {
        it("returns its match result", function() {
          var parser = PEG.buildParser('start = "a"');

          expect(parser).toParse("a", "a");
        });
      });

      describe("when the expression doesn't match", function() {
        describe("without display name", function() {
          it("reports match failure and doesn't record any expectation", function() {
            var parser = PEG.buildParser('start = "a"');

            expect(parser).toFailToParse("b", {
              expected: [{ type: "literal", value: "a", description: '"a"' }]
            });
          });
        });

        describe("with display name", function() {
          it("reports match failure and records an expectation of type \"other\"", function() {
            var parser = PEG.buildParser('start "start" = "a"');

            expect(parser).toFailToParse("b", {
              expected: [{ type: "other", description: "start" }]
            });
          });

          it("discards any expectations recorded when matching the expression", function() {
            var parser = PEG.buildParser('start "start" = "a"');

            expect(parser).toFailToParse("b", {
              expected: [{ type: "other", description: "start" }]
            });
          });
        });
      });
    });

    describe("literal", function() {
      describe("matching", function() {
        it("matches empty literals", function() {
          var parser = PEG.buildParser('start = ""', options);

          expect(parser).toParse("");
        });

        it("matches one-character literals", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toParse("a");
          expect(parser).toFailToParse("b");
        });

        it("matches multi-character literals", function() {
          var parser = PEG.buildParser('start = "abcd"', options);

          expect(parser).toParse("abcd");
          expect(parser).toFailToParse("efgh");
        });

        it("is case sensitive without the \"i\" flag", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toParse("a");
          expect(parser).toFailToParse("A");
        });

        it("is case insensitive with the \"i\" flag", function() {
          var parser = PEG.buildParser('start = "a"i', options);

          expect(parser).toParse("a");
          expect(parser).toParse("A");
        });
      });

      describe("when it matches", function() {
        it("returns the matched text", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toParse("a", "a");
        });

        it("consumes the matched text", function() {
          var parser = PEG.buildParser('start = "a" .', options);

          expect(parser).toParse("ab");
        });
      });

      describe("when it doesn't match", function() {
        it("reports match failure and records an expectation of type \"literal\"", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toFailToParse("b", {
            expected: [{ type: "literal", value: "a", description: '"a"' }]
          });
        });
      });
    });

    describe("character class", function() {
      describe("matching", function() {
        it("matches empty classes", function() {
          var parser = PEG.buildParser('start = []', options);

          expect(parser).toFailToParse("a");
        });

        it("matches classes with a character list", function() {
          var parser = PEG.buildParser('start = [abc]', options);

          expect(parser).toParse("a");
          expect(parser).toParse("b");
          expect(parser).toParse("c");
          expect(parser).toFailToParse("d");
        });

        it("matches classes with a character range", function() {
          var parser = PEG.buildParser('start = [a-c]', options);

          expect(parser).toParse("a");
          expect(parser).toParse("b");
          expect(parser).toParse("c");
          expect(parser).toFailToParse("d");
        });

        it("matches inverted classes", function() {
          var parser = PEG.buildParser('start = [^a]', options);

          expect(parser).toFailToParse("a");
          expect(parser).toParse("b");
        });

        it("is case sensitive without the \"i\" flag", function() {
          var parser = PEG.buildParser('start = [a]', options);

          expect(parser).toParse("a");
          expect(parser).toFailToParse("A");
        });

        it("is case insensitive with the \"i\" flag", function() {
          var parser = PEG.buildParser('start = [a]i', options);

          expect(parser).toParse("a");
          expect(parser).toParse("A");
        });
      });

      describe("when it matches", function() {
        it("returns the matched character", function() {
          var parser = PEG.buildParser('start = [a]', options);

          expect(parser).toParse("a", "a");
        });

        it("consumes the matched character", function() {
          var parser = PEG.buildParser('start = [a] .', options);

          expect(parser).toParse("ab");
        });
      });

      describe("when it doesn't match", function() {
        it("reports match failure and records an expectation of type \"class\"", function() {
          var parser = PEG.buildParser('start = [a]', options);

          expect(parser).toFailToParse("b", {
            expected: [{ type: "class", value: "[a]", description: "[a]" }]
          });
        });
      });
    });

    describe("dot", function() {
      describe("matching", function() {
        it("matches any character", function() {
          var parser = PEG.buildParser('start = .', options);

          expect(parser).toParse("a");
          expect(parser).toParse("b");
          expect(parser).toParse("c");
        });
      });

      describe("when it matches", function() {
        it("returns the matched character", function() {
          var parser = PEG.buildParser('start = .', options);

          expect(parser).toParse("a", "a");
        });

        it("consumes the matched character", function() {
          var parser = PEG.buildParser('start = . .', options);

          expect(parser).toParse("ab");
        });
      });

      describe("when it doesn't match", function() {
        it("reports match failure and records an expectation of type \"any\"", function() {
          var parser = PEG.buildParser('start = .', options);

          expect(parser).toFailToParse("", {
            expected: [{ type: "any", description: "any character" }]
          });
        });
      });
    });

    describe("rule reference", function() {
      describe("when referenced rule's expression matches", function() {
        it("returns its result", function() {
          var parser = PEG.buildParser([
                'start = a',
                'a = "a"'
              ].join("\n"), options);

          expect(parser).toParse("a", "a");
        });
      });

      describe("when referenced rule's expression doesn't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser([
                'start = a',
                'a = "a"'
              ].join("\n"), options);

          expect(parser).toFailToParse("b");
        });
      });
    });

    describe("positive semantic predicate", function() {
      describe("when the code returns a truthy value", function() {
        it("returns |undefined|", function() {
          var parser = PEG.buildParser('start = &{ return true; }', options);

          expect(parser).toParse("", undefined);
        });
      });

      describe("when the code returns a falsey value", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = &{ return false; }', options);

          expect(parser).toFailToParse("");
        });
      });

      describe("label variables", function() {
        describe("in containing sequence", function() {
          it("can access variables defined by preceding labeled elements", function() {
            var parser = PEG.buildParser(
                  'start = a:"a" &{ return a === "a"; }',
                  options
                );

            expect(parser).toParse("a");
          });

          it("cannot access variable defined by labeled predicate element", function() {
            var parser = PEG.buildParser(
                  'start = "a" b:&{ return b === undefined; } "c"',
                  options
                );

            expect(parser).toFailToParse("ac");
          });

          it("cannot access variables defined by following labeled elements", function() {
            var parser = PEG.buildParser(
                  'start = &{ return a === "a"; } a:"a"',
                  options
                );

            expect(parser).toFailToParse("a");
          });

          it("cannot access variables defined by subexpressions", function() {
            var testcases = [
                  {
                    grammar: 'start = (a:"a") &{ return a === "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = (a:"a")? &{ return a === "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = (a:"a")* &{ return a === "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = (a:"a")+ &{ return a === "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = $(a:"a") &{ return a === "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = &(a:"a") "a" &{ return a === "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = !(a:"a") "b" &{ return a === "a"; }',
                    input:   "b"
                  },
                  {
                    grammar: 'start = b:(a:"a") &{ return a === "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = ("a" b:"b" "c") &{ return b === "b"; }',
                    input:   "abc"
                  },
                  {
                    grammar: 'start = (a:"a" { return a; }) &{ return a === "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = ("a" / b:"b" / "c") &{ return b === "b"; }',
                    input:   "b"
                  }
                ],
                parser, i;

            for (i = 0; i < testcases.length; i++) {
              parser = PEG.buildParser(testcases[i].grammar, options);
              expect(parser).toFailToParse(testcases[i].input);
            }
          });
        });

        describe("in outer sequence", function() {
          it("can access variables defined by preceding labeled elements", function() {
            var parser = PEG.buildParser(
                  'start = a:"a" ("b" &{ return a === "a"; })',
                  options
                );

            expect(parser).toParse("ab");
          });

          it("cannot access variable defined by labeled predicate element", function() {
            var parser = PEG.buildParser(
                  'start = "a" b:("b" &{ return b === undefined; }) "c"',
                  options
                );

            expect(parser).toFailToParse("abc");
          });

          it("cannot access variables defined by following labeled elements", function() {
            var parser = PEG.buildParser(
                  'start = ("a" &{ return b === "b"; }) b:"b"',
                  options
                );

            expect(parser).toFailToParse("ab");
          });
        });
      });

      describe("initializer variables & functions", function() {
        it("can access variables defined in the initializer", function() {
          var parser = PEG.buildParser([
                '{ var v = 42 }',
                'start = &{ return v === 42; }'
              ].join("\n"), options);

          expect(parser).toParse("");
        });

        it("can access functions defined in the initializer", function() {
          var parser = PEG.buildParser([
                '{ function f() { return 42; } }',
                'start = &{ return f() === 42; }'
              ].join("\n"), options);

          expect(parser).toParse("");
        });
      });

      describe("available variables & functions", function() {
        it("|parser| contains the parser object", function() {
          var parser = PEG.buildParser([
                '{ var result; }',
                'start = &{ result = parser; return true; } { return result; }'
              ].join("\n"), options);

          expect(parser).toParse("", parser);
        });

        it("|options| contains options", function() {
          var parser = PEG.buildParser([
                '{ var result; }',
                'start = &{ result = options; return true; } { return result; }'
              ].join("\n"), options);

          expect(parser).toParse("", { a: 42 }, { a: 42 });
        });

        it("|location| returns current location info", function() {
          var parser = PEG.buildParser([
                '{ var result; }',
                'start  = line (nl+ line)* { return result; }',
                'line   = thing (" "+ thing)*',
                'thing  = digit / mark',
                'digit  = [0-9]',
                'mark   = &{ result = location(); return true; } "x"',
                'nl     = "\\r"? "\\n"'
              ].join("\n"), options);

          expect(parser).toParse("1\n2\n\n3\n\n\n4 5 x", {
            start: { offset: 13, line: 7, column: 5 },
            end:   { offset: 13, line: 7, column: 5 }
          });

          /* Newline representations */
          expect(parser).toParse("1\nx", {     // Unix
            start: { offset: 2, line: 2, column: 1 },
            end:   { offset: 2, line: 2, column: 1 }
          });
          expect(parser).toParse("1\r\nx", {   // Windows
            start: { offset: 3, line: 2, column: 1 },
            end:   { offset: 3, line: 2, column: 1 }
          });
        });
      });
    });

    describe("negative semantic predicate", function() {
      describe("when the code returns a falsey value", function() {
        it("returns |undefined|", function() {
          var parser = PEG.buildParser('start = !{ return false; }', options);

          expect(parser).toParse("", undefined);
        });
      });

      describe("when the code returns a truthy value", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = !{ return true; }', options);

          expect(parser).toFailToParse("");
        });
      });

      describe("label variables", function() {
        describe("in containing sequence", function() {
          it("can access variables defined by preceding labeled elements", function() {
            var parser = PEG.buildParser(
                  'start = a:"a" !{ return a !== "a"; }',
                  options
                );

            expect(parser).toParse("a");
          });

          it("cannot access variable defined by labeled predicate element", function() {
            var parser = PEG.buildParser(
                  'start = "a" b:!{ return b !== undefined; } "c"',
                  options
                );

            expect(parser).toFailToParse("ac");
          });

          it("cannot access variables defined by following labeled elements", function() {
            var parser = PEG.buildParser(
                  'start = !{ return a !== "a"; } a:"a"',
                  options
                );

            expect(parser).toFailToParse("a");
          });

          it("cannot access variables defined by subexpressions", function() {
            var testcases = [
                  {
                    grammar: 'start = (a:"a") !{ return a !== "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = (a:"a")? !{ return a !== "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = (a:"a")* !{ return a !== "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = (a:"a")+ !{ return a !== "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = $(a:"a") !{ return a !== "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = &(a:"a") "a" !{ return a !== "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = !(a:"a") "b" !{ return a !== "a"; }',
                    input:   "b"
                  },
                  {
                    grammar: 'start = b:(a:"a") !{ return a !== "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = ("a" b:"b" "c") !{ return b !== "b"; }',
                    input:   "abc"
                  },
                  {
                    grammar: 'start = (a:"a" { return a; }) !{ return a !== "a"; }',
                    input:   "a"
                  },
                  {
                    grammar: 'start = ("a" / b:"b" / "c") !{ return b !== "b"; }',
                    input:   "b"
                  }
                ],
                parser, i;

            for (i = 0; i < testcases.length; i++) {
              parser = PEG.buildParser(testcases[i].grammar, options);
              expect(parser).toFailToParse(testcases[i].input);
            }
          });
        });

        describe("in outer sequence", function() {
          it("can access variables defined by preceding labeled elements", function() {
            var parser = PEG.buildParser(
                  'start = a:"a" ("b" !{ return a !== "a"; })',
                  options
                );

            expect(parser).toParse("ab");
          });

          it("cannot access variable defined by labeled predicate element", function() {
            var parser = PEG.buildParser(
                  'start = "a" b:("b" !{ return b !== undefined; }) "c"',
                  options
                );

            expect(parser).toFailToParse("abc");
          });

          it("cannot access variables defined by following labeled elements", function() {
            var parser = PEG.buildParser(
                  'start = ("a" !{ return b !== "b"; }) b:"b"',
                  options
                );

            expect(parser).toFailToParse("ab");
          });
        });
      });

      describe("initializer variables & functions", function() {
        it("can access variables defined in the initializer", function() {
          var parser = PEG.buildParser([
                '{ var v = 42 }',
                'start = !{ return v !== 42; }'
              ].join("\n"), options);

          expect(parser).toParse("");
        });

        it("can access functions defined in the initializer", function() {
          var parser = PEG.buildParser([
                '{ function f() { return 42; } }',
                'start = !{ return f() !== 42; }'
              ].join("\n"), options);

          expect(parser).toParse("");
        });
      });

      describe("available variables & functions", function() {
        it("|parser| contains the parser object", function() {
          var parser = PEG.buildParser([
                '{ var result; }',
                'start = !{ result = parser; return false; } { return result; }'
              ].join("\n"), options);

          expect(parser).toParse("", parser);
        });

        it("|options| contains options", function() {
          var parser = PEG.buildParser([
                '{ var result; }',
                'start = !{ result = options; return false; } { return result; }'
              ].join("\n"), options);

          expect(parser).toParse("", { a: 42 }, { a: 42 });
        });

        it("|location| returns current location info", function() {
          var parser = PEG.buildParser([
                '{ var result; }',
                'start  = line (nl+ line)* { return result; }',
                'line   = thing (" "+ thing)*',
                'thing  = digit / mark',
                'digit  = [0-9]',
                'mark   = !{ result = location(); return false; } "x"',
                'nl     = "\\r"? "\\n"'
              ].join("\n"), options);

          expect(parser).toParse("1\n2\n\n3\n\n\n4 5 x", {
            start: { offset: 13, line: 7, column: 5 },
            end:   { offset: 13, line: 7, column: 5 }
          });

          /* Newline representations */
          expect(parser).toParse("1\nx", {     // Unix
            start: { offset: 2, line: 2, column: 1 },
            end:   { offset: 2, line: 2, column: 1 }
          });
          expect(parser).toParse("1\r\nx", {   // Windows
            start: { offset: 3, line: 2, column: 1 },
            end:   { offset: 3, line: 2, column: 1 }
          });
        });
      });
    });

    describe("group", function() {
      describe("when the expression matches", function() {
        it("returns its match result", function() {
          var parser = PEG.buildParser('start = ("a")', options);

          expect(parser).toParse("a", "a");
        });
      });

      describe("when the expression doesn't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = ("a")', options);

          expect(parser).toFailToParse("b");
        });
      });
    });

    describe("optional", function() {
      describe("when the expression matches", function() {
        it("returns its match result", function() {
          var parser = PEG.buildParser('start = "a"?', options);

          expect(parser).toParse("a", "a");
        });
      });

      describe("when the expression doesn't match", function() {
        it("returns |null|", function() {
          var parser = PEG.buildParser('start = "a"?', options);

          expect(parser).toParse("", null);
        });
      });
    });

    describe("zero or more", function() {
      describe("when the expression matches zero or more times", function() {
        it("returns an array of its match results", function() {
          var parser = PEG.buildParser('start = "a"*', options);

          expect(parser).toParse("",    []);
          expect(parser).toParse("a",   ["a"]);
          expect(parser).toParse("aaa", ["a", "a", "a"]);
        });
      });
    });

    describe("one or more", function() {
      describe("when the expression matches one or more times", function() {
        it("returns an array of its match results", function() {
          var parser = PEG.buildParser('start = "a"+', options);

          expect(parser).toParse("a",   ["a"]);
          expect(parser).toParse("aaa", ["a", "a", "a"]);
        });
      });

      describe("when the expression doesn't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = "a"+', options);

          expect(parser).toFailToParse("");
        });
      });
    });

    describe("text", function() {
      describe("when the expression matches", function() {
        it("returns the matched text", function() {
          var parser = PEG.buildParser('start = $("a" "b" "c")', options);

          expect(parser).toParse("abc", "abc");
        });
      });

      describe("when the expression doesn't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = $("a")', options);

          expect(parser).toFailToParse("b");
        });
      });
    });

    describe("positive simple predicate", function() {
      describe("when the expression matches", function() {
        it("returns |undefined|", function() {
          var parser = PEG.buildParser('start = &"a" "a"', options);

          expect(parser).toParse("a", [undefined, "a"]);
        });

        it("resets parse position", function() {
          var parser = PEG.buildParser('start = &"a" "a"', options);

          expect(parser).toParse("a");
        });
      });

      describe("when the expression doesn't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = &"a"', options);

          expect(parser).toFailToParse("b");
        });

        it("discards any expectations recorded when matching the expression", function() {
          var parser = PEG.buildParser('start = "a" / &"b" / "c"', options);

          expect(parser).toFailToParse("d", {
            expected: [
              { type: "literal", value: "a", description: '"a"' },
              { type: "literal", value: "c", description: '"c"' }
            ]
          });
        });
      });
    });

    describe("negative simple predicate", function() {
      describe("when the expression matches", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = !"a"', options);

          expect(parser).toFailToParse("a");
        });
      });

      describe("when the expression doesn't match", function() {
        it("returns |undefined|", function() {
          var parser = PEG.buildParser('start = !"a" "b"', options);

          expect(parser).toParse("b", [undefined, "b"]);
        });

        it("resets parse position", function() {
          var parser = PEG.buildParser('start = !"a" "b"', options);

          expect(parser).toParse("b");
        });

        it("discards any expectations recorded when matching the expression", function() {
          var parser = PEG.buildParser('start = "a" / !"b" / "c"', options);

          expect(parser).toFailToParse("b", {
            expected: [
              { type: "literal", value: "a", description: '"a"' },
              { type: "literal", value: "c", description: '"c"' }
            ]
          });
        });
      });
    });

    describe("label", function() {
      describe("when the expression matches", function() {
        it("returns its match result", function() {
          var parser = PEG.buildParser('start = a:"a"', options);

          expect(parser).toParse("a", "a");
        });
      });

      describe("when the expression doesn't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = a:"a"', options);

          expect(parser).toFailToParse("b");
        });
      });
    });

    describe("sequence", function() {
      describe("when all expressions match", function() {
        it("returns an array of their match results", function() {
          var parser = PEG.buildParser('start = "a" "b" "c"', options);

          expect(parser).toParse("abc", ["a", "b", "c"]);
        });
      });

      describe("when any expression doesn't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = "a" "b" "c"', options);

          expect(parser).toFailToParse("dbc");
          expect(parser).toFailToParse("adc");
          expect(parser).toFailToParse("abd");
        });

        it("resets parse position", function() {
          var parser = PEG.buildParser('start = "a" "b" / "a"', options);

          expect(parser).toParse("a", "a");
        });
      });
    });

    describe("action", function() {
      describe("when the expression matches", function() {
        it("returns the value returned by the code", function() {
          var parser = PEG.buildParser('start = "a" { return 42; }', options);

          expect(parser).toParse("a", 42);
        });

        describe("label variables", function() {
          describe("in the expression", function() {
            it("can access variable defined by labeled expression", function() {
              var parser = PEG.buildParser('start = a:"a" { return a; }', options);

              expect(parser).toParse("a", "a");
            });

            it("can access variables defined by labeled sequence elements", function() {
              var parser = PEG.buildParser(
                    'start = a:"a" b:"b" c:"c" { return [a, b, c]; }',
                    options
                  );

              expect(parser).toParse("abc", ["a", "b", "c"]);
            });

            it("cannot access variables defined by subexpressions", function() {
              var testcases = [
                    {
                      grammar: 'start = (a:"a") { return a; }',
                      input:   "a"
                    },
                    {
                      grammar: 'start = (a:"a")? { return a; }',
                      input:   "a"
                    },
                    {
                      grammar: 'start = (a:"a")* { return a; }',
                      input:   "a"
                    },
                    {
                      grammar: 'start = (a:"a")+ { return a; }',
                      input:   "a"
                    },
                    {
                      grammar: 'start = $(a:"a") { return a; }',
                      input:   "a"
                    },
                    {
                      grammar: 'start = &(a:"a") "a" { return a; }',
                      input:   "a"
                    },
                    {
                      grammar: 'start = !(a:"a") "b" { return a; }',
                      input:   "b"
                    },
                    {
                      grammar: 'start = b:(a:"a") { return a; }',
                      input:   "a"
                    },
                    {
                      grammar: 'start = ("a" b:"b" "c") { return b; }',
                      input:   "abc"
                    },
                    {
                      grammar: 'start = (a:"a" { return a; }) { return a; }',
                      input:   "a"
                    },
                    {
                      grammar: 'start = ("a" / b:"b" / "c") { return b; }',
                      input:   "b"
                    }
                  ],
                  parser, i;

              for (i = 0; i < testcases.length; i++) {
                parser = PEG.buildParser(testcases[i].grammar, options);
                expect(parser).toFailToParse(testcases[i].input);
              }
            });
          });

          describe("in outer sequence", function() {
            it("can access variables defined by preceding labeled elements", function() {
              var parser = PEG.buildParser(
                    'start = a:"a" ("b" { return a; })',
                    options
                  );

              expect(parser).toParse("ab", ["a", "a"]);
            });

            it("cannot access variable defined by labeled action element", function() {
              var parser = PEG.buildParser(
                    'start = "a" b:("b" { return b; }) c:"c"',
                    options
                  );

              expect(parser).toFailToParse("abc");
            });

            it("cannot access variables defined by following labeled elements", function() {
              var parser = PEG.buildParser(
                    'start = ("a" { return b; }) b:"b"',
                    options
                  );

              expect(parser).toFailToParse("ab");
            });
          });
        });

        describe("initializer variables & functions", function() {
          it("can access variables defined in the initializer", function() {
            var parser = PEG.buildParser([
                  '{ var v = 42 }',
                  'start = "a" { return v; }'
                ].join("\n"), options);

            expect(parser).toParse("a", 42);
          });

          it("can access functions defined in the initializer", function() {
            var parser = PEG.buildParser([
                  '{ function f() { return 42; } }',
                  'start = "a" { return f(); }'
                ].join("\n"), options);

            expect(parser).toParse("a", 42);
          });
        });

        describe("available variables & functions", function() {
          it("|parser| contains the parser object", function() {
            var parser = PEG.buildParser(
                  'start = "a" { return parser; }',
                  options
                );

            expect(parser).toParse("a", parser);
          });

          it("|options| contains options", function() {
            var parser = PEG.buildParser(
                  'start = "a" { return options; }',
                  options
                );

            expect(parser).toParse("a", { a: 42 }, { a: 42 });
          });

          it("|text| returns text matched by the expression", function() {
            var parser = PEG.buildParser(
                  'start = "a" { return text(); }',
                  options
                );

            expect(parser).toParse("a", "a");
          });

          it("|location| returns location info of the expression", function() {
            var parser = PEG.buildParser([
                  '{ var result; }',
                  'start  = line (nl+ line)* { return result; }',
                  'line   = thing (" "+ thing)*',
                  'thing  = digit / mark',
                  'digit  = [0-9]',
                  'mark   = "x" { result = location(); }',
                  'nl     = "\\r"? "\\n"'
                ].join("\n"), options);

            expect(parser).toParse("1\n2\n\n3\n\n\n4 5 x", {
              start: { offset: 13, line: 7, column: 5 },
              end:   { offset: 14, line: 7, column: 6 }
            });

            /* Newline representations */
            expect(parser).toParse("1\nx", {     // Unix
              start: { offset: 2, line: 2, column: 1 },
              end:   { offset: 3, line: 2, column: 2 }
            });
            expect(parser).toParse("1\r\nx", {   // Windows
              start: { offset: 3, line: 2, column: 1 },
              end:   { offset: 4, line: 2, column: 2 }
            });
          });

          it("|expected| terminates parsing and throws an exception", function() {
            var parser = PEG.buildParser(
                  'start = "a" { expected("a"); }',
                  options
                );

            expect(parser).toFailToParse("a", {
              message:  'Expected a.',
              expected: [{ type: "other", description: "a" }],
              location: {
                start: { offset: 0, line: 1, column: 1 },
                end:   { offset: 1, line: 1, column: 2 }
              }
            });
          });

          it("|error| terminates parsing and throws an exception", function() {
            var parser = PEG.buildParser(
                  'start = "a" { error("a"); }',
                  options
                );

            expect(parser).toFailToParse("a", {
              message:  "a",
              expected: null,
              location: {
                start: { offset: 0, line: 1, column: 1 },
                end:   { offset: 1, line: 1, column: 2 }
              }
            });
          });
        });
      });

      describe("when the expression doesn't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = "a" { return 42; }', options);

          expect(parser).toFailToParse("b");
        });

        it("doesn't execute the code", function() {
          var parser = PEG.buildParser(
                'start = "a" { throw "Boom!"; } / "b"',
                options
              );

          expect(parser).toParse("b");
        });
      });
    });

    describe("choice", function() {
      describe("when any expression matches", function() {
        it("returns its match result", function() {
          var parser = PEG.buildParser('start = "a" / "b" / "c"', options);

          expect(parser).toParse("a", "a");
          expect(parser).toParse("b", "b");
          expect(parser).toParse("c", "c");
        });
      });

      describe("when all expressions don't match", function() {
        it("reports match failure", function() {
          var parser = PEG.buildParser('start = "a" / "b" / "c"', options);

          expect(parser).toFailToParse("d");
        });
      });
    });

    describe("error reporting", function() {
      describe("behavior", function() {
        it("reports only the rightmost error", function() {
          var parser = PEG.buildParser('start = "a" "b" / "a" "c" "d"', options);

          expect(parser).toFailToParse("ace", {
            expected: [{ type: "literal", value: "d", description: '"d"' }]
          });
        });
      });

      describe("expectations reporting", function() {
        it("reports expectations correctly with no alternative", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toFailToParse("ab", {
            expected: [{ type: "end", description: "end of input" }]
          });
        });

        it("reports expectations correctly with one alternative", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toFailToParse("b", {
            expected: [{ type: "literal", value: "a", description: '"a"' }]
          });
        });

        it("reports expectations correctly with multiple alternatives", function() {
          var parser = PEG.buildParser('start = "a" / "b" / "c"', options);

          expect(parser).toFailToParse("d", {
            expected: [
              { type: "literal", value: "a", description: '"a"' },
              { type: "literal", value: "b", description: '"b"' },
              { type: "literal", value: "c", description: '"c"' }
            ]
          });
        });

        it("removes duplicates from expectations", function() {
          /*
           * There was a bug in the code that manifested only with three
           * duplicates. This is why the following test uses three choices
           * instead of seemingly sufficient two.
           *
           * See https://github.com/pegjs/pegjs/pull/146.
           */
          var parser = PEG.buildParser('start = "a" / "a" / "a"', options);

          expect(parser).toFailToParse("b", {
            expected: [{ type: "literal", value: "a", description: '"a"' }]
          });
        });

        it("sorts expectations", function() {
          var parser = PEG.buildParser('start = "c" / "b" / "a"', options);

          expect(parser).toFailToParse("d", {
            expected: [
              { type: "literal", value: "a", description: '"a"' },
              { type: "literal", value: "b", description: '"b"' },
              { type: "literal", value: "c", description: '"c"' }
            ]
          });
        });
      });

      describe("message building", function() {
        it("builds message correctly with no alternative", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toFailToParse("ab", {
            message: 'Expected end of input.'
          });
        });

        it("builds message correctly with one alternative", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toFailToParse("b", {
            message: 'Expected "a".'
          });
        });

        it("builds message correctly with multiple alternatives", function() {
          var parser = PEG.buildParser('start = "a" / "b" / "c"', options);

          expect(parser).toFailToParse("d", {
            message: 'Expected "a", "b" or "c".'
          });
        });
      });

      describe("position reporting", function() {
        it("reports position correctly with no trailing input", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toFailToParse("b", {
            location: {
              start: { offset: 0, line: 1, column: 1 },
              end:   { offset: 0, line: 1, column: 1 }
            }
          });
        });

        it("reports position correctly with trailing input", function() {
          var parser = PEG.buildParser('start = "a"', options);

          expect(parser).toFailToParse("aa", {
            location: {
              start: { offset: 1, line: 1, column: 2 },
              end:   { offset: 1, line: 1, column: 2 }
            }
          });
        });

        it("reports position correctly in complex cases", function() {
          var parser = PEG.buildParser([
                'start  = line (nl+ line)*',
                'line   = digit (" "+ digit)*',
                'digit  = [0-9]',
                'nl     = "\\r"? "\\n"'
              ].join("\n"), options);

          expect(parser).toFailToParse("1\n2\n\n3\n\n\n4 5 x", {
            location: {
              start: { offset: 13, line: 7, column: 5 },
              end:   { offset: 13, line: 7, column: 5 }
            }
          });

          /* Newline representations */
          expect(parser).toFailToParse("1\nx", {     // Old Mac
            location: {
              start: { offset: 2, line: 2, column: 1 },
              end:   { offset: 2, line: 2, column: 1 }
            }
          });
          expect(parser).toFailToParse("1\r\nx", {   // Windows
            location: {
              start: { offset: 3, line: 2, column: 1 },
              end:   { offset: 3, line: 2, column: 1 }
            }
          });
        });
      });
    });

    /*
     * Following examples are from Wikipedia, see
     * http://en.wikipedia.org/w/index.php?title=Parsing_expression_grammar&oldid=335106938.
     */
    describe("complex examples", function() {
      it("handles arithmetics example correctly", function() {
        /*
         * Value   ← [0-9]+ / '(' Expr ')'
         * Product ← Value (('*' / '/') Value)*
         * Sum     ← Product (('+' / '-') Product)*
         * Expr    ← Sum
         */
        var parser = PEG.buildParser([
              'Expr    = Sum',
              'Sum     = first:Product rest:(("+" / "-") Product)* {',
              '            var result = first, i;',
              '            for (i = 0; i < rest.length; i++) {',
              '              if (rest[i][0] == "+") { result += rest[i][1]; }',
              '              if (rest[i][0] == "-") { result -= rest[i][1]; }',
              '            }',
              '            return result;',
              '          }',
              'Product = first:Value rest:(("*" / "/") Value)* {',
              '            var result = first, i;',
              '            for (i = 0; i < rest.length; i++) {',
              '              if (rest[i][0] == "*") { result *= rest[i][1]; }',
              '              if (rest[i][0] == "/") { result /= rest[i][1]; }',
              '            }',
              '            return result;',
              '          }',
              'Value   = digits:[0-9]+     { return parseInt(digits.join(""), 10); }',
              '        / "(" expr:Expr ")" { return expr; }'
            ].join("\n"), options);

        /* The "value" rule */
        expect(parser).toParse("0",       0);
        expect(parser).toParse("123",     123);
        expect(parser).toParse("(42+43)", 42+43);

        /* The "product" rule */
        expect(parser).toParse("42",          42);
        expect(parser).toParse("42*43",       42*43);
        expect(parser).toParse("42*43*44*45", 42*43*44*45);
        expect(parser).toParse("42/43",       42/43);
        expect(parser).toParse("42/43/44/45", 42/43/44/45);

        /* The "sum" rule */
        expect(parser).toParse("42*43",                   42*43);
        expect(parser).toParse("42*43+44*45",             42*43+44*45);
        expect(parser).toParse("42*43+44*45+46*47+48*49", 42*43+44*45+46*47+48*49);
        expect(parser).toParse("42*43-44*45",             42*43-44*45);
        expect(parser).toParse("42*43-44*45-46*47-48*49", 42*43-44*45-46*47-48*49);

        /* The "expr" rule */
        expect(parser).toParse("42+43", 42+43);

        /* Complex test */
        expect(parser).toParse("(1+2)*(3+4)", (1+2)*(3+4));
      });

      it("handles non-context-free language correctly", function() {
        /* The following parsing expression grammar describes the classic
         * non-context-free language { a^n b^n c^n : n >= 1 }:
         *
         * S ← &(A c) a+ B !(a/b/c)
         * A ← a A? b
         * B ← b B? c
         */
        var parser = PEG.buildParser([
              'S = &(A "c") a:"a"+ B:B !("a" / "b" / "c") { return a.join("") + B; }',
              'A = a:"a" A:A? b:"b" { return [a, A, b].join(""); }',
              'B = b:"b" B:B? c:"c" { return [b, B, c].join(""); }'
            ].join("\n"), options);

        expect(parser).toParse("abc",       "abc");
        expect(parser).toParse("aaabbbccc", "aaabbbccc");
        expect(parser).toFailToParse("aabbbccc");
        expect(parser).toFailToParse("aaaabbbccc");
        expect(parser).toFailToParse("aaabbccc");
        expect(parser).toFailToParse("aaabbbbccc");
        expect(parser).toFailToParse("aaabbbcc");
        expect(parser).toFailToParse("aaabbbcccc");
      });

      it("handles nested comments example correctly", function() {
        /*
         * Begin ← "(*"
         * End ← "*)"
         * C ← Begin N* End
         * N ← C / (!Begin !End Z)
         * Z ← any single character
         */
        var parser = PEG.buildParser([
              'C     = begin:Begin ns:N* end:End { return begin + ns.join("") + end; }',
              'N     = C',
              '      / !Begin !End z:Z { return z; }',
              'Z     = .',
              'Begin = "(*"',
              'End   = "*)"'
            ].join("\n"), options);

        expect(parser).toParse("(**)",     "(**)");
        expect(parser).toParse("(*abc*)",  "(*abc*)");
        expect(parser).toParse("(*(**)*)", "(*(**)*)");
        expect(parser).toParse(
          "(*abc(*def*)ghi(*(*(*jkl*)*)*)mno*)",
          "(*abc(*def*)ghi(*(*(*jkl*)*)*)mno*)"
        );
      });
    });
  });
});


text:
package install

import (
	"code.gitea.io/gitea/models/db"
	"code.gitea.io/gitea/modules/setting"

	"xorm.io/xorm"
)

func getXORMEngine() *xorm.Engine {
	return db.DefaultContext.(*db.Context).Engine().(*xorm.Engine)
}

// CheckDatabaseConnection checks the database connection
func CheckDatabaseConnection() error {
	e := db.GetEngine(db.DefaultContext)
	_, err := e.Exec("SELECT 1")
	return err
}

// GetMigrationVersion gets the database migration version
func GetMigrationVersion() (int64, error) {
	var installedDbVersion int64
	x := getXORMEngine()
	exist, err := x.IsTableExist("version")
	if err != nil {
		return 0, err
	}
	if !exist {
		return 0, nil
	}
	_, err = x.Table("version").Cols("version").Get(&installedDbVersion)
	if err != nil {
		return 0, err
	}
	return installedDbVersion, nil
}

// HasPostInstallationUsers checks whether there are users after installation
func HasPostInstallationUsers() (bool, error) {
	x := getXORMEngine()
	exist, err := x.IsTableExist("user")
	if err != nil {
		return false, err
	}
	if !exist {
		return false, nil
	}

	// if there are 2 or more users in database, we consider there are users created after installation
	threshold := 2
	if !setting.IsProd {
		// to debug easily, with non-prod RUN_MODE, we only check the count to 1
		threshold = 1
	}
	res, err := x.Table("user").Cols("id").Limit(threshold).Query()
	if err != nil {
		return false, err
	}
	return len(res) >= threshold, nil
}

redpajama_set_name: RedPajamaGithub


text:
require_relative '../../../../spec_helper'

describe 'base::screen', :type => :class do

  it { is_expected.to compile }

  it { is_expected.to compile.with_all_deps }

  it { is_expected.to contain_class('base::screen') }
end


text:
import __builtin__
import __future__
import functools
import imp
import inspect
import json
from pathlib import Path
import optparse
import os
import os.path
import subprocess
import sys

# When build files are executed, the functions in this file tagged with
# @provide_for_build will be provided in the build file's local symbol table.
#
# When these functions are called from a build file, they will be passed
# a keyword parameter, build_env, which is a object with information about
# the environment of the build file which is currently being processed.
# It contains the following attributes:
#
# "dirname" - The directory containing the build file.
#
# "base_path" - The base path of the build file.

BUILD_FUNCTIONS = []

class SyncCookieState(object):
    """
    Process-wide state used to enable Watchman sync cookies only on
    the first query issued.
    """

    def __init__(self):
        self.use_sync_cookies = True

class BuildContextType(object):

    """
    Identifies the type of input file to the processor.
    """

    BUILD_FILE = 'build_file'
    INCLUDE = 'include'

class BuildFileContext(object):
    """
    The build context used when processing a build file.
    """

    type = BuildContextType.BUILD_FILE

    def __init__(self, base_path, dirname, allow_empty_globs, watchman_client,
                 watchman_watch_root, watchman_project_prefix, sync_cookie_state,
                 watchman_error):
        self.globals = {}
        self.includes = set()
        self.base_path = base_path
        self.dirname = dirname
        self.allow_empty_globs = allow_empty_globs
        self.watchman_client = watchman_client
        self.watchman_watch_root = watchman_watch_root
        self.watchman_project_prefix = watchman_project_prefix
        self.sync_cookie_state = sync_cookie_state
        self.watchman_error = watchman_error
        self.rules = {}

class IncludeContext(object):
    """
    The build context used when processing an include.
    """

    type = BuildContextType.INCLUDE

    def __init__(self):
        self.globals = {}
        self.includes = set()

class LazyBuildEnvPartial(object):
    """Pairs a function with a build environment in which it will be executed.

    Note that while the function is specified via the constructor, the build
    environment must be assigned after construction, for the build environment
    currently being used.

    To call the function with its build environment, use the invoke() method of
    this class, which will forward the arguments from invoke() to the
    underlying function.
    """

    def __init__(self, func):
        self.func = func
        self.build_env = None

    def invoke(self, *args, **kwargs):
        """Invokes the bound function injecting 'build_env' into **kwargs."""
        updated_kwargs = kwargs.copy()
        updated_kwargs.update({'build_env': self.build_env})
        return self.func(*args, **updated_kwargs)

def provide_for_build(func):
    BUILD_FUNCTIONS.append(func)
    return func

def add_rule(rule, build_env):
    assert build_env.type == BuildContextType.BUILD_FILE, (
        "Cannot use `{}()` at the top-level of an included file."
        .format(rule['buck.type']))

    # Include the base path of the BUILD file so the reader consuming this
    # JSON will know which BUILD file the rule came from.
    if 'name' not in rule:
        raise ValueError(
            'rules must contain the field \'name\'.  Found %s.' % rule)
    rule_name = rule['name']
    if rule_name in build_env.rules:
        raise ValueError('Duplicate rule definition found.  Found %s and %s' %
                         (rule, build_env.rules[rule_name]))
    rule['buck.base_path'] = build_env.base_path
    build_env.rules[rule_name] = rule

class memoized(object):
    '''Decorator. Caches a function's return value each time it is called.
    If called later with the same arguments, the cached value is returned
    (not reevaluated).
    '''
    def __init__(self, func):
        self.func = func
        self.cache = {}

    def __call__(self, *args):
        args_key = repr(args)
        if args_key in self.cache:
            return self.cache[args_key]
        else:
            value = self.func(*args)
            self.cache[args_key] = value
            return value

    def __repr__(self):
        '''Return the function's docstring.'''
        return self.func.__doc__

    def __get__(self, obj, objtype):
        '''Support instance methods.'''
        return functools.partial(self.__call__, obj)

@provide_for_build
def glob(includes, excludes=[], include_dotfiles=False, build_env=None):
    assert build_env.type == BuildContextType.BUILD_FILE, (
        "Cannot use `glob()` at the top-level of an included file.")
    # Ensure the user passes lists of strings rather than just a string.
    assert not isinstance(includes, basestring), \
        "The first argument to glob() must be a list of strings."
    assert not isinstance(excludes, basestring), \
        "The excludes argument must be a list of strings."

    results = None
    if not includes:
        results = []
    elif build_env.watchman_client:
        try:
            results = glob_watchman(
                includes,
                excludes,
                include_dotfiles,
                build_env.base_path,
                build_env.watchman_watch_root,
                build_env.watchman_project_prefix,
                build_env.sync_cookie_state,
                build_env.watchman_client)
        except build_env.watchman_error, e:
            print >>sys.stderr, 'Watchman error, falling back to slow glob: ' + str(e)
            try:
                build_env.watchman_client.close()
            except:
                pass
            build_env.watchman_client = None

    if results is None:
        search_base = Path(build_env.dirname)
        results = glob_internal(
            includes,
            excludes,
            include_dotfiles,
            search_base)
    assert build_env.allow_empty_globs or results, (
        "glob(includes={includes}, excludes={excludes}, include_dotfiles={include_dotfiles}) " +
        "returned no results.  (allow_empty_globs is set to false in the Buck " +
        "configuration)").format(
            includes=includes,
            excludes=excludes,
            include_dotfiles=include_dotfiles)

    return results

def format_watchman_query_params(includes, excludes, include_dotfiles, relative_root):
    match_exprs = ["allof", "exists", ["anyof", ["type", "f"], ["type", "l"]]]
    match_flags = {}
    if include_dotfiles:
        match_flags["includedotfiles"] = True
    if includes:
        match_exprs.append(
            ["anyof"] + [["match", i, "wholename", match_flags] for i in includes])
    if excludes:
        match_exprs.append(
            ["not",
                ["anyof"] + [["match", x, "wholename", match_flags] for x in excludes]])

    return {
        "relative_root": relative_root,
        # Explicitly pass an empty path so Watchman queries only the tree of files
        # starting at base_path.
        "path": [''],
        "fields": ["name"],
        "expression": match_exprs,
    }

@memoized
def glob_watchman(includes, excludes, include_dotfiles, base_path, watchman_watch_root,
                  watchman_project_prefix, sync_cookie_state, watchman_client):
    assert includes, "The includes argument must be a non-empty list of strings."

    if watchman_project_prefix:
        relative_root = os.path.join(watchman_project_prefix, base_path)
    else:
        relative_root = base_path
    query_params = format_watchman_query_params(
        includes, excludes, include_dotfiles, relative_root)

    # Sync cookies cause a massive overhead when issuing thousands of
    # glob queries.  Only enable them (by not setting sync_timeout to 0)
    # for the very first request issued by this process.
    if sync_cookie_state.use_sync_cookies:
        sync_cookie_state.use_sync_cookies = False
    else:
        query_params["sync_timeout"] = 0

    query = ["query", watchman_watch_root, query_params]
    res = watchman_client.query(*query)
    if res.get('warning'):
        print >> sys.stderr, 'Watchman warning from query {}: {}'.format(
            query,
            res.get('warning'))
    result = res.get('files', [])
    return sorted(result)

def glob_internal(includes, excludes, include_dotfiles, search_base):

    def includes_iterator():
        for pattern in includes:
            for path in search_base.glob(pattern):
                # TODO(user): Handle hidden files on Windows.
                if path.is_file() and (include_dotfiles or not path.name.startswith('.')):
                    yield path.relative_to(search_base)

    def is_special(pat):
        return "*" in pat or "?" in pat or "[" in pat

    non_special_excludes = set()
    match_excludes = set()
    for pattern in excludes:
        if is_special(pattern):
            match_excludes.add(pattern)
        else:
            non_special_excludes.add(pattern)

    def exclusion(path):
        if path.as_posix() in non_special_excludes:
            return True
        for pattern in match_excludes:
            result = path.match(pattern, match_entire=True)
            if result:
                return True
        return False

    return sorted(set([str(p) for p in includes_iterator() if not exclusion(p)]))

@provide_for_build
def get_base_path(build_env=None):
    """Get the base path to the build file that was initially evaluated.

    This function is intended to be used from within a build defs file that
    likely contains macros that could be called from any build file.
    Such macros may need to know the base path of the file in which they
    are defining new build rules.

    Returns: a string, such as "java/com/facebook". Note there is no
             trailing slash. The return value will be "" if called from
             the build file in the root of the project.
    """
    assert build_env.type == BuildContextType.BUILD_FILE, (
        "Cannot use `get_base_path()` at the top-level of an included file.")
    return build_env.base_path

@provide_for_build
def add_deps(name, deps=[], build_env=None):
    assert build_env.type == BuildContextType.BUILD_FILE, (
        "Cannot use `add_deps()` at the top-level of an included file.")

    if name not in build_env.rules:
        raise ValueError(
            'Invoked \'add_deps\' on non-existent rule %s.' % name)

    rule = build_env.rules[name]
    if 'deps' not in rule:
        raise ValueError(
            'Invoked \'add_deps\' on rule %s that has no \'deps\' field'
            % name)
    rule['deps'] = rule['deps'] + deps

class BuildFileProcessor(object):

    def __init__(self, project_root, watchman_watch_root, watchman_project_prefix, build_file_name,
                 allow_empty_globs, watchman_client, watchman_error, implicit_includes=[],
                 extra_funcs=[]):
        self._cache = {}
        self._build_env_stack = []
        self._sync_cookie_state = SyncCookieState()

        self._project_root = project_root
        self._watchman_watch_root = watchman_watch_root
        self._watchman_project_prefix = watchman_project_prefix
        self._build_file_name = build_file_name
        self._implicit_includes = implicit_includes
        self._allow_empty_globs = allow_empty_globs
        self._watchman_client = watchman_client
        self._watchman_error = watchman_error

        lazy_functions = {}
        for func in BUILD_FUNCTIONS + extra_funcs:
            func_with_env = LazyBuildEnvPartial(func)
            lazy_functions[func.__name__] = func_with_env
        self._functions = lazy_functions

    def _merge_globals(self, mod, dst):
        """
        Copy the global definitions from one globals dict to another.

        Ignores special attributes and attributes starting with '_', which
        typically denote module-level private attributes.
        """

        hidden = set([
            'include_defs',
        ])

        keys = getattr(mod, '__all__', mod.__dict__.keys())

        for key in keys:
            if not key.startswith('_') and key not in hidden:
                dst[key] = mod.__dict__[key]

    def _update_functions(self, build_env):
        """
        Updates the build functions to use the given build context when called.
        """

        for function in self._functions.itervalues():
            function.build_env = build_env

    def install_builtins(self, namespace):
        """
        Installs the build functions, by their name, into the given namespace.
        """

        for name, function in self._functions.iteritems():
            namespace[name] = function.invoke

    def _get_include_path(self, name):
        """
        Resolve the given include def name to a full path.
        """

        # Find the path from the include def name.
        if not name.startswith('//'):
            raise ValueError(
                'include_defs argument "%s" must begin with //' % name)
        relative_path = name[2:]
        return os.path.join(self._project_root, relative_path)

    def _include_defs(self, name, implicit_includes=[]):
        """
        Pull the named include into the current caller's context.

        This method is meant to be installed into the globals of any files or
        includes that we process.
        """

        # Grab the current build context from the top of the stack.
        build_env = self._build_env_stack[-1]

        # Resolve the named include to its path and process it to get its
        # build context and module.
        path = self._get_include_path(name)
        inner_env, mod = self._process_include(
            path,
            implicit_includes=implicit_includes)

        # Look up the caller's stack frame and merge the include's globals
        # into it's symbol table.
        frame = inspect.currentframe()
        while frame.f_globals['__name__'] == __name__:
            frame = frame.f_back
        self._merge_globals(mod, frame.f_globals)

        # Pull in the include's accounting of its own referenced includes
        # into the current build context.
        build_env.includes.add(path)
        build_env.includes.update(inner_env.includes)

    def _push_build_env(self, build_env):
        """
        Set the given build context as the current context.
        """

        self._build_env_stack.append(build_env)
        self._update_functions(build_env)

    def _pop_build_env(self):
        """
        Restore the previous build context as the current context.
        """

        self._build_env_stack.pop()
        if self._build_env_stack:
            self._update_functions(self._build_env_stack[-1])

    def _process(self, build_env, path, implicit_includes=[]):
        """
        Process a build file or include at the given path.
        """

        # First check the cache.
        cached = self._cache.get(path)
        if cached is not None:
            return cached

        # Install the build context for this input as the current context.
        self._push_build_env(build_env)

        # The globals dict that this file will be executed under.
        default_globals = {}

        # Install the 'include_defs' function into our global object.
        default_globals['include_defs'] = functools.partial(
            self._include_defs,
            implicit_includes=implicit_includes)

        # If any implicit includes were specified, process them first.
        for include in implicit_includes:
            include_path = self._get_include_path(include)
            inner_env, mod = self._process_include(include_path)
            self._merge_globals(mod, default_globals)
            build_env.includes.add(include_path)
            build_env.includes.update(inner_env.includes)

        # Build a new module for the given file, using the default globals
        # created above.
        module = imp.new_module(path)
        module.__file__ = path
        module.__dict__.update(default_globals)

        with open(path) as f:
            contents = f.read()

        # Enable absolute imports.  This prevents the compiler from trying to
        # do a relative import first, and warning that this module doesn't
        # exist in sys.modules.
        future_features = __future__.absolute_import.compiler_flag
        code = compile(contents, path, 'exec', future_features, 1)
        exec(code, module.__dict__)

        # Restore the previous build context.
        self._pop_build_env()

        self._cache[path] = build_env, module
        return build_env, module

    def _process_include(self, path, implicit_includes=[]):
        """
        Process the include file at the given path.
        """

        build_env = IncludeContext()
        return self._process(
            build_env,
            path,
            implicit_includes=implicit_includes)

    def _process_build_file(self, path, implicit_includes=[]):
        """
        Process the build file at the given path.
        """

        # Create the build file context, including the base path and directory
        # name of the given path.
        relative_path_to_build_file = os.path.relpath(
            path, self._project_root).replace('\\', '/')
        len_suffix = -len('/' + self._build_file_name)
        base_path = relative_path_to_build_file[:len_suffix]
        dirname = os.path.dirname(path)
        build_env = BuildFileContext(
            base_path,
            dirname,
            self._allow_empty_globs,
            self._watchman_client,
            self._watchman_watch_root,
            self._watchman_project_prefix,
            self._sync_cookie_state,
            self._watchman_error)

        return self._process(
            build_env,
            path,
            implicit_includes=implicit_includes)

    def process(self, path):
        """
        Process a build file returning a dict of it's rules and includes.
        """
        build_env, mod = self._process_build_file(
            os.path.join(self._project_root, path),
            implicit_includes=self._implicit_includes)
        values = build_env.rules.values()
        values.append({"__includes": [path] + sorted(build_env.includes)})
        return values

def cygwin_adjusted_path(path):
    if sys.platform == 'cygwin':
        return subprocess.check_output(['cygpath', path]).rstrip()
    else:
        return path

# Inexplicably, this script appears to run faster when the arguments passed
# into it are absolute paths. However, we want the "buck.base_path" property
# of each rule to be printed out to be the base path of the build target that
# identifies the rule. That means that when parsing a BUILD file, we must know
# its path relative to the root of the project to produce the base path.
#
# To that end, the first argument to this script must be an absolute path to
# the project root.  It must be followed by one or more absolute paths to
# BUILD files under the project root.  If no paths to BUILD files are
# specified, then it will traverse the project root for BUILD files, excluding
# directories of generated files produced by Buck.
#
# All of the build rules that are parsed from the BUILD files will be printed
# to stdout by a JSON parser. That means that printing out other information
# for debugging purposes will likely break the JSON parsing, so be careful!

def main():
    # Our parent expects to read JSON from our stdout, so if anyone
    # uses print, buck will complain with a helpful "but I wanted an
    # array!" message and quit.  Redirect stdout to stderr so that
    # doesn't happen.  Actually dup2 the file handle so that writing
    # to file descriptor 1, os.system, and so on work as expected too.

    to_parent = os.fdopen(os.dup(sys.stdout.fileno()), 'a')
    os.dup2(sys.stderr.fileno(), sys.stdout.fileno())

    parser = optparse.OptionParser()
    parser.add_option(
        '--project_root',
        action='store',
        type='string',
        dest='project_root')
    parser.add_option(
        '--build_file_name',
        action='store',
        type='string',
        dest="build_file_name")
    parser.add_option(
        '--allow_empty_globs',
        action='store_true',
        dest='allow_empty_globs',
        help='Tells the parser not to raise an error when glob returns no results.')
    parser.add_option(
        '--use_watchman_glob',
        action='store_true',
        dest='use_watchman_glob',
        help='Invokes `watchman query` to get lists of files instead of globbing in-process.')
    parser.add_option(
        '--watchman_watch_root',
        action='store',
        type='string',
        dest='watchman_watch_root',
        help='Path to root of watchman watch as returned by `watchman watch-project`.')
    parser.add_option(
        '--watchman_project_prefix',
        action='store',
        type='string',
        dest='watchman_project_prefix',
        help='Relative project prefix as returned by `watchman watch-project`.')
    parser.add_option(
        '--watchman_query_timeout_ms',
        action='store',
        type='int',
        dest='watchman_query_timeout_ms',
        help='Maximum time in milliseconds to wait for watchman query to respond.')
    parser.add_option(
        '--include',
        action='append',
        dest='include')
    (options, args) = parser.parse_args()

    # Even though project_root is absolute path, it may not be concise. For
    # example, it might be like "C:\project\.\rule".
    #
    # Under cygwin, the project root will be invoked from buck as C:\path, but
    # the cygwin python uses UNIX-style paths. They can be converted using
    # cygpath, which is necessary because abspath will treat C:\path as a
    # relative path.
    options.project_root = cygwin_adjusted_path(options.project_root)
    project_root = os.path.abspath(options.project_root)

    watchman_client = None
    watchman_error = None
    output_format = 'JSON'
    output_encode = lambda val: json.dumps(val, sort_keys=True)
    if options.use_watchman_glob:
        try:
            # pywatchman may not be built, so fall back to non-watchman
            # in that case.
            import pywatchman
            client_args = {}
            if options.watchman_query_timeout_ms is not None:
                # pywatchman expects a timeout as a nonnegative floating-point
                # value in seconds.
                client_args['timeout'] = max(0.0, options.watchman_query_timeout_ms / 1000.0)
            watchman_client = pywatchman.client(**client_args)
            watchman_error = pywatchman.WatchmanError
            output_format = 'BSER'
            output_encode = lambda val: pywatchman.bser.dumps(val)
        except ImportError, e:
            # TODO(agallagher): Restore this when the PEX builds pywatchman.
            # print >> sys.stderr, \
            #     'Could not import pywatchman (sys.path {}): {}'.format(
            #         sys.path,
            #         repr(e))
            pass

    buildFileProcessor = BuildFileProcessor(
        project_root,
        options.watchman_watch_root,
        options.watchman_project_prefix,
        options.build_file_name,
        options.allow_empty_globs,
        watchman_client,
        watchman_error,
        implicit_includes=options.include or [])

    buildFileProcessor.install_builtins(__builtin__.__dict__)

    to_parent.write(output_format + '\n')
    to_parent.flush()

    for build_file in args:
        build_file = cygwin_adjusted_path(build_file)
        values = buildFileProcessor.process(build_file)
        to_parent.write(output_encode(values))
        to_parent.flush()

    # "for ... in sys.stdin" in Python 2.x hangs until stdin is closed.
    for build_file in iter(sys.stdin.readline, ''):
        build_file = cygwin_adjusted_path(build_file)
        values = buildFileProcessor.process(build_file.rstrip())
        to_parent.write(output_encode(values))
        to_parent.flush()

    # Python tries to flush/close stdout when it quits, and if there's a dead
    # pipe on the other end, it will spit some warnings to stderr. This breaks
    # tests sometimes. Prevent that by explicitly catching the error.
    try:
        to_parent.close()
    except IOError:
        pass


text:
namespace safe_json {

class SafeJsonParserAndroid : public SafeJsonParser {
 public:
  SafeJsonParserAndroid(const std::string& unsafe_json,
                        const SuccessCallback& success_callback,
                        const ErrorCallback& error_callback);

 private:
  friend std::default_delete<SafeJsonParserAndroid>;

  ~SafeJsonParserAndroid() override;

  void OnSanitizationSuccess(const std::string& sanitized_json);
  void OnSanitizationError(const std::string& error);

  // SafeJsonParser implementation.
  void Start() override;

  const std::string unsafe_json_;
  SuccessCallback success_callback_;
  ErrorCallback error_callback_;

  DISALLOW_COPY_AND_ASSIGN(SafeJsonParserAndroid);
};

}  // namespace safe_json

#endif   // COMPONENTS_SAFE_JSON_SAFE_JSON_PARSER_ANDROID_H_


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _objectWithoutProperties2 = require('babel-runtime/helpers/objectWithoutProperties');

var _objectWithoutProperties3 = _interopRequireDefault(_objectWithoutProperties2);

var _simpleAssign = require('simple-assign');

var _simpleAssign2 = _interopRequireDefault(_simpleAssign);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _propTypes = require('prop-types');

var _propTypes2 = _interopRequireDefault(_propTypes);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Subheader = function Subheader(props, context) {
  var children = props.children,
      inset = props.inset,
      style = props.style,
      other = (0, _objectWithoutProperties3.default)(props, ['children', 'inset', 'style']);
  var _context$muiTheme = context.muiTheme,
      prepareStyles = _context$muiTheme.prepareStyles,
      subheader = _context$muiTheme.subheader;

  var styles = {
    root: {
      boxSizing: 'border-box',
      color: subheader.color,
      fontSize: 14,
      fontWeight: subheader.fontWeight,
      lineHeight: '48px',
      paddingLeft: inset ? 72 : 16,
      width: '100%'
    }
  };

  return _react2.default.createElement(
    'div',
    (0, _extends3.default)({}, other, { style: prepareStyles((0, _simpleAssign2.default)(styles.root, style)) }),
    children
  );
};

Subheader.muiName = 'Subheader';

Subheader.propTypes = process.env.NODE_ENV !== "production" ? {
  /**
   * Node that will be placed inside the `Subheader`.
   */
  children: _propTypes2.default.node,
  /**
   * If true, the `Subheader` will be indented.
   */
  inset: _propTypes2.default.bool,
  /**
   * Override the inline-styles of the root element.
   */
  style: _propTypes2.default.object
} : {};

Subheader.defaultProps = {
  inset: false
};

Subheader.contextTypes = {
  muiTheme: _propTypes2.default.object.isRequired
};

exports.default = Subheader;


text:
<?php

namespace Intervention\Image\Imagick\Commands;

class MaskCommand extends \Intervention\Image\Commands\AbstractCommand
{
    /**
     * Applies an alpha mask to an image
     *
     * @param  \Intervention\Image\Image $image
     * @return boolean
     */
    public function execute($image)
    {
        $mask_source = $this->argument(0)->value();
        $mask_w_alpha = $this->argument(1)->type('bool')->value(false);

        // get imagick
        $imagick = $image->getCore();

        // build mask image from source
        $mask = $image->getDriver()->init($mask_source);

        // resize mask to size of current image (if necessary)
        $image_size = $image->getSize();
        if ($mask->getSize() != $image_size) {
            $mask->resize($image_size->width, $image_size->height);
        }

        $imagick->setImageMatte(true);

        if ($mask_w_alpha) {

            // just mask with alpha map
            $imagick->compositeImage($mask->getCore(), \Imagick::COMPOSITE_DSTIN, 0, 0);

        } else {

            // get alpha channel of original as greyscale image
            $original_alpha = clone $imagick;
            $original_alpha->separateImageChannel(\Imagick::CHANNEL_ALPHA);

            // use red channel from mask ask alpha
            $mask_alpha = clone $mask->getCore();
            $mask_alpha->compositeImage($mask->getCore(), \Imagick::COMPOSITE_DEFAULT, 0, 0);
            // $mask_alpha->setImageAlphaChannel(\Imagick::ALPHACHANNEL_DEACTIVATE);
            $mask_alpha->separateImageChannel(\Imagick::CHANNEL_ALL);

            // combine both alphas from original and mask
            $original_alpha->compositeImage($mask_alpha, \Imagick::COMPOSITE_COPYOPACITY, 0, 0);

            // mask the image with the alpha combination
            $imagick->compositeImage($original_alpha, \Imagick::COMPOSITE_DSTIN, 0, 0);
        }

        return true;
    }
}


text:
@interface UIImageView (Common)

@end


text:
'use strict';

// TODO put this in a separate project on github
const all = require('../data/all-languages.json');
const withIETF = all.filter(lang => (typeof lang.ietf === 'string'));
const byIETF = {};
module.exports = {
  all: all,
  withIETF: withIETF,
  byIETF: byIETF
}

withIETF.forEach(language => {
  byIETF[language.ietf] = language;
})


text:
require "language_pack/base"

# This file is automatically generated by rake
module LanguagePack
  class LanguagePack::Base
    VERSION_FILE = File.expand_path('../../../VERSION', __FILE__)
    CF_BUILDPACK_VERSION = File.readlines(VERSION_FILE).first.chomp
    BUILDPACK_VERSION = "v146"
  end
end


text:
TaskClass = {}
TaskClass.__index = TaskClass

function TaskClass.new(equipment, owner)
  assert(action)

  local instance = {}
  setmetatable(instance, TaskClass)
  instance.equipment = equipment
  instance.owner = owner
  return instance
end

function TaskClass:done()
  assert(false, "Task doesn't implement done()")
end

-- Defaults to 'nil' (no task list description)
function TaskClass:description()
  return nil
end

function TaskClass:update(dt)
  assert(false, "Task doesn't implement update(dt)")
end

function TaskClass:draw()
  assert(false, "Task doesn't implement draw()")
end


text:
class ObservablesController < ComponentsController

  def index
    @components = Observable.all.group_by {|o|
      if o.object.present?
        component_title(o.object.properties.class)
      else
        'Event'
      end
    }
  end

  def klass
    Observable
  end
end


text:
'use strict';

//Registrants service used for communicating with the registrants REST endpoints
angular.module('registrants').factory('Registrants', ['$resource',
  function ($resource) {
    return $resource('api/registrants/:registrantId', {
      registrantId: '@_id'
    }, {
      update: {
        method: 'PUT'
      }
    });
  }
]);


text:
import _ from 'lodash';
import Job from '../models/jobs';
import User from '../models/user'
import Application from '../models/apps'
import moment from 'moment'

/**
 * List
 */
export function all(req, res) {
  Job.find({}).exec((err, data) => {
    if (err) {
      console.log('Error in first query');
      return res.status(500).send('Something went wrong getting the data');
    }

    let appHash = {}
    Application.find({}).exec((err, apps) => {
      apps.forEach((element) => {
        appHash[element.company._id] = element.company._id
      })
      const result = data.filter((posting) => {
        return !appHash[posting._id]
      })

       return res.json(result.slice(0,30))
    })
  });
}

/**
 * Interested! Queue it up
 */
export function addQueue(req, res) {
  let app = req.body
  app.user = req.user._id

  Application.create(app, (err) => {
    if (err) {
      console.log(err);
      return res.status(400).send(err);
    }

    Application.find({'user': req.user._id}).exec((err, data) => {
      if(err) {
        return res.status(400).send(err)
      }

      return res.status(200).send(
        data.filter((ele) => {
          return ele.interest > 0
        })
      );
    })
  });
}

/**
 * Update a topic
 */
export function addNope(req, res) {
  const query = { 'company._id' : req.params.id, user: req.user._id};
  let status = {
    queue: false,
    offer: false,
    phone: false,
    apply: false,
    nope: true,
    nopeDate: moment()
  }

  //posting id
  //date of nope
  //any other info attached to it

  Application.update(query, {'$set': {'user': req.user._id}, '$set': {'interest': 0}}, {upsert: true}, (err, data) => {
    if (err) {
      console.log("done goofed bro", err)
    }
    Application.find({'user': req.user._id, 'interest': {'$gt': 0}}).exec((err, data) => {
      if(err) {
        return res.status(400).send(err)
      }
      res.status(200).send(data.filter((ele) => {
          return ele.interest > 0
        })
      )
  })
  }
)}

/**
 * Remove a topic
 */
export function remove(req, res) {
  const query = { id: req.params.id };
  Topic.findOneAndRemove(query, (err) => {
    if (err) {
      console.log('Error on delete');
      return res.status(500).send('We failed to delete for some reason');
    }

    return res.status(200).send('Removed Successfully');
  });
}

export default {
  all,
  addQueue,
  addNope,
  remove
};


text:
using System;
using NUnit.Framework;
using Moq;
using OutsuranceAssessment.Helpers.Interfaces;
using OutsuranceAssessment.Helpers;
using OutsuranceAssessment.Models;
using System.Collections.Generic;

namespace OutsuranceAssessment.Test
{
    //[SetUpFixture]
    public class PeopleAnalysis_UnitTests
    {
        public static string[] SampleArray1 = { "Reuel", "Lawrence", "22 Helmcroft Cresent" };
        public static string[] SampleArray2 = { "Christina", "Lawrence", "342 Hillgrove Drive" };

        private static List<Person> _people;

        private IPersonHelper _personHelper;
        private IUtilities _utilities;
        private IFileHelper _fileHelper;

        [OneTimeSetUp]
        public void Setup()
        {
            _personHelper = new PersonHelper();
            _utilities = new Utilities();
            _fileHelper = new FileHelper();

            _people = new List<Person>();
            _people.Add(new Person
            {
                FirstName = "Reuel",
                LastName = "Lawrence",
                Address = "22 Helmcroft Crescent"
            });
            _people.Add(new Person
            {
                FirstName = "Christina",
                LastName = "Lawrence",
                Address = "342 Allgrove drive"
            });
        }

        [TestCase(new string[] { "Christina", "Lawrence", "22 Helmcroft Crescent" }, 0, "Christina")]
        [TestCase(new string[] { "Christina", "Lawrence", "22 Helmcroft Crescent" }, 1, "Lawrence")]
        [TestCase(new string[] { "Christina", "Lawrence", "22 Helmcroft Crescent" }, 2, "22 Helmcroft Crescent")]
        [TestCase(new string[] { "Christina", "Lawrence", "22 Helmcroft Crescent" }, 3, "")]
        public void GetPersonItem_ThreeItems_GetItem(string[] itemArray, int index, string expectedValue)
        {
            var actualResult = _utilities.GetArrayItem(itemArray, index);

            Assert.That(expectedValue, Is.EqualTo(actualResult));
        }

        [Test]
        public void GetPersonItem_NegativeIndex_ThrowsException()
        {
            Assert.Throws<ArgumentException>(() => _utilities.GetArrayItem(new string[] { }, -1));
        }

        [Test]
        public void CreatePerson_ReturnsPersonObject()
        {
            var actualResult = _personHelper.CreatePerson(SampleArray1);

            var expectedResult = new Person
            {
                FirstName = "Reuel",
                LastName = "Lawrence",
                Address = "22 Helmcroft Cresent"
            };

            Assert.That(expectedResult, NUnit.DeepObjectCompare.Is.DeepEqualTo(actualResult));
        }

        [Test]
        public void CreatePerson_Calls_GetArrayItem()
        {
            var mockUtilities = new Mock<IUtilities>();
            var personHelper = new PersonHelper(mockUtilities.Object);
            var person = personHelper.CreatePerson(SampleArray1);
            mockUtilities.Verify(m => m.GetArrayItem(SampleArray1, It.IsAny<int>()), Times.Exactly(3));
        }

        [Test]
        public void GetPersonName_AggretatesCorrectly()
        {
            var actualResult = _personHelper.GetPersonNames(_people);

            var expectedResult = new List<PersonName>();
            expectedResult.Add(new PersonName
            {
                Name = "Lawrence",
                Count = 2
            });
            expectedResult.Add(new PersonName
            {
                Name = "Christina",
                Count = 1
            });
            expectedResult.Add(new PersonName
            {
                Name = "Reuel",
                Count = 1
            });

            Assert.That(expectedResult, NUnit.DeepObjectCompare.Is.DeepEqualTo(actualResult));
        }

        [Test]
        public void GetPersonAddress_SortsCorrectly()
        {
            var actualResult = _personHelper.GetPersonAddresses(_people);

            var expectedResult = new List<PersonAddress>();
            expectedResult.Add(new PersonAddress
            {
                Street = "342 Allgrove drive"
            });
            expectedResult.Add(new PersonAddress
            {
                Street = "22 Helmcroft Crescent"
            });

            Assert.That(expectedResult, NUnit.DeepObjectCompare.Is.DeepEqualTo(actualResult));
        }
    }
}


text:
package discovery

import (
	"github.com/micro/go-micro/cmd"
	"github.com/micro/go-micro/registry"
)

const (
	HeartbeatTopic = "micro.discovery.heartbeat"
)

// Discovery builds on the registry for heartbeating and client side caching
type Discovery interface {
	Close() error
	registry.Registry
}

func init() {
	cmd.DefaultRegistries["os"] = NewRegistry
}

func NewDiscovery(opts ...registry.Option) Discovery {
	return newOS(opts...)
}

func NewRegistry(opts ...registry.Option) registry.Registry {
	return newOS(opts...)
}